From 8f2129e2f916dbf4543a0a76bd710f4b45836c34 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 001/199] chore: move to TypeScript with pnpm, ESLint, Prettier and Vitest --- .prettierignore | 6 + .prettierrc.json | 21 + eslint.config.ts | 391 +++++ package-lock.json | 321 ---- package.json | 57 +- pnpm-lock.yaml | 3852 +++++++++++++++++++++++++++++++++++++++++++ pnpm-workspace.yaml | 2 + src/reset.d.ts | 1 + tsconfig.build.json | 11 + tsconfig.json | 24 + vitest.config.ts | 10 + 11 files changed, 4366 insertions(+), 330 deletions(-) create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 eslint.config.ts delete mode 100644 package-lock.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 src/reset.d.ts create mode 100644 tsconfig.build.json create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..fa71a2d --- /dev/null +++ b/.prettierignore @@ -0,0 +1,6 @@ +node_modules +dist +coverage +pnpm-lock.yaml +drizzle/meta +PLAN.md diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..9b9108e --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,21 @@ +{ + "singleQuote": true, + "semi": true, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "trailingComma": "all", + "bracketSpacing": true, + "bracketSameLine": false, + "arrowParens": "always", + "objectWrap": "preserve", + "endOfLine": "lf", + "overrides": [ + { + "files": ["*.scss", "*.sass"], + "options": { + "useTabs": true + } + } + ] +} diff --git a/eslint.config.ts b/eslint.config.ts new file mode 100644 index 0000000..208becd --- /dev/null +++ b/eslint.config.ts @@ -0,0 +1,391 @@ +import js from '@eslint/js'; +import type { Linter } from 'eslint'; +import { defineConfig, globalIgnores } from 'eslint/config'; +import tseslint from 'typescript-eslint'; +import sonarjs from 'eslint-plugin-sonarjs'; +import unicorn from 'eslint-plugin-unicorn'; +import prettier from 'eslint-config-prettier'; +import globals from 'globals'; +import importX from 'eslint-plugin-import-x'; +import { createTypeScriptImportResolver } from 'eslint-import-resolver-typescript'; + +const javascriptFiles = ['**/*.{js,mjs,cjs,jsx}']; +const typescriptFiles = ['**/*.{ts,mts,cts,tsx}']; +const sourceFiles = [...javascriptFiles, ...typescriptFiles]; + +const qualityRules: Linter.RulesRecord = { + 'no-alert': 'error', + 'no-console': ['warn', { allow: ['warn', 'error'] }], + 'no-debugger': 'error', + 'no-eval': 'error', + 'no-implied-eval': 'error', + 'no-new-func': 'error', + 'no-new-wrappers': 'error', + 'no-unsafe-optional-chaining': 'error', + 'no-constant-binary-expression': 'error', + 'no-promise-executor-return': 'error', + 'no-async-promise-executor': 'error', + 'no-unmodified-loop-condition': 'error', + 'no-unreachable-loop': 'error', + 'no-template-curly-in-string': 'error', + 'no-useless-call': 'error', + 'no-useless-concat': 'error', + 'no-useless-return': 'error', + 'no-else-return': 'error', + 'no-lonely-if': 'error', + 'no-param-reassign': 'error', + 'no-shadow': 'error', + 'no-use-before-define': 'off', + 'no-void': 'off', + + 'array-callback-return': ['error', { checkForEach: true }], + 'consistent-return': 'error', + 'constructor-super': 'error', + 'default-case-last': 'error', + 'default-param-last': 'error', + eqeqeq: ['error', 'always'], + curly: ['error', 'all'], + 'dot-notation': 'error', + 'guard-for-in': 'error', + radix: 'error', + yoda: 'error', + + 'object-shorthand': ['error', 'always'], + 'prefer-const': 'error', + 'prefer-template': 'error', + 'prefer-object-spread': 'error', + 'prefer-rest-params': 'error', + 'prefer-spread': 'error', + 'prefer-exponentiation-operator': 'error', + 'prefer-numeric-literals': 'error', + 'prefer-promise-reject-errors': 'error', + + 'no-duplicate-imports': ['error', { allowSeparateTypeImports: true }], + + complexity: ['error', { max: 15 }], + 'max-depth': ['error', { max: 4 }], + 'max-params': ['error', { max: 5 }], + 'max-nested-callbacks': ['error', { max: 4 }], + + 'sonarjs/cognitive-complexity': ['error', 15], + 'sonarjs/no-duplicate-string': 'off', + 'sonarjs/no-nested-conditional': 'error', + 'sonarjs/prefer-single-boolean-return': 'error', + 'sonarjs/prefer-regexp-exec': 'error', + 'sonarjs/no-empty-collection': 'error', + 'sonarjs/reduce-initial-value': 'error', +}; + +// Files that hold business logic or persistence must stay transport-agnostic. +const transportFreeFiles = [ + 'src/db/**/*.ts', + 'src/integrations/**/*.ts', + 'src/shared/**/*.ts', + 'src/core/scheduler/store.ts', + 'src/core/permissions/store.ts', +]; +const transportFreeFeatureFiles = [ + 'src/features/*/service.ts', + 'src/features/*/schema.ts', +]; + +const noDiscordImport = { + name: 'discord.js', + message: + 'Keep Discord transport code out of services, stores and integrations.', +}; + +// A feature may only reach into another feature through its index.ts. +const featurePrivatePattern = { + group: ['../*/*', '!../*/index.js', '!../../**'], + message: "Import other features only through their public 'index.js'.", +}; + +const unicornRules: Linter.RulesRecord = { + 'unicorn/prefer-set-has': 'error', + 'unicorn/prefer-array-some': 'error', + 'unicorn/prefer-array-find': 'error', + 'unicorn/prefer-array-flat': 'error', + 'unicorn/prefer-array-flat-map': 'error', + 'unicorn/prefer-array-index-of': 'error', + 'unicorn/prefer-includes': 'error', + 'unicorn/prefer-string-starts-ends-with': 'error', + 'unicorn/prefer-string-slice': 'error', + 'unicorn/prefer-string-replace-all': 'error', + 'unicorn/prefer-string-raw': 'error', + 'unicorn/prefer-number-properties': 'error', + 'unicorn/prefer-regexp-test': 'error', + 'unicorn/prefer-type-error': 'error', + 'unicorn/prefer-date-now': 'error', + 'unicorn/prefer-at': 'error', + + 'unicorn/no-useless-switch-case': 'error', + 'unicorn/no-useless-promise-resolve-reject': 'error', + 'unicorn/no-useless-spread': 'error', + 'unicorn/no-useless-length-check': 'error', + 'unicorn/no-unnecessary-await': 'error', + 'unicorn/no-useless-undefined': 'error', + 'unicorn/no-await-expression-member': 'error', + 'unicorn/no-for-loop': 'error', + + 'unicorn/no-array-reduce': 'off', +}; + +export default defineConfig( + globalIgnores([ + '**/node_modules/**', + '**/dist/**', + '**/build/**', + '**/coverage/**', + '**/.next/**', + '**/.nuxt/**', + '**/.output/**', + '**/.cache/**', + '**/.turbo/**', + '**/.vercel/**', + '**/vendor/**', + '**/generated/**', + '**/*.generated.*', + '**/*.min.js', + '**/*.d.ts', + ]), + + { + files: sourceFiles, + extends: [js.configs.recommended, sonarjs.configs.recommended], + languageOptions: { + ecmaVersion: 'latest', + globals: globals.builtin, + }, + rules: qualityRules, + }, + + { + files: sourceFiles, + plugins: { unicorn }, + rules: unicornRules, + }, + + { + files: javascriptFiles, + languageOptions: { + sourceType: 'module', + }, + rules: { + 'no-undef': 'error', + 'no-unused-vars': [ + 'error', + { + argsIgnorePattern: '^_', + varsIgnorePattern: '^_', + ignoreRestSiblings: true, + }, + ], + }, + }, + + { + files: ['**/*.cjs'], + languageOptions: { + sourceType: 'commonjs', + globals: globals.node, + }, + }, + + { + files: typescriptFiles, + extends: [ + tseslint.configs.strictTypeChecked, + tseslint.configs.stylisticTypeChecked, + ], + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + 'no-undef': 'off', + 'no-unused-vars': 'off', + 'no-shadow': 'off', + 'default-param-last': 'off', + 'no-redeclare': 'off', + + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/default-param-last': 'error', + '@typescript-eslint/no-redeclare': 'error', + + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + '@typescript-eslint/no-unsafe-type-assertion': 'error', + + '@typescript-eslint/consistent-type-imports': [ + 'error', + { + prefer: 'type-imports', + fixStyle: 'separate-type-imports', + }, + ], + '@typescript-eslint/consistent-type-exports': 'error', + '@typescript-eslint/consistent-type-definitions': ['error', 'type'], + '@typescript-eslint/consistent-generic-constructors': [ + 'error', + 'constructor', + ], + '@typescript-eslint/array-type': ['error', { default: 'array-simple' }], + '@typescript-eslint/method-signature-style': ['error', 'property'], + + '@typescript-eslint/no-unused-vars': [ + 'error', + { + argsIgnorePattern: '^_', + varsIgnorePattern: '^_', + caughtErrorsIgnorePattern: '^_', + ignoreRestSiblings: true, + }, + ], + + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + allowNumber: true, + allowBoolean: true, + }, + ], + + '@typescript-eslint/no-confusing-void-expression': [ + 'error', + { ignoreArrowShorthand: true }, + ], + + '@typescript-eslint/no-misused-promises': [ + 'error', + { checksVoidReturn: true }, + ], + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-readonly': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/switch-exhaustiveness-check': 'error', + '@typescript-eslint/strict-boolean-expressions': 'error', + '@typescript-eslint/only-throw-error': 'error', + }, + }, + + { + files: [ + '**/*.{test,spec}.{js,jsx,ts,tsx}', + '**/__tests__/**/*.{js,jsx,ts,tsx}', + ], + rules: { + 'max-params': 'off', + 'sonarjs/no-duplicate-string': 'off', + }, + }, + + { + files: [ + '**/*.config.{js,mjs,cjs,ts,mts,cts}', + '**/scripts/**/*.{js,mjs,cjs,ts,mts,cts}', + ], + languageOptions: { + globals: globals.node, + }, + rules: { + 'no-console': 'off', + }, + }, + + { + files: ['src/**/*.ts', 'tests/**/*.ts', 'scripts/**/*.ts', '*.config.ts'], + languageOptions: { + globals: globals.node, + }, + plugins: { 'import-x': importX }, + settings: { + 'import-x/resolver-next': [createTypeScriptImportResolver()], + }, + rules: { + 'import-x/no-cycle': 'error', + 'import-x/no-self-import': 'error', + 'import-x/no-useless-path-segments': 'error', + 'import-x/no-extraneous-dependencies': [ + 'error', + { + devDependencies: [ + 'tests/**', + 'scripts/**', + '**/*.test.ts', + '*.config.ts', + ], + }, + ], + 'import-x/no-restricted-paths': [ + 'error', + { + zones: [ + { + target: './src/core', + from: ['./src/features', './src/app.ts', './src/index.ts'], + message: 'Core must not depend on concrete features.', + }, + { + target: './src/features', + from: ['./src/app.ts', './src/index.ts'], + message: 'Features must not import the composition root.', + }, + { + target: ['./src/db', './src/integrations', './src/shared'], + from: ['./src/features', './src/core', './src/app.ts'], + message: 'Infrastructure must not depend on application code.', + }, + ], + }, + ], + }, + }, + + { + files: ['src/features/**/*.ts'], + rules: { + 'no-restricted-imports': ['error', { patterns: [featurePrivatePattern] }], + }, + }, + + { + files: transportFreeFiles, + rules: { + 'no-restricted-imports': ['error', { paths: [noDiscordImport] }], + }, + }, + + { + files: transportFreeFeatureFiles, + rules: { + 'no-restricted-imports': [ + 'error', + { paths: [noDiscordImport], patterns: [featurePrivatePattern] }, + ], + }, + }, + + { + files: ['**/*.test.ts', 'tests/**/*.ts'], + rules: { + '@typescript-eslint/no-unsafe-type-assertion': 'off', + '@typescript-eslint/unbound-method': 'off', + '@typescript-eslint/require-await': 'off', + 'unicorn/no-useless-undefined': 'off', + 'unicorn/no-await-expression-member': 'off', + // Tests may build fixtures with another feature's internals. + 'no-restricted-imports': 'off', + }, + }, + + prettier, +); diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 8a1f302..0000000 --- a/package-lock.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "name": "lapbot", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "lapbot", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "discord.js": "^14.18.0", - "dotenv": "^16.4.7" - } - }, - "node_modules/@discordjs/builders": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.10.1.tgz", - "integrity": "sha512-OWo1fY4ztL1/M/DUyRPShB4d/EzVfuUvPTRRHRIt/YxBrUYSz0a+JicD5F5zHFoNs2oTuWavxCOVFV1UljHTng==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/formatters": "^0.6.0", - "@discordjs/util": "^1.1.1", - "@sapphire/shapeshift": "^4.0.0", - "discord-api-types": "^0.37.119", - "fast-deep-equal": "^3.1.3", - "ts-mixer": "^6.0.4", - "tslib": "^2.6.3" - }, - "engines": { - "node": ">=16.11.0" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/collection": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", - "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=16.11.0" - } - }, - "node_modules/@discordjs/formatters": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.0.tgz", - "integrity": "sha512-YIruKw4UILt/ivO4uISmrGq2GdMY6EkoTtD0oS0GvkJFRZbTSdPhzYiUILbJ/QslsvC9H9nTgGgnarnIl4jMfw==", - "license": "Apache-2.0", - "dependencies": { - "discord-api-types": "^0.37.114" - }, - "engines": { - "node": ">=16.11.0" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/rest": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.4.3.tgz", - "integrity": "sha512-+SO4RKvWsM+y8uFHgYQrcTl/3+cY02uQOH7/7bKbVZsTfrfpoE62o5p+mmV+s7FVhTX82/kQUGGbu4YlV60RtA==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/collection": "^2.1.1", - "@discordjs/util": "^1.1.1", - "@sapphire/async-queue": "^1.5.3", - "@sapphire/snowflake": "^3.5.3", - "@vladfrangu/async_event_emitter": "^2.4.6", - "discord-api-types": "^0.37.119", - "magic-bytes.js": "^1.10.0", - "tslib": "^2.6.3", - "undici": "6.21.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", - "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", - "license": "Apache-2.0", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/util": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.1.1.tgz", - "integrity": "sha512-eddz6UnOBEB1oITPinyrB2Pttej49M9FZQY8NxgEvc3tq6ZICZ19m70RsmzRdDHk80O9NoYN/25AqJl8vPVf/g==", - "license": "Apache-2.0", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/ws": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.1.tgz", - "integrity": "sha512-PBvenhZG56a6tMWF/f4P6f4GxZKJTBG95n7aiGSPTnodmz4N5g60t79rSIAq7ywMbv8A4jFtexMruH+oe51aQQ==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/collection": "^2.1.0", - "@discordjs/rest": "^2.4.3", - "@discordjs/util": "^1.1.0", - "@sapphire/async-queue": "^1.5.2", - "@types/ws": "^8.5.10", - "@vladfrangu/async_event_emitter": "^2.2.4", - "discord-api-types": "^0.37.119", - "tslib": "^2.6.2", - "ws": "^8.17.0" - }, - "engines": { - "node": ">=16.11.0" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", - "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", - "license": "Apache-2.0", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@sapphire/async-queue": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", - "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==", - "license": "MIT", - "engines": { - "node": ">=v14.0.0", - "npm": ">=7.0.0" - } - }, - "node_modules/@sapphire/shapeshift": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz", - "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "lodash": "^4.17.21" - }, - "engines": { - "node": ">=v16" - } - }, - "node_modules/@sapphire/snowflake": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz", - "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==", - "license": "MIT", - "engines": { - "node": ">=v14.0.0", - "npm": ">=7.0.0" - } - }, - "node_modules/@types/node": { - "version": "22.13.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.2.tgz", - "integrity": "sha512-Z+r8y3XL9ZpI2EY52YYygAFmo2/oWfNSj4BCpAXE2McAexDk8VcnBMGC9Djn9gTKt4d2T/hhXqmPzo4hfIXtTg==", - "license": "MIT", - "dependencies": { - "undici-types": "~6.20.0" - } - }, - "node_modules/@types/ws": { - "version": "8.5.14", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.14.tgz", - "integrity": "sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@vladfrangu/async_event_emitter": { - "version": "2.4.6", - "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.6.tgz", - "integrity": "sha512-RaI5qZo6D2CVS6sTHFKg1v5Ohq/+Bo2LZ5gzUEwZ/WkHhwtGTCB/sVLw8ijOkAUxasZ+WshN/Rzj4ywsABJ5ZA==", - "license": "MIT", - "engines": { - "node": ">=v14.0.0", - "npm": ">=7.0.0" - } - }, - "node_modules/discord-api-types": { - "version": "0.37.119", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.119.tgz", - "integrity": "sha512-WasbGFXEB+VQWXlo6IpW3oUv73Yuau1Ig4AZF/m13tXcTKnMpc/mHjpztIlz4+BM9FG9BHQkEXiPto3bKduQUg==", - "license": "MIT" - }, - "node_modules/discord.js": { - "version": "14.18.0", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.18.0.tgz", - "integrity": "sha512-SvU5kVUvwunQhN2/+0t55QW/1EHfB1lp0TtLZUSXVHDmyHTrdOj5LRKdR0zLcybaA15F+NtdWuWmGOX9lE+CAw==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/builders": "^1.10.1", - "@discordjs/collection": "1.5.3", - "@discordjs/formatters": "^0.6.0", - "@discordjs/rest": "^2.4.3", - "@discordjs/util": "^1.1.1", - "@discordjs/ws": "^1.2.1", - "@sapphire/snowflake": "3.5.3", - "discord-api-types": "^0.37.119", - "fast-deep-equal": "3.1.3", - "lodash.snakecase": "4.1.1", - "tslib": "^2.6.3", - "undici": "6.21.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/dotenv": { - "version": "16.4.7", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", - "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT" - }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "license": "MIT" - }, - "node_modules/lodash.snakecase": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", - "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", - "license": "MIT" - }, - "node_modules/magic-bytes.js": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz", - "integrity": "sha512-/k20Lg2q8LE5xiaaSkMXk4sfvI+9EGEykFS4b0CHHGWqDYU0bGUFSwchNOMA56D7TCs9GwVTkqe9als1/ns8UQ==", - "license": "MIT" - }, - "node_modules/ts-mixer": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", - "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==", - "license": "MIT" - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/undici": { - "version": "6.21.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz", - "integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==", - "license": "MIT", - "engines": { - "node": ">=18.17" - } - }, - "node_modules/undici-types": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", - "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", - "license": "MIT" - }, - "node_modules/ws": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", - "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } -} diff --git a/package.json b/package.json index d953f6e..59b85df 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,55 @@ { "name": "lapbot", - "version": "1.0.0", - "main": "index.js", + "version": "2.0.0", + "private": true, + "description": "Lapikud community Discord bot", + "license": "ISC", + "type": "module", + "engines": { + "node": ">=24" + }, + "packageManager": "pnpm@11.22.0", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "dev": "tsx watch --env-file-if-exists=.env src/index.ts", + "build": "tsc -p tsconfig.build.json", + "start": "node --env-file-if-exists=.env --enable-source-maps dist/index.js", + "typecheck": "tsc --noEmit", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "format": "prettier . --write", + "format:check": "prettier . --check", + "test": "vitest run", + "db:generate": "drizzle-kit generate", + "db:migrate": "tsx --env-file-if-exists=.env scripts/migrate.ts", + "commands:register": "tsx --env-file-if-exists=.env scripts/register-commands.ts" }, - "keywords": [], - "author": "", - "license": "ISC", - "description": "", "dependencies": { - "discord.js": "^14.18.0", - "dotenv": "^16.4.7" + "discord.js": "^14.28.1", + "drizzle-orm": "^0.45.4", + "luxon": "^3.7.2", + "pino": "^10.4.0", + "postgres": "^3.4.9", + "zod": "^4.6.7" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@total-typescript/ts-reset": "^0.6.1", + "@types/luxon": "^3.7.6", + "@types/node": "^24.19.2", + "drizzle-kit": "^0.31.11", + "eslint": "^10.15.0", + "eslint-config-prettier": "^10.1.8", + "eslint-import-resolver-typescript": "^4.4.5", + "eslint-plugin-import-x": "^4.18.1", + "eslint-plugin-sonarjs": "^4.2.2", + "eslint-plugin-unicorn": "^79.0.0", + "globals": "^17.14.0", + "jiti": "^2.7.0", + "pino-pretty": "^13.2.0", + "prettier": "^3.10.1", + "tsx": "^4.23.15", + "typescript": "~6.0.3", + "typescript-eslint": "^8.72.2", + "vitest": "^5.1.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..ffcaeb5 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,3852 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + discord.js: + specifier: ^14.28.1 + version: 14.28.1 + drizzle-orm: + specifier: ^0.45.4 + version: 0.45.4(postgres@3.4.9) + luxon: + specifier: ^3.7.2 + version: 3.7.2 + pino: + specifier: ^10.4.0 + version: 10.4.0 + postgres: + specifier: ^3.4.9 + version: 3.4.9 + zod: + specifier: ^4.6.7 + version: 4.6.7 + devDependencies: + '@eslint/js': + specifier: ^10.0.1 + version: 10.0.1(eslint@10.15.0(jiti@2.7.0)) + '@total-typescript/ts-reset': + specifier: ^0.6.1 + version: 0.6.1 + '@types/luxon': + specifier: ^3.7.6 + version: 3.7.6 + '@types/node': + specifier: ^24.19.2 + version: 24.19.2 + drizzle-kit: + specifier: ^0.31.11 + version: 0.31.11 + eslint: + specifier: ^10.15.0 + version: 10.15.0(jiti@2.7.0) + eslint-config-prettier: + specifier: ^10.1.8 + version: 10.1.8(eslint@10.15.0(jiti@2.7.0)) + eslint-import-resolver-typescript: + specifier: ^4.4.5 + version: 4.4.5(eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0)))(eslint@10.15.0(jiti@2.7.0)) + eslint-plugin-import-x: + specifier: ^4.18.1 + version: 4.18.1(@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0)) + eslint-plugin-sonarjs: + specifier: ^4.2.2 + version: 4.2.2(eslint@10.15.0(jiti@2.7.0)) + eslint-plugin-unicorn: + specifier: ^79.0.0 + version: 79.0.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + globals: + specifier: ^17.14.0 + version: 17.14.0 + jiti: + specifier: ^2.7.0 + version: 2.7.0 + pino-pretty: + specifier: ^13.2.0 + version: 13.2.0 + prettier: + specifier: ^3.10.1 + version: 3.10.1 + tsx: + specifier: ^4.23.15 + version: 4.23.15 + typescript: + specifier: ~6.0.3 + version: 6.0.3 + typescript-eslint: + specifier: ^8.72.2 + version: 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + vitest: + specifier: ^5.1.0 + version: 5.1.0(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) + +packages: + + '@cacheable/memory@2.2.0': + resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==} + + '@cacheable/utils@2.5.0': + resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + + '@discordjs/builders@1.15.0': + resolution: {integrity: sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==} + engines: {node: '>=16.11.0'} + + '@discordjs/collection@1.5.3': + resolution: {integrity: sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==} + engines: {node: '>=16.11.0'} + + '@discordjs/collection@2.1.1': + resolution: {integrity: sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==} + engines: {node: '>=18'} + + '@discordjs/formatters@0.6.2': + resolution: {integrity: sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==} + engines: {node: '>=16.11.0'} + + '@discordjs/rest@2.6.3': + resolution: {integrity: sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==} + engines: {node: '>=18'} + + '@discordjs/util@1.2.0': + resolution: {integrity: sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==} + engines: {node: '>=18'} + + '@discordjs/ws@1.2.3': + resolution: {integrity: sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==} + engines: {node: '>=16.11.0'} + + '@drizzle-team/brocli@0.10.2': + resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} + + '@emnapi/core@2.0.0-beta.2': + resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==} + + '@emnapi/runtime@2.0.0-beta.2': + resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==} + + '@emnapi/wasi-threads@2.2.0': + resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==} + + '@esbuild-kit/core-utils@3.3.2': + resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + + '@esbuild-kit/esm-loader@2.6.5': + resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + + '@esbuild/aix-ppc64@0.25.12': + resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.18.20': + resolution: {integrity: sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.25.12': + resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.18.20': + resolution: {integrity: sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.25.12': + resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.18.20': + resolution: {integrity: sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.25.12': + resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.18.20': + resolution: {integrity: sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.25.12': + resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.18.20': + resolution: {integrity: sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.25.12': + resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.18.20': + resolution: {integrity: sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.25.12': + resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.18.20': + resolution: {integrity: sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.25.12': + resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.18.20': + resolution: {integrity: sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.25.12': + resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.18.20': + resolution: {integrity: sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.25.12': + resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.18.20': + resolution: {integrity: sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.25.12': + resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.18.20': + resolution: {integrity: sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.25.12': + resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.18.20': + resolution: {integrity: sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.25.12': + resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.18.20': + resolution: {integrity: sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.25.12': + resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.18.20': + resolution: {integrity: sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.25.12': + resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.18.20': + resolution: {integrity: sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.25.12': + resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.18.20': + resolution: {integrity: sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.25.12': + resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.25.12': + resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.18.20': + resolution: {integrity: sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.25.12': + resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.25.12': + resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.18.20': + resolution: {integrity: sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.25.12': + resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.25.12': + resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.18.20': + resolution: {integrity: sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.25.12': + resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.18.20': + resolution: {integrity: sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.25.12': + resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.18.20': + resolution: {integrity: sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.25.12': + resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.18.20': + resolution: {integrity: sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.25.12': + resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.3': + resolution: {integrity: sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.23.6': + resolution: {integrity: sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/config-helpers@0.7.0': + resolution: {integrity: sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/core@1.2.1': + resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/css-tree@4.1.2': + resolution: {integrity: sha512-rVcxLmwSkEL3aWS3vAgsTRrQHoYE1b0XcgDtKHDJ92XOkyUpcbS/g0tUJKhvCtlEhYzgKBWsgDd+Z/aPhd166w==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/js@10.0.1': + resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^10.0.0 + peerDependenciesMeta: + eslint: + optional: true + + '@eslint/object-schema@3.0.5': + resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/plugin-kit@0.7.3': + resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + + '@isaacs/nonrecursive-glob-match@1.1.0': + resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} + + '@jridgewell/resolve-uri@3.1.3': + resolution: {integrity: sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@keyv/bigmap@1.3.1': + resolution: {integrity: sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==} + engines: {node: '>= 18'} + peerDependencies: + keyv: ^5.6.0 + + '@keyv/serialize@1.1.1': + resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + + '@napi-rs/wasm-runtime@1.2.6': + resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + peerDependencies: + '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 + '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@pinojs/redact@0.4.0': + resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + + '@rolldown/binding-android-arm-eabi@1.2.19': + resolution: {integrity: sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.19': + resolution: {integrity: sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.19': + resolution: {integrity: sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.19': + resolution: {integrity: sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.19': + resolution: {integrity: sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': + resolution: {integrity: sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.19': + resolution: {integrity: sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.19': + resolution: {integrity: sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.19': + resolution: {integrity: sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.19': + resolution: {integrity: sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.19': + resolution: {integrity: sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.19': + resolution: {integrity: sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.19': + resolution: {integrity: sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.2.19': + resolution: {integrity: sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.2.19': + resolution: {integrity: sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.19': + resolution: {integrity: sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.1.1': + resolution: {integrity: sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==} + + '@sapphire/async-queue@1.5.5': + resolution: {integrity: sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==} + engines: {node: '>=v14.0.0', npm: '>=7.0.0'} + + '@sapphire/shapeshift@4.0.0': + resolution: {integrity: sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==} + engines: {node: '>=v16'} + + '@sapphire/snowflake@3.5.5': + resolution: {integrity: sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==} + engines: {node: '>=v14.0.0', npm: '>=7.0.0'} + + '@sonarsource/analyzer-commons-configurations@2.31.0-5284': + resolution: {integrity: sha512-ruk3blMs9BE9RNSp9LPpWZAIjxJmq4Cp00E3cELIHz7Kym3WxdWGRlKOMYLRQ5tJg/de7jN5AtEElY3bGIfTcw==} + + '@total-typescript/ts-reset@0.6.1': + resolution: {integrity: sha512-cka47fVSo6lfQDIATYqb/vO1nvFfbPw7uWLayIXIhGETj0wcOOlrlkobOMDNQOFr9QOafegUPq13V2+6vtD7yg==} + + '@tybys/wasm-util@0.10.4': + resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/debug@4.1.13': + resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/esrecurse@4.3.1': + resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/luxon@3.7.6': + resolution: {integrity: sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ==} + + '@types/ms@2.1.0': + resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} + + '@types/node@24.19.2': + resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==} + + '@types/node@26.6.6': + resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + + '@typescript-eslint/eslint-plugin@8.72.2': + resolution: {integrity: sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.72.2 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.72.2': + resolution: {integrity: sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/project-service@8.72.2': + resolution: {integrity: sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/scope-manager@8.72.2': + resolution: {integrity: sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/tsconfig-utils@8.72.2': + resolution: {integrity: sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/type-utils@8.72.2': + resolution: {integrity: sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/types@8.72.2': + resolution: {integrity: sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.72.2': + resolution: {integrity: sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/utils@8.72.2': + resolution: {integrity: sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/visitor-keys@8.72.2': + resolution: {integrity: sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@unrs/resolver-binding-android-arm-eabi@1.13.0': + resolution: {integrity: sha512-60E5mvmIiW+i1E/HYeSX4iE4A8s9NJSGYPu7UM0DJght1c2tTkWwuyDyAwzsEXhKM/XbbndfnTiXdfrf27d2hw==} + cpu: [arm] + os: [android] + + '@unrs/resolver-binding-android-arm64@1.13.0': + resolution: {integrity: sha512-qlh/JR3Tuy1cJ7xtf5pR4ykvLiK6os7X7EL2+zXZbrVc/s+yB8DoFdQrCAW9/a2TOxPVbR7QVNpkPWh7UWIsEQ==} + cpu: [arm64] + os: [android] + + '@unrs/resolver-binding-darwin-arm64@1.13.0': + resolution: {integrity: sha512-yynnnnJXUC99WeD1GfvuXPKsKNfvgzGYC2eRayFnUfsHVROjqrbFOkFQLZiSx1H8+PLy5BzU8vqyPyLqbRfeBQ==} + cpu: [arm64] + os: [darwin] + + '@unrs/resolver-binding-darwin-x64@1.13.0': + resolution: {integrity: sha512-t8PXE0Ip9tmGyhRlfVsnEbzGM5iSvJIeNIXciUACjzpg0mmPs13fGv2x7W8sBa0S8zbIiohxKXS9fL/LXW/ERQ==} + cpu: [x64] + os: [darwin] + + '@unrs/resolver-binding-freebsd-x64@1.13.0': + resolution: {integrity: sha512-qdtl9GDWDoDx6rhzF4RU5SJutV3lcLOiTiyqD6nBxYfEO6lAgLNukfrA+HJ2u2OiyWvV8JW5iEWD3LoONw7lYA==} + cpu: [x64] + os: [freebsd] + + '@unrs/resolver-binding-linux-arm-gnueabihf@1.13.0': + resolution: {integrity: sha512-VrMUVwdrScTarsh4B6aUhTtziUavSlglo4Hi8XZ6CpAe4+j3nquY+XoP+tYkiSBDsXZ8386ne4pv4YYYBNi02w==} + cpu: [arm] + os: [linux] + + '@unrs/resolver-binding-linux-arm-musleabihf@1.13.0': + resolution: {integrity: sha512-zSbTVwaxiTC+zYJ9xVNTC6c+BYO/kOV/odcTI3bHuFFXa+XmjLoUkb/8UxsZeU5YF4K000m17wrXoTblNWuzOg==} + cpu: [arm] + os: [linux] + + '@unrs/resolver-binding-linux-arm64-gnu@1.13.0': + resolution: {integrity: sha512-Z/Rax87moZHsuvJ8awdfP+zrMlsCt3d7mggUPIiPe32KpeagimyzJWnZSMQoV67an9uVQghyh92Pc0VprITnYA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@unrs/resolver-binding-linux-arm64-musl@1.13.0': + resolution: {integrity: sha512-oUzXz8hNvFLNEAag8lBKJe1euiV2dmGHAR+eQ5fNpsZO0F1K7IMRb4J6pqYsd7uLMRQNPiu5A1WKUJHbFLWbbw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@unrs/resolver-binding-linux-loong64-gnu@1.13.0': + resolution: {integrity: sha512-BxhGYvZBg0YrvNOeSEGR3eNklwXYy0mUJk7oeGJvZoQMKM68zYvbbf52+fQI3Le4X0fW276FTKIoTwjpMob80A==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@unrs/resolver-binding-linux-loong64-musl@1.13.0': + resolution: {integrity: sha512-nZcIuup9Ar3gAlqoZfX/KW6x83TMI11tLpCjldZG5M1KeY8qNUPNJJ71+sPvG8HMBpoh+ix1pAm5gkMFvcSAcQ==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@unrs/resolver-binding-linux-ppc64-gnu@1.13.0': + resolution: {integrity: sha512-AG6AgdDrkRNjAPwD/cftFJGgZUWCiJX+E8vpYCDEnwFHLTHZ7ppBiU6/vyPPwrfjcPUPQCDbbxE/eZUXsx49jQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@unrs/resolver-binding-linux-riscv64-gnu@1.13.0': + resolution: {integrity: sha512-6vOqYGcAmzpRWpUURWutzvpf1qJ6eOu5cfYObdtPJnzZ0+Kw4cw+ZkZJqIYEh8fPuTBwSYDL/FwlUhma1G/JVQ==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@unrs/resolver-binding-linux-riscv64-musl@1.13.0': + resolution: {integrity: sha512-4HeIn0S2KVUowK0A+EweXrDvZ8CKHEfTtif0kx9vt3ORNsqcXNFFIFnHE0tizma3/Gt5OGrU2ovYNuj+D/bN4g==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@unrs/resolver-binding-linux-s390x-gnu@1.13.0': + resolution: {integrity: sha512-JfkvqY7NZbxyhexLE+g6Z8Hsx4utHOGaVazAVghPiBn8Upw2iERZPpKYnW1FBVU4WStv/BiIsoK/Muke0E7asA==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@unrs/resolver-binding-linux-x64-gnu@1.13.0': + resolution: {integrity: sha512-iwjLeVdZo/8v5OKAeRIC+4VQV045t1EPZr5B/AVLgUQ04IdtNthWzg6not2cNjZgH2gHpSf4fOXMmN83aLO1FA==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@unrs/resolver-binding-linux-x64-musl@1.13.0': + resolution: {integrity: sha512-TOh1fqOjyq1OPoht3BDLd7Y+HeMJRwd5g2VNmCQclknEbjp4py5GFRmT4L/rOybF5Af8q0LT9zHs2WGkwlqtrw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@unrs/resolver-binding-openharmony-arm64@1.13.0': + resolution: {integrity: sha512-3T2MNtF2dd1yjaXCVqrsi+/3VZeksEzU1hygPzqqkBLVVjn+2iJzXEkxxCKIVFrWnpmEbazeHJp/ruYD0RUVWA==} + cpu: [arm64] + os: [openharmony] + + '@unrs/resolver-binding-win32-arm64-msvc@1.13.0': + resolution: {integrity: sha512-hKWfSLiN3L4cIxg0jrpyP/66AXLTcyD37jmSn//rGdOUYGlizYxTEFdJ+GZbp2NnaML3YS/A73nCysze8FaJdg==} + cpu: [arm64] + os: [win32] + + '@unrs/resolver-binding-win32-ia32-msvc@1.13.0': + resolution: {integrity: sha512-N4gDKkDoiyIQEcn3vTqe2ksRxUAtBvQ8c5TiT+WonSa6FHgCAY5+RggnZ134hXJoRj57JEjv4/m+i/pAKHWrTQ==} + cpu: [ia32] + os: [win32] + + '@unrs/resolver-binding-win32-x64-msvc@1.13.0': + resolution: {integrity: sha512-DpLMlAqlrk4zBVK3DiDjwKD0oq7pZNy+8BiIBRuByqb6dm5jsdoLMhIiyh/xR7+WejaW/1Ui+XgbgMNa4+zWJg==} + cpu: [x64] + os: [win32] + + '@vitest/mocker@5.1.0': + resolution: {integrity: sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.1.0': + resolution: {integrity: sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==} + + '@vladfrangu/async_event_emitter@2.4.7': + resolution: {integrity: sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==} + engines: {node: '>=v14.0.0', npm: '>=7.0.0'} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.19.0: + resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + atomic-sleep@1.0.0: + resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} + engines: {node: '>=8.0.0'} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + baseline-browser-mapping@2.11.37: + resolution: {integrity: sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==} + engines: {node: '>=6.0.0'} + hasBin: true + + brace-expansion@5.0.13: + resolution: {integrity: sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==} + engines: {node: 20 || >=22} + + browserslist@4.29.5: + resolution: {integrity: sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + builtin-modules@3.3.0: + resolution: {integrity: sha512-zhaCDicdLuWN5UbN5IMnFqNMhNfo919sH85y2/ea+5Yg9TsTkeZxpL+JLbp6cgYFS4sRLp3YV4S6yDuqVWHYOw==} + engines: {node: '>=6'} + + builtin-modules@5.5.0: + resolution: {integrity: sha512-2uhx+Lkzc2fnAcNEpzbJziSzwdv6cJjxxsi9oByBhSuy2wffAPzmazVDiWJk2xDKULFONl5gNOEOLOupQ8gsPg==} + engines: {node: '>=18.20'} + + bytes@3.1.2: + resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} + engines: {node: '>= 0.8'} + + cacheable@2.5.0: + resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} + + caniuse-lite@1.0.30001826: + resolution: {integrity: sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + change-case@5.4.4: + resolution: {integrity: sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==} + + character-entities@2.0.2: + resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==} + + ci-info@4.5.0: + resolution: {integrity: sha512-d1uM8k5UZEyPza1n/MG3ko8nKupKN0KJpFsipgPcgaCCvV+IqIfJ+NzTjetlLM+UcXZx3+cLrNr76+eAO7G1Mw==} + engines: {node: '>=8'} + + cjs-module-lexer@2.3.0: + resolution: {integrity: sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==} + + colorette@2.0.20: + resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} + + comment-parser@1.4.9: + resolution: {integrity: sha512-+2AvZKjJaNq9GQljm3tr0utwrig5BL+jgJGvz5rDpGKNIp+ojcRXWUwBbh/sGIi1QCprR6PsKFakub+w1v+4hQ==} + engines: {node: '>= 12.0.0'} + + core-js-compat@3.51.0: + resolution: {integrity: sha512-52r6fkXgxv4GLMjmFcMWRx7X9bw071xTTdrDcdyPGRqU2oE+9pCG0bAOMifSBdLw0JRBZKEF0q3B55qPlLuE8g==} + engines: {node: '>=6.4.0'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + dateformat@4.6.3: + resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decode-named-character-reference@1.3.0: + resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==} + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + detect-indent@7.0.2: + resolution: {integrity: sha512-y+8xyqdGLL+6sh0tVeHcfP/QDd8gUgbasolJJpY7NgeQGSZ739bDtSiaiDgtoicy+mtYB81dKLxO9xRhCyIB3A==} + engines: {node: '>=12.20'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + devlop@1.1.0: + resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} + + discord-api-types@0.38.59: + resolution: {integrity: sha512-LZqh8gvWU/Bhl9qEVIRLeLJuaPGO7rA26IXLrXnMcjXxofh/h5UhP6notfCTj4X5kR1ogMvVgcrVYIuynY/CxQ==} + + discord.js@14.28.1: + resolution: {integrity: sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==} + engines: {node: '>=18'} + + drizzle-kit@0.31.11: + resolution: {integrity: sha512-YCYqxTLIB2OCqf6w9/Vef13baBVbwQIPcbT4Y56AfO6B9ajZhDhD8Jkveg/hJvT/iuMloKD/IYYkyMMNhr7Kqg==} + hasBin: true + + drizzle-orm@0.45.4: + resolution: {integrity: sha512-NiM1YZpJ2UxyeE67DpDDZ+Tsw4YLX3trSlkNT7Tm9eKoUNb1LvaAaQzXgYQsWs+AQ9TUmmwMmBOCXuqqxUWKKQ==} + peerDependencies: + '@aws-sdk/client-rds-data': '>=3' + '@cloudflare/workers-types': '>=4' + '@electric-sql/pglite': '>=0.2.0' + '@libsql/client': '>=0.10.0' + '@libsql/client-wasm': '>=0.10.0' + '@neondatabase/serverless': '>=0.10.0' + '@netlify/db': '>=0.4.0' + '@op-engineering/op-sqlite': '>=2' + '@opentelemetry/api': ^1.4.1 + '@planetscale/database': '>=1.13' + '@prisma/client': '*' + '@tidbcloud/serverless': '*' + '@types/better-sqlite3': '*' + '@types/pg': '*' + '@types/sql.js': '*' + '@upstash/redis': '>=1.34.7' + '@vercel/postgres': '>=0.8.0' + '@xata.io/client': '*' + better-sqlite3: '>=7' + bun-types: '*' + expo-sqlite: '>=14.0.0' + gel: '>=2' + knex: '*' + kysely: '*' + mysql2: '>=2' + pg: '>=8' + postgres: '>=3' + prisma: '*' + sql.js: '>=1' + sqlite3: '>=5' + peerDependenciesMeta: + '@aws-sdk/client-rds-data': + optional: true + '@cloudflare/workers-types': + optional: true + '@electric-sql/pglite': + optional: true + '@libsql/client': + optional: true + '@libsql/client-wasm': + optional: true + '@neondatabase/serverless': + optional: true + '@netlify/db': + optional: true + '@op-engineering/op-sqlite': + optional: true + '@opentelemetry/api': + optional: true + '@planetscale/database': + optional: true + '@prisma/client': + optional: true + '@tidbcloud/serverless': + optional: true + '@types/better-sqlite3': + optional: true + '@types/pg': + optional: true + '@types/sql.js': + optional: true + '@upstash/redis': + optional: true + '@vercel/postgres': + optional: true + '@xata.io/client': + optional: true + better-sqlite3: + optional: true + bun-types: + optional: true + expo-sqlite: + optional: true + gel: + optional: true + knex: + optional: true + kysely: + optional: true + mysql2: + optional: true + pg: + optional: true + postgres: + optional: true + prisma: + optional: true + sql.js: + optional: true + sqlite3: + optional: true + + electron-to-chromium@1.5.485: + resolution: {integrity: sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw==} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + entities@8.1.0: + resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} + engines: {node: '>=20.19.0'} + + entities@9.0.0: + resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} + engines: {node: '>=20.19.0'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + es-module-lexer@3.0.4: + resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==} + + esbuild@0.18.20: + resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.25.12: + resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} + engines: {node: '>=18'} + hasBin: true + + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-config-prettier@10.1.8: + resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==} + hasBin: true + peerDependencies: + eslint: '>=7.0.0' + + eslint-import-context@0.1.9: + resolution: {integrity: sha512-K9Hb+yRaGAGUbwjhFNHvSmmkZs9+zbuoe3kFQ4V1wYjrepUFYM2dZAfNtjbbj3qsPfUfsA68Bx/ICWQMi+C8Eg==} + engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} + peerDependencies: + unrs-resolver: ^1.0.0 + peerDependenciesMeta: + unrs-resolver: + optional: true + + eslint-import-resolver-typescript@4.4.5: + resolution: {integrity: sha512-nbE5XLph6TLtGYcu/U6e6ZVXyKBhbDWK5cLGk76eJ7NdZpwf1P9EFkpt1Z01mNZNrrilsAYWKH6zUkL4reoXbw==} + engines: {node: ^16.17.0 || >=18.6.0} + peerDependencies: + eslint: '*' + eslint-plugin-import: '*' + eslint-plugin-import-x: '*' + peerDependenciesMeta: + eslint-plugin-import: + optional: true + eslint-plugin-import-x: + optional: true + + eslint-plugin-import-x@4.18.1: + resolution: {integrity: sha512-D1h++38NS2Z40zf8jbd2OHqDrnIFRKpdp8sL0jP4xSDGZj6MNwEQua8F+r3tOWjcHrsWuhHOJ7wASWioJ31tfg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/utils': ^8.56.0 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + eslint-import-resolver-node: '*' + peerDependenciesMeta: + '@typescript-eslint/utils': + optional: true + eslint-import-resolver-node: + optional: true + + eslint-plugin-sonarjs@4.2.2: + resolution: {integrity: sha512-usNF9GfP89ibwhfxpZaCMW40sC7UEOusDgDCk7lyqAhh4AYdbBaAgLVL5Y/QS0jSed8eJ2ACGH6zzE8ezd/yZQ==} + peerDependencies: + eslint: ^8.0.0 || ^9.0.0 || ^10.0.0 + + eslint-plugin-unicorn@79.0.0: + resolution: {integrity: sha512-k7MWrjoVTVCnjKpgaxBuScPNSPomLvDpsd9uADpWrIFzrnwiec27eWhGrmmyuTj1bC3xVNYP4QfG3MEzEw6ifg==} + engines: {node: '>=22'} + peerDependencies: + eslint: '>=10.4' + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + eslint-scope@9.1.2: + resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@10.15.0: + resolution: {integrity: sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@11.2.0: + resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fast-copy@4.3.1: + resolution: {integrity: sha512-CRzQaTFOFUs6PuhsAq7lk9Zqr995soJBcFNZlfJS/5keTSl1awREV9dZW4xS2nX4pWbhIIR0xp4h+J8PQxCkvg==} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fast-safe-stringify@2.1.1: + resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-entry-cache@11.1.5: + resolution: {integrity: sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==} + + find-up-simple@1.0.1: + resolution: {integrity: sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ==} + engines: {node: '>=18'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@6.1.23: + resolution: {integrity: sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==} + + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + functional-red-black-tree@1.0.1: + resolution: {integrity: sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==} + + get-tsconfig@4.14.3: + resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + globals@17.14.0: + resolution: {integrity: sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==} + engines: {node: '>=18'} + + hashery@1.5.1: + resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} + engines: {node: '>=20'} + + help-me@5.0.0: + resolution: {integrity: sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==} + + hookified@1.15.1: + resolution: {integrity: sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==} + + hookified@2.2.0: + resolution: {integrity: sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==} + + identifier-regex@1.1.0: + resolution: {integrity: sha512-SLX4H/vtcYlYnL7XqnuJKHU7Z8517TgsW9nmQiGOgMCjQ8V/deLYu6bEmbGoXe7WMMhc9+EUGyFFneHja8KabA==} + engines: {node: '>=18'} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.14: + resolution: {integrity: sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==} + engines: {node: '>= 4'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + indent-string@5.0.0: + resolution: {integrity: sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==} + engines: {node: '>=12'} + + is-builtin-module@5.0.0: + resolution: {integrity: sha512-f4RqJKBUe5rQkJ2eJEJBXSticB3hGbN9j0yxxMQFqIW89Jp9WYFtzfTcRlstDKVUTRzSOTLKRfO9vIztenwtxA==} + engines: {node: '>=18.20'} + + is-bun-module@2.0.0: + resolution: {integrity: sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + jsx-ast-utils-x@0.1.0: + resolution: {integrity: sha512-eQQBjBnsVtGacsG9uJNB8qOr3yA8rga4wAaGG1qRcBzSIvfhERLrWxMAM1hp5fcS6Abo8M4+bUBTekYR0qTPQw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + keyv@5.6.0: + resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + + lodash.snakecase@4.1.1: + resolution: {integrity: sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==} + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + luxon@3.7.2: + resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} + engines: {node: '>=12'} + + magic-bytes.js@1.13.1: + resolution: {integrity: sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==} + + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + + mdn-data@2.37.2: + resolution: {integrity: sha512-rz9YOBGItdSbe7HcSArUbhiAv4SB/4DKRYg96CSFS2CcIYMbUvBtZlzA1NCbk2AdgbmYwMqwNblLpR441lLeiQ==} + + micromark-core-commonmark@2.0.4: + resolution: {integrity: sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==} + + micromark-factory-destination@2.0.1: + resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==} + + micromark-factory-label@2.0.1: + resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==} + + micromark-factory-space@2.1.0: + resolution: {integrity: sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==} + + micromark-factory-title@2.0.1: + resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==} + + micromark-factory-whitespace@2.0.1: + resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==} + + micromark-util-character@2.1.1: + resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==} + + micromark-util-chunked@2.0.1: + resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==} + + micromark-util-classify-character@2.0.1: + resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==} + + micromark-util-combine-extensions@2.0.1: + resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==} + + micromark-util-decode-numeric-character-reference@2.0.2: + resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==} + + micromark-util-edit-map@1.0.0: + resolution: {integrity: sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==} + + micromark-util-encode@2.0.1: + resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==} + + micromark-util-html-tag-name@2.0.1: + resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==} + + micromark-util-normalize-identifier@2.0.1: + resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==} + + micromark-util-resolve-all@2.0.1: + resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==} + + micromark-util-sanitize-uri@2.0.1: + resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==} + + micromark-util-subtokenize@2.1.0: + resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==} + + micromark-util-symbol@2.0.1: + resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==} + + micromark-util-types@2.0.3: + resolution: {integrity: sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==} + + micromark@4.0.3: + resolution: {integrity: sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==} + + minimatch@10.2.6: + resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} + engines: {node: 18 || 20 || >=22} + + minimatch@11.0.8: + resolution: {integrity: sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==} + engines: {node: 20 || >=22} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + napi-postinstall@0.3.8: + resolution: {integrity: sha512-dHbDC5V1g/EI8OLEtL4Iuwbu0fgzmyykxenn2KnlsX9XdhTXL3gWnfbbP+ab+oUcgV6CFpb8QGyQt/ZXA0UXig==} + engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} + hasBin: true + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + node-releases@2.0.64: + resolution: {integrity: sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==} + engines: {node: '>=18'} + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + on-exit-leak-free@2.1.2: + resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} + engines: {node: '>=14.0.0'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + parse5@8.1.1: + resolution: {integrity: sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + pino-abstract-transport@3.0.0: + resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==} + + pino-pretty@13.2.0: + resolution: {integrity: sha512-jjghD1ML+Di/WxjJDz6j6Y4FT7hIXOlb8h27AyJ+ohtAXJXH4PS/xkv7si+RCCIW59HMgZsMKTDgzdr0RhuRrg==} + hasBin: true + + pino-std-serializers@7.1.0: + resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==} + + pino@10.4.0: + resolution: {integrity: sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==} + hasBin: true + + pluralize@8.0.0: + resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==} + engines: {node: '>=4'} + + postcss@8.5.33: + resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} + engines: {node: ^10 || ^12 || >=14} + + postgres@3.4.9: + resolution: {integrity: sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw==} + engines: {node: '>=12'} + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier@3.10.1: + resolution: {integrity: sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==} + engines: {node: '>=14'} + hasBin: true + + process-warning@5.1.1: + resolution: {integrity: sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==} + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + qified@0.10.1: + resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} + engines: {node: '>=20'} + + quick-format-unescaped@4.0.4: + resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} + + quote-js-string@0.1.0: + resolution: {integrity: sha512-Y3NoRtprEEZQD8RfxMCfS0ZTqc4e+i18OrXEXAvpM6TfC/3y+0L5rNbZiSnbBBEkDfFzbpd8o+cE8q3/anjMGA==} + engines: {node: '>=22'} + + real-require@1.0.0: + resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==} + + refa@0.12.1: + resolution: {integrity: sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + regexp-ast-analysis@0.7.1: + resolution: {integrity: sha512-sZuz1dYW/ZsfG17WSAG7eS85r5a0dDsvg+7BiiYR5o6lKCAtUrEwdmRmaGF6rwVj3LcmAeYkOWKEPlbPzN3Y3A==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + regjsparser@0.13.4: + resolution: {integrity: sha512-EWV80YgFaVgFrjGCAsV7oybp4GOxbls5RzBg8OB0nKEVXsBJR1JlV8Di1JhCROg3MzTfe1RI8yitIm1eOs68iA==} + hasBin: true + + reserved-identifiers@1.2.0: + resolution: {integrity: sha512-yE7KUfFvaBFzGPs5H3Ops1RevfUEsDc5Iz65rOwWg4lE8HJSYtle77uul3+573457oHvBKuHYDl/xqUkKpEEdw==} + engines: {node: '>=18'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + rolldown@1.2.19: + resolution: {integrity: sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + safe-stable-stringify@2.5.0: + resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} + engines: {node: '>=10'} + + scslre@0.3.0: + resolution: {integrity: sha512-3A6sD0WYP7+QrjbfNA2FN3FsOaGGFoekCVgTyypy53gPxhbkCIjtO6YWgdrfM+n/8sI8JeXZOIxsHjMTNxQ4nQ==} + engines: {node: ^14.0.0 || >=16.0.0} + + secure-json-parse@4.1.1: + resolution: {integrity: sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==} + + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + sonic-boom@4.2.1: + resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} + + sonic-boom@5.0.2: + resolution: {integrity: sha512-/JEruzo6yhNVhsLblTRchgTQHIt7SsdJP0YyrfWaNKjIOQDfrdZv9gwYraYCAsmKV39/LAdV31FLL5NCDpoL/A==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + stable-hash-x@0.2.0: + resolution: {integrity: sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ==} + engines: {node: '>=12.0.0'} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + strip-indent@4.1.1: + resolution: {integrity: sha512-SlyRoSkdh1dYP0PzclLE7r0M9sgbFKKMFXpFRUMNuKhQSbC6VQIGzq3E0qsfvGJaUFJPGv6Ws1NZ/haTAjfbMA==} + engines: {node: '>=12'} + + strip-json-comments@5.1.0: + resolution: {integrity: sha512-ErcwpJBYr8EfX/Br7JauOIGXoRE92w0hVtuS9j92UFgbATxA+WRSIZksSUDzEeItfWB/0QCEprTZT55RSINUHQ==} + engines: {node: '>=22'} + + thread-stream@4.2.1: + resolution: {integrity: sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ==} + engines: {node: '>=20'} + + tinybench@6.2.3: + resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + ts-api-utils@2.5.0: + resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} + engines: {node: '>=18.12'} + peerDependencies: + typescript: '>=4.8.4' + + ts-mixer@6.0.4: + resolution: {integrity: sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==} + + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + typescript-eslint@8.72.2: + resolution: {integrity: sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + undici@6.29.1: + resolution: {integrity: sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==} + engines: {node: '>=18.17'} + + unrs-resolver@1.13.0: + resolution: {integrity: sha512-mcPQo9Vm6kXd84d/WqMiYBi2CcA57QHBX/ev5PoUEb8b2oQzUvJ6xYsfseQblnCncgnVmCZGWiFwK7KkS5JZJA==} + + update-browserslist-db@1.3.4: + resolution: {integrity: sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + vite@8.3.8: + resolution: {integrity: sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.1.0: + resolution: {integrity: sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.1.0 + '@vitest/browser-preview': 5.1.0 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.1.0 + '@vitest/coverage-v8': 5.1.0 + '@vitest/ui': 5.1.0 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + ws@8.23.0: + resolution: {integrity: sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + +snapshots: + + '@cacheable/memory@2.2.0': + dependencies: + '@cacheable/utils': 2.5.0 + '@keyv/bigmap': 1.3.1(keyv@5.6.0) + hookified: 1.15.1 + keyv: 5.6.0 + + '@cacheable/utils@2.5.0': + dependencies: + hashery: 1.5.1 + keyv: 5.6.0 + + '@discordjs/builders@1.15.0': + dependencies: + '@discordjs/formatters': 0.6.2 + '@discordjs/util': 1.2.0 + '@sapphire/shapeshift': 4.0.0 + discord-api-types: 0.38.59 + fast-deep-equal: 3.1.3 + ts-mixer: 6.0.4 + tslib: 2.9.1 + + '@discordjs/collection@1.5.3': {} + + '@discordjs/collection@2.1.1': {} + + '@discordjs/formatters@0.6.2': + dependencies: + discord-api-types: 0.38.59 + + '@discordjs/rest@2.6.3': + dependencies: + '@discordjs/collection': 2.1.1 + '@discordjs/util': 1.2.0 + '@sapphire/async-queue': 1.5.5 + '@sapphire/snowflake': 3.5.5 + '@vladfrangu/async_event_emitter': 2.4.7 + discord-api-types: 0.38.59 + magic-bytes.js: 1.13.1 + tslib: 2.9.1 + undici: 6.29.1 + + '@discordjs/util@1.2.0': + dependencies: + discord-api-types: 0.38.59 + + '@discordjs/ws@1.2.3': + dependencies: + '@discordjs/collection': 2.1.1 + '@discordjs/rest': 2.6.3 + '@discordjs/util': 1.2.0 + '@sapphire/async-queue': 1.5.5 + '@types/ws': 8.18.2 + '@vladfrangu/async_event_emitter': 2.4.7 + discord-api-types: 0.38.59 + tslib: 2.9.1 + ws: 8.23.0 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + '@drizzle-team/brocli@0.10.2': {} + + '@emnapi/core@2.0.0-beta.2': + dependencies: + '@emnapi/wasi-threads': 2.2.0 + tslib: 2.9.1 + optional: true + + '@emnapi/runtime@2.0.0-beta.2': + dependencies: + tslib: 2.9.1 + optional: true + + '@emnapi/wasi-threads@2.2.0': + dependencies: + tslib: 2.9.1 + optional: true + + '@esbuild-kit/core-utils@3.3.2': + dependencies: + esbuild: 0.18.20 + source-map-support: 0.5.21 + + '@esbuild-kit/esm-loader@2.6.5': + dependencies: + '@esbuild-kit/core-utils': 3.3.2 + get-tsconfig: 4.14.3 + + '@esbuild/aix-ppc64@0.25.12': + optional: true + + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.18.20': + optional: true + + '@esbuild/android-arm64@0.25.12': + optional: true + + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.18.20': + optional: true + + '@esbuild/android-arm@0.25.12': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.18.20': + optional: true + + '@esbuild/android-x64@0.25.12': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.18.20': + optional: true + + '@esbuild/darwin-arm64@0.25.12': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.18.20': + optional: true + + '@esbuild/darwin-x64@0.25.12': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.18.20': + optional: true + + '@esbuild/freebsd-arm64@0.25.12': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.18.20': + optional: true + + '@esbuild/freebsd-x64@0.25.12': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.18.20': + optional: true + + '@esbuild/linux-arm64@0.25.12': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.18.20': + optional: true + + '@esbuild/linux-arm@0.25.12': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.18.20': + optional: true + + '@esbuild/linux-ia32@0.25.12': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.18.20': + optional: true + + '@esbuild/linux-loong64@0.25.12': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.18.20': + optional: true + + '@esbuild/linux-mips64el@0.25.12': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.18.20': + optional: true + + '@esbuild/linux-ppc64@0.25.12': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.18.20': + optional: true + + '@esbuild/linux-riscv64@0.25.12': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.18.20': + optional: true + + '@esbuild/linux-s390x@0.25.12': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.18.20': + optional: true + + '@esbuild/linux-x64@0.25.12': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.25.12': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.18.20': + optional: true + + '@esbuild/netbsd-x64@0.25.12': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.25.12': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.18.20': + optional: true + + '@esbuild/openbsd-x64@0.25.12': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.25.12': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.18.20': + optional: true + + '@esbuild/sunos-x64@0.25.12': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.18.20': + optional: true + + '@esbuild/win32-arm64@0.25.12': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.18.20': + optional: true + + '@esbuild/win32-ia32@0.25.12': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.18.20': + optional: true + + '@esbuild/win32-x64@0.25.12': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@eslint-community/eslint-utils@4.10.1(eslint@10.15.0(jiti@2.7.0))': + dependencies: + eslint: 10.15.0(jiti@2.7.0) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.3': {} + + '@eslint/config-array@0.23.6': + dependencies: + '@eslint/object-schema': 3.0.5 + debug: 4.4.3 + minimatch: 11.0.8 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.7.0': + dependencies: + '@eslint/core': 1.2.1 + + '@eslint/core@1.2.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/css-tree@4.1.2': + dependencies: + mdn-data: 2.37.2 + source-map-js: 1.2.2 + + '@eslint/js@10.0.1(eslint@10.15.0(jiti@2.7.0))': + optionalDependencies: + eslint: 10.15.0(jiti@2.7.0) + + '@eslint/object-schema@3.0.5': {} + + '@eslint/plugin-kit@0.7.3': + dependencies: + '@eslint/core': 1.2.1 + levn: 0.4.1 + + '@humanfs/core@0.19.2': + dependencies: + '@humanfs/types': 0.15.0 + + '@humanfs/node@0.16.8': + dependencies: + '@humanfs/core': 0.19.2 + '@humanfs/types': 0.15.0 + '@humanwhocodes/retry': 0.4.3 + + '@humanfs/types@0.15.0': {} + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + + '@isaacs/nonrecursive-glob-match@1.1.0': {} + + '@jridgewell/resolve-uri@3.1.3': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.3 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@keyv/bigmap@1.3.1(keyv@5.6.0)': + dependencies: + hashery: 1.5.1 + hookified: 1.15.1 + keyv: 5.6.0 + + '@keyv/serialize@1.1.1': {} + + '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@tybys/wasm-util': 0.10.4 + optional: true + + '@oxc-project/types@0.156.0': {} + + '@pinojs/redact@0.4.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.19': + optional: true + + '@rolldown/binding-android-arm64@1.2.19': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.19': + optional: true + + '@rolldown/binding-darwin-x64@1.2.19': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.19': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.19': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.19': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.19': + optional: true + + '@rolldown/binding-wasm32-wasi@1.2.19': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2) + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.19': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.19': + optional: true + + '@rolldown/pluginutils@1.1.1': {} + + '@sapphire/async-queue@1.5.5': {} + + '@sapphire/shapeshift@4.0.0': + dependencies: + fast-deep-equal: 3.1.3 + lodash: 4.18.1 + + '@sapphire/snowflake@3.5.5': {} + + '@sonarsource/analyzer-commons-configurations@2.31.0-5284': {} + + '@total-typescript/ts-reset@0.6.1': {} + + '@tybys/wasm-util@0.10.4': + dependencies: + tslib: 2.9.1 + optional: true + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/debug@4.1.13': + dependencies: + '@types/ms': 2.1.0 + + '@types/deep-eql@4.0.2': {} + + '@types/esrecurse@4.3.1': {} + + '@types/estree@1.0.10': {} + + '@types/json-schema@7.0.15': {} + + '@types/luxon@3.7.6': {} + + '@types/ms@2.1.0': {} + + '@types/node@24.19.2': + dependencies: + undici-types: 7.24.6 + + '@types/node@26.6.6': + dependencies: + undici-types: 8.9.0 + + '@types/ws@8.18.2': + dependencies: + '@types/node': 26.6.6 + + '@typescript-eslint/eslint-plugin@8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)': + dependencies: + '@eslint-community/regexpp': 4.12.3 + '@typescript-eslint/parser': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/scope-manager': 8.72.2 + '@typescript-eslint/type-utils': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/utils': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.72.2 + eslint: 10.15.0(jiti@2.7.0) + ignore: 7.0.14 + natural-compare: 1.4.0 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)': + dependencies: + '@typescript-eslint/scope-manager': 8.72.2 + '@typescript-eslint/types': 8.72.2 + '@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3) + '@typescript-eslint/visitor-keys': 8.72.2 + debug: 4.4.3 + eslint: 10.15.0(jiti@2.7.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/project-service@8.72.2(typescript@6.0.3)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.72.2(typescript@6.0.3) + '@typescript-eslint/types': 8.72.2 + debug: 4.4.3 + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@8.72.2': + dependencies: + '@typescript-eslint/types': 8.72.2 + '@typescript-eslint/visitor-keys': 8.72.2 + + '@typescript-eslint/tsconfig-utils@8.72.2(typescript@6.0.3)': + dependencies: + typescript: 6.0.3 + + '@typescript-eslint/type-utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)': + dependencies: + '@typescript-eslint/types': 8.72.2 + '@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3) + '@typescript-eslint/utils': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + debug: 4.4.3 + eslint: 10.15.0(jiti@2.7.0) + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@8.72.2': {} + + '@typescript-eslint/typescript-estree@8.72.2(typescript@6.0.3)': + dependencies: + '@typescript-eslint/project-service': 8.72.2(typescript@6.0.3) + '@typescript-eslint/tsconfig-utils': 8.72.2(typescript@6.0.3) + '@typescript-eslint/types': 8.72.2 + '@typescript-eslint/visitor-keys': 8.72.2 + debug: 4.4.3 + minimatch: 10.2.6 + semver: 7.8.6 + tinyglobby: 0.2.17 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)': + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0(jiti@2.7.0)) + '@typescript-eslint/scope-manager': 8.72.2 + '@typescript-eslint/types': 8.72.2 + '@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3) + eslint: 10.15.0(jiti@2.7.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/visitor-keys@8.72.2': + dependencies: + '@typescript-eslint/types': 8.72.2 + eslint-visitor-keys: 5.0.1 + + '@unrs/resolver-binding-android-arm-eabi@1.13.0': + optional: true + + '@unrs/resolver-binding-android-arm64@1.13.0': + optional: true + + '@unrs/resolver-binding-darwin-arm64@1.13.0': + optional: true + + '@unrs/resolver-binding-darwin-x64@1.13.0': + optional: true + + '@unrs/resolver-binding-freebsd-x64@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-arm-gnueabihf@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-arm-musleabihf@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-arm64-gnu@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-arm64-musl@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-loong64-gnu@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-loong64-musl@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-ppc64-gnu@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-riscv64-gnu@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-riscv64-musl@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-s390x-gnu@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-x64-gnu@1.13.0': + optional: true + + '@unrs/resolver-binding-linux-x64-musl@1.13.0': + optional: true + + '@unrs/resolver-binding-openharmony-arm64@1.13.0': + optional: true + + '@unrs/resolver-binding-win32-arm64-msvc@1.13.0': + optional: true + + '@unrs/resolver-binding-win32-ia32-msvc@1.13.0': + optional: true + + '@unrs/resolver-binding-win32-x64-msvc@1.13.0': + optional: true + + '@vitest/mocker@5.1.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.1.0 + estree-walker: 3.0.3 + magic-string: 1.4.5 + optionalDependencies: + vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + + '@vitest/spy@5.1.0': {} + + '@vladfrangu/async_event_emitter@2.4.7': {} + + acorn-jsx@5.3.2(acorn@8.19.0): + dependencies: + acorn: 8.19.0 + + acorn@8.19.0: {} + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + assertion-error@2.0.1: {} + + atomic-sleep@1.0.0: {} + + balanced-match@4.0.4: {} + + baseline-browser-mapping@2.11.37: {} + + brace-expansion@5.0.13: + dependencies: + balanced-match: 4.0.4 + + browserslist@4.29.5: + dependencies: + baseline-browser-mapping: 2.11.37 + caniuse-lite: 1.0.30001826 + electron-to-chromium: 1.5.485 + node-releases: 2.0.64 + update-browserslist-db: 1.3.4(browserslist@4.29.5) + + buffer-from@1.1.2: {} + + builtin-modules@3.3.0: {} + + builtin-modules@5.5.0: {} + + bytes@3.1.2: {} + + cacheable@2.5.0: + dependencies: + '@cacheable/memory': 2.2.0 + '@cacheable/utils': 2.5.0 + hookified: 1.15.1 + keyv: 5.6.0 + qified: 0.10.1 + + caniuse-lite@1.0.30001826: {} + + chai@6.3.0: {} + + change-case@5.4.4: {} + + character-entities@2.0.2: {} + + ci-info@4.5.0: {} + + cjs-module-lexer@2.3.0: {} + + colorette@2.0.20: {} + + comment-parser@1.4.9: {} + + core-js-compat@3.51.0: + dependencies: + browserslist: 4.29.5 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + dateformat@4.6.3: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decode-named-character-reference@1.3.0: + dependencies: + character-entities: 2.0.2 + + deep-is@0.1.4: {} + + dequal@2.0.3: {} + + detect-indent@7.0.2: {} + + detect-libc@2.1.2: {} + + devlop@1.1.0: + dependencies: + dequal: 2.0.3 + + discord-api-types@0.38.59: {} + + discord.js@14.28.1: + dependencies: + '@discordjs/builders': 1.15.0 + '@discordjs/collection': 1.5.3 + '@discordjs/formatters': 0.6.2 + '@discordjs/rest': 2.6.3 + '@discordjs/util': 1.2.0 + '@discordjs/ws': 1.2.3 + '@sapphire/snowflake': 3.5.5 + discord-api-types: 0.38.59 + fast-deep-equal: 3.1.3 + lodash.snakecase: 4.1.1 + magic-bytes.js: 1.13.1 + tslib: 2.9.1 + undici: 6.29.1 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + drizzle-kit@0.31.11: + dependencies: + '@drizzle-team/brocli': 0.10.2 + '@esbuild-kit/esm-loader': 2.6.5 + esbuild: 0.25.12 + tsx: 4.23.15 + + drizzle-orm@0.45.4(postgres@3.4.9): + optionalDependencies: + postgres: 3.4.9 + + electron-to-chromium@1.5.485: {} + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + + entities@8.1.0: {} + + entities@9.0.0: {} + + es-module-lexer@2.3.2: {} + + es-module-lexer@3.0.4: {} + + esbuild@0.18.20: + optionalDependencies: + '@esbuild/android-arm': 0.18.20 + '@esbuild/android-arm64': 0.18.20 + '@esbuild/android-x64': 0.18.20 + '@esbuild/darwin-arm64': 0.18.20 + '@esbuild/darwin-x64': 0.18.20 + '@esbuild/freebsd-arm64': 0.18.20 + '@esbuild/freebsd-x64': 0.18.20 + '@esbuild/linux-arm': 0.18.20 + '@esbuild/linux-arm64': 0.18.20 + '@esbuild/linux-ia32': 0.18.20 + '@esbuild/linux-loong64': 0.18.20 + '@esbuild/linux-mips64el': 0.18.20 + '@esbuild/linux-ppc64': 0.18.20 + '@esbuild/linux-riscv64': 0.18.20 + '@esbuild/linux-s390x': 0.18.20 + '@esbuild/linux-x64': 0.18.20 + '@esbuild/netbsd-x64': 0.18.20 + '@esbuild/openbsd-x64': 0.18.20 + '@esbuild/sunos-x64': 0.18.20 + '@esbuild/win32-arm64': 0.18.20 + '@esbuild/win32-ia32': 0.18.20 + '@esbuild/win32-x64': 0.18.20 + + esbuild@0.25.12: + optionalDependencies: + '@esbuild/aix-ppc64': 0.25.12 + '@esbuild/android-arm': 0.25.12 + '@esbuild/android-arm64': 0.25.12 + '@esbuild/android-x64': 0.25.12 + '@esbuild/darwin-arm64': 0.25.12 + '@esbuild/darwin-x64': 0.25.12 + '@esbuild/freebsd-arm64': 0.25.12 + '@esbuild/freebsd-x64': 0.25.12 + '@esbuild/linux-arm': 0.25.12 + '@esbuild/linux-arm64': 0.25.12 + '@esbuild/linux-ia32': 0.25.12 + '@esbuild/linux-loong64': 0.25.12 + '@esbuild/linux-mips64el': 0.25.12 + '@esbuild/linux-ppc64': 0.25.12 + '@esbuild/linux-riscv64': 0.25.12 + '@esbuild/linux-s390x': 0.25.12 + '@esbuild/linux-x64': 0.25.12 + '@esbuild/netbsd-arm64': 0.25.12 + '@esbuild/netbsd-x64': 0.25.12 + '@esbuild/openbsd-arm64': 0.25.12 + '@esbuild/openbsd-x64': 0.25.12 + '@esbuild/openharmony-arm64': 0.25.12 + '@esbuild/sunos-x64': 0.25.12 + '@esbuild/win32-arm64': 0.25.12 + '@esbuild/win32-ia32': 0.25.12 + '@esbuild/win32-x64': 0.25.12 + + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + + escalade@3.2.0: {} + + escape-string-regexp@4.0.0: {} + + eslint-config-prettier@10.1.8(eslint@10.15.0(jiti@2.7.0)): + dependencies: + eslint: 10.15.0(jiti@2.7.0) + + eslint-import-context@0.1.9(unrs-resolver@1.13.0): + dependencies: + get-tsconfig: 4.14.3 + stable-hash-x: 0.2.0 + optionalDependencies: + unrs-resolver: 1.13.0 + + eslint-import-resolver-typescript@4.4.5(eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0)))(eslint@10.15.0(jiti@2.7.0)): + dependencies: + debug: 4.4.3 + eslint: 10.15.0(jiti@2.7.0) + eslint-import-context: 0.1.9(unrs-resolver@1.13.0) + get-tsconfig: 4.14.3 + is-bun-module: 2.0.0 + stable-hash-x: 0.2.0 + tinyglobby: 0.2.17 + unrs-resolver: 1.13.0 + optionalDependencies: + eslint-plugin-import-x: 4.18.1(@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0)) + transitivePeerDependencies: + - supports-color + + eslint-plugin-import-x@4.18.1(@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0)): + dependencies: + '@typescript-eslint/types': 8.72.2 + cjs-module-lexer: 2.3.0 + comment-parser: 1.4.9 + debug: 4.4.3 + es-module-lexer: 3.0.4 + eslint: 10.15.0(jiti@2.7.0) + eslint-import-context: 0.1.9(unrs-resolver@1.13.0) + is-glob: 4.0.3 + minimatch: 11.0.8 + semver: 7.8.6 + stable-hash-x: 0.2.0 + unrs-resolver: 1.13.0 + optionalDependencies: + '@typescript-eslint/utils': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + transitivePeerDependencies: + - supports-color + + eslint-plugin-sonarjs@4.2.2(eslint@10.15.0(jiti@2.7.0)): + dependencies: + '@eslint-community/regexpp': 4.12.3 + '@sonarsource/analyzer-commons-configurations': 2.31.0-5284 + builtin-modules: 3.3.0 + bytes: 3.1.2 + eslint: 10.15.0(jiti@2.7.0) + functional-red-black-tree: 1.0.1 + globals: 17.14.0 + jsx-ast-utils-x: 0.1.0 + lodash.merge: 4.6.2 + minimatch: 10.2.6 + scslre: 0.3.0 + semver: 7.8.6 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + yaml: 2.9.1 + + eslint-plugin-unicorn@79.0.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3): + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0(jiti@2.7.0)) + '@eslint/css-tree': 4.1.2 + browserslist: 4.29.5 + change-case: 5.4.4 + ci-info: 4.5.0 + core-js-compat: 3.51.0 + detect-indent: 7.0.2 + entities: 8.1.0 + eslint: 10.15.0(jiti@2.7.0) + find-up-simple: 1.0.1 + globals: 17.14.0 + identifier-regex: 1.1.0 + indent-string: 5.0.0 + is-builtin-module: 5.0.0 + micromark: 4.0.3 + parse5: 8.1.1 + pluralize: 8.0.0 + quote-js-string: 0.1.0 + regjsparser: 0.13.4 + reserved-identifiers: 1.2.0 + semver: 7.8.6 + strip-indent: 4.1.1 + yaml: 2.9.1 + optionalDependencies: + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + eslint-scope@9.1.2: + dependencies: + '@types/esrecurse': 4.3.1 + '@types/estree': 1.0.10 + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@10.15.0(jiti@2.7.0): + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0(jiti@2.7.0)) + '@eslint-community/regexpp': 4.12.3 + '@eslint/config-array': 0.23.6 + '@eslint/config-helpers': 0.7.0 + '@eslint/core': 1.2.1 + '@eslint/plugin-kit': 0.7.3 + '@humanfs/node': 0.16.8 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.10 + ajv: 6.15.0 + cross-spawn: 7.0.6 + debug: 4.4.3 + escape-string-regexp: 4.0.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + espree: 11.2.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 11.1.5 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + minimatch: 11.0.8 + natural-compare: 1.4.0 + optionator: 0.9.4 + optionalDependencies: + jiti: 2.7.0 + transitivePeerDependencies: + - supports-color + + espree@11.2.0: + dependencies: + acorn: 8.19.0 + acorn-jsx: 5.3.2(acorn@8.19.0) + eslint-visitor-keys: 5.0.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.10 + + esutils@2.0.3: {} + + expect-type@1.4.0: {} + + fast-copy@4.3.1: {} + + fast-deep-equal@3.1.3: {} + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fast-safe-stringify@2.1.1: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + file-entry-cache@11.1.5: + dependencies: + flat-cache: 6.1.23 + + find-up-simple@1.0.1: {} + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@6.1.23: + dependencies: + cacheable: 2.5.0 + flatted: 3.4.4 + hookified: 1.15.1 + + flatted@3.4.4: {} + + fsevents@2.3.3: + optional: true + + functional-red-black-tree@1.0.1: {} + + get-tsconfig@4.14.3: + dependencies: + resolve-pkg-maps: 1.0.0 + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + globals@17.14.0: {} + + hashery@1.5.1: + dependencies: + hookified: 1.15.1 + + help-me@5.0.0: {} + + hookified@1.15.1: {} + + hookified@2.2.0: {} + + identifier-regex@1.1.0: + dependencies: + reserved-identifiers: 1.2.0 + + ignore@5.3.2: {} + + ignore@7.0.14: {} + + imurmurhash@0.1.4: {} + + indent-string@5.0.0: {} + + is-builtin-module@5.0.0: + dependencies: + builtin-modules: 5.5.0 + + is-bun-module@2.0.0: + dependencies: + semver: 7.8.6 + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + isexe@2.0.0: {} + + jiti@2.7.0: {} + + joycon@3.1.1: {} + + jsesc@3.1.0: {} + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + jsx-ast-utils-x@0.1.0: {} + + keyv@5.6.0: + dependencies: + '@keyv/serialize': 1.1.1 + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + lodash.merge@4.6.2: {} + + lodash.snakecase@4.1.1: {} + + lodash@4.18.1: {} + + luxon@3.7.2: {} + + magic-bytes.js@1.13.1: {} + + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + mdn-data@2.37.2: {} + + micromark-core-commonmark@2.0.4: + dependencies: + decode-named-character-reference: 1.3.0 + devlop: 1.1.0 + micromark-factory-destination: 2.0.1 + micromark-factory-label: 2.0.1 + micromark-factory-space: 2.1.0 + micromark-factory-title: 2.0.1 + micromark-factory-whitespace: 2.0.1 + micromark-util-character: 2.1.1 + micromark-util-chunked: 2.0.1 + micromark-util-classify-character: 2.0.1 + micromark-util-edit-map: 1.0.0 + micromark-util-html-tag-name: 2.0.1 + micromark-util-normalize-identifier: 2.0.1 + micromark-util-resolve-all: 2.0.1 + micromark-util-subtokenize: 2.1.0 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-factory-destination@2.0.1: + dependencies: + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-factory-label@2.0.1: + dependencies: + devlop: 1.1.0 + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-factory-space@2.1.0: + dependencies: + micromark-util-character: 2.1.1 + micromark-util-types: 2.0.3 + + micromark-factory-title@2.0.1: + dependencies: + micromark-factory-space: 2.1.0 + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-factory-whitespace@2.0.1: + dependencies: + micromark-factory-space: 2.1.0 + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-util-character@2.1.1: + dependencies: + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-util-chunked@2.0.1: + dependencies: + micromark-util-symbol: 2.0.1 + + micromark-util-classify-character@2.0.1: + dependencies: + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-util-combine-extensions@2.0.1: + dependencies: + micromark-util-chunked: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-util-decode-numeric-character-reference@2.0.2: + dependencies: + micromark-util-symbol: 2.0.1 + + micromark-util-edit-map@1.0.0: + dependencies: + micromark-util-types: 2.0.3 + + micromark-util-encode@2.0.1: {} + + micromark-util-html-tag-name@2.0.1: {} + + micromark-util-normalize-identifier@2.0.1: + dependencies: + micromark-util-symbol: 2.0.1 + + micromark-util-resolve-all@2.0.1: + dependencies: + micromark-util-types: 2.0.3 + + micromark-util-sanitize-uri@2.0.1: + dependencies: + micromark-util-character: 2.1.1 + micromark-util-encode: 2.0.1 + micromark-util-symbol: 2.0.1 + + micromark-util-subtokenize@2.1.0: + dependencies: + devlop: 1.1.0 + micromark-util-chunked: 2.0.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + + micromark-util-symbol@2.0.1: {} + + micromark-util-types@2.0.3: {} + + micromark@4.0.3: + dependencies: + '@types/debug': 4.1.13 + debug: 4.4.3 + decode-named-character-reference: 1.3.0 + devlop: 1.1.0 + micromark-core-commonmark: 2.0.4 + micromark-factory-space: 2.1.0 + micromark-util-character: 2.1.1 + micromark-util-chunked: 2.0.1 + micromark-util-combine-extensions: 2.0.1 + micromark-util-decode-numeric-character-reference: 2.0.2 + micromark-util-edit-map: 1.0.0 + micromark-util-encode: 2.0.1 + micromark-util-normalize-identifier: 2.0.1 + micromark-util-resolve-all: 2.0.1 + micromark-util-sanitize-uri: 2.0.1 + micromark-util-subtokenize: 2.1.0 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.3 + transitivePeerDependencies: + - supports-color + + minimatch@10.2.6: + dependencies: + brace-expansion: 5.0.13 + + minimatch@11.0.8: + dependencies: + '@isaacs/nonrecursive-glob-match': 1.1.0 + brace-expansion: 5.0.13 + + minimist@1.2.8: {} + + ms@2.1.3: {} + + nanoid@3.3.20: {} + + napi-postinstall@0.3.8: {} + + natural-compare@1.4.0: {} + + node-releases@2.0.64: {} + + obug@3.0.0: {} + + on-exit-leak-free@2.1.2: {} + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + parse5@8.1.1: + dependencies: + entities: 9.0.0 + + path-exists@4.0.0: {} + + path-key@3.1.1: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + pino-abstract-transport@3.0.0: + dependencies: + split2: 4.2.0 + + pino-pretty@13.2.0: + dependencies: + colorette: 2.0.20 + dateformat: 4.6.3 + fast-copy: 4.3.1 + fast-safe-stringify: 2.1.1 + help-me: 5.0.0 + joycon: 3.1.1 + minimist: 1.2.8 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pump: 3.0.4 + secure-json-parse: 4.1.1 + sonic-boom: 5.0.2 + strip-json-comments: 5.1.0 + + pino-std-serializers@7.1.0: {} + + pino@10.4.0: + dependencies: + '@pinojs/redact': 0.4.0 + atomic-sleep: 1.0.0 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pino-std-serializers: 7.1.0 + process-warning: 5.1.1 + quick-format-unescaped: 4.0.4 + real-require: 1.0.0 + safe-stable-stringify: 2.5.0 + sonic-boom: 4.2.1 + thread-stream: 4.2.1 + + pluralize@8.0.0: {} + + postcss@8.5.33: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + postgres@3.4.9: {} + + prelude-ls@1.2.1: {} + + prettier@3.10.1: {} + + process-warning@5.1.1: {} + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + + punycode@2.3.1: {} + + qified@0.10.1: + dependencies: + hookified: 2.2.0 + + quick-format-unescaped@4.0.4: {} + + quote-js-string@0.1.0: {} + + real-require@1.0.0: {} + + refa@0.12.1: + dependencies: + '@eslint-community/regexpp': 4.12.3 + + regexp-ast-analysis@0.7.1: + dependencies: + '@eslint-community/regexpp': 4.12.3 + refa: 0.12.1 + + regjsparser@0.13.4: + dependencies: + jsesc: 3.1.0 + + reserved-identifiers@1.2.0: {} + + resolve-pkg-maps@1.0.0: {} + + rolldown@1.2.19: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.1.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.19 + '@rolldown/binding-android-arm64': 1.2.19 + '@rolldown/binding-darwin-arm64': 1.2.19 + '@rolldown/binding-darwin-x64': 1.2.19 + '@rolldown/binding-freebsd-x64': 1.2.19 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.19 + '@rolldown/binding-linux-arm64-gnu': 1.2.19 + '@rolldown/binding-linux-arm64-musl': 1.2.19 + '@rolldown/binding-linux-ppc64-gnu': 1.2.19 + '@rolldown/binding-linux-s390x-gnu': 1.2.19 + '@rolldown/binding-linux-x64-gnu': 1.2.19 + '@rolldown/binding-linux-x64-musl': 1.2.19 + '@rolldown/binding-openharmony-arm64': 1.2.19 + '@rolldown/binding-wasm32-wasi': 1.2.19 + '@rolldown/binding-win32-arm64-msvc': 1.2.19 + '@rolldown/binding-win32-x64-msvc': 1.2.19 + + safe-stable-stringify@2.5.0: {} + + scslre@0.3.0: + dependencies: + '@eslint-community/regexpp': 4.12.3 + refa: 0.12.1 + regexp-ast-analysis: 0.7.1 + + secure-json-parse@4.1.1: {} + + semver@7.8.6: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + sonic-boom@4.2.1: + dependencies: + atomic-sleep: 1.0.0 + + sonic-boom@5.0.2: + dependencies: + atomic-sleep: 1.0.0 + + source-map-js@1.2.2: {} + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + split2@4.2.0: {} + + stable-hash-x@0.2.0: {} + + std-env@4.3.0: {} + + strip-indent@4.1.1: {} + + strip-json-comments@5.1.0: {} + + thread-stream@4.2.1: + dependencies: + real-require: 1.0.0 + + tinybench@6.2.3: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + ts-api-utils@2.5.0(typescript@6.0.3): + dependencies: + typescript: 6.0.3 + + ts-mixer@6.0.4: {} + + tslib@2.9.1: {} + + tsx@4.23.15: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + typescript-eslint@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3): + dependencies: + '@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/parser': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + '@typescript-eslint/typescript-estree': 8.72.2(typescript@6.0.3) + '@typescript-eslint/utils': 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) + eslint: 10.15.0(jiti@2.7.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + + typescript@6.0.3: {} + + undici-types@7.24.6: {} + + undici-types@8.9.0: {} + + undici@6.29.1: {} + + unrs-resolver@1.13.0: + dependencies: + napi-postinstall: 0.3.8 + optionalDependencies: + '@unrs/resolver-binding-android-arm-eabi': 1.13.0 + '@unrs/resolver-binding-android-arm64': 1.13.0 + '@unrs/resolver-binding-darwin-arm64': 1.13.0 + '@unrs/resolver-binding-darwin-x64': 1.13.0 + '@unrs/resolver-binding-freebsd-x64': 1.13.0 + '@unrs/resolver-binding-linux-arm-gnueabihf': 1.13.0 + '@unrs/resolver-binding-linux-arm-musleabihf': 1.13.0 + '@unrs/resolver-binding-linux-arm64-gnu': 1.13.0 + '@unrs/resolver-binding-linux-arm64-musl': 1.13.0 + '@unrs/resolver-binding-linux-loong64-gnu': 1.13.0 + '@unrs/resolver-binding-linux-loong64-musl': 1.13.0 + '@unrs/resolver-binding-linux-ppc64-gnu': 1.13.0 + '@unrs/resolver-binding-linux-riscv64-gnu': 1.13.0 + '@unrs/resolver-binding-linux-riscv64-musl': 1.13.0 + '@unrs/resolver-binding-linux-s390x-gnu': 1.13.0 + '@unrs/resolver-binding-linux-x64-gnu': 1.13.0 + '@unrs/resolver-binding-linux-x64-musl': 1.13.0 + '@unrs/resolver-binding-openharmony-arm64': 1.13.0 + '@unrs/resolver-binding-win32-arm64-msvc': 1.13.0 + '@unrs/resolver-binding-win32-ia32-msvc': 1.13.0 + '@unrs/resolver-binding-win32-x64-msvc': 1.13.0 + + update-browserslist-db@1.3.4(browserslist@4.29.5): + dependencies: + browserslist: 4.29.5 + escalade: 3.2.0 + picocolors: 1.1.1 + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.33 + rolldown: 1.2.19 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.19.2 + esbuild: 0.28.2 + fsevents: 2.3.3 + jiti: 2.7.0 + tsx: 4.23.15 + yaml: 2.9.1 + + vitest@5.1.0(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.1.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.5 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.3 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 24.19.2 + transitivePeerDependencies: + - msw + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@3.2.1: {} + + word-wrap@1.2.5: {} + + wrappy@1.0.2: {} + + ws@8.23.0: {} + + yaml@2.9.1: {} + + yocto-queue@0.1.0: {} + + zod@4.6.7: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..5ed0b5a --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +allowBuilds: + esbuild: true diff --git a/src/reset.d.ts b/src/reset.d.ts new file mode 100644 index 0000000..12bd3ed --- /dev/null +++ b/src/reset.d.ts @@ -0,0 +1 @@ +import '@total-typescript/ts-reset'; diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..af7cb03 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "rootDir": "src", + "outDir": "dist", + "sourceMap": true + }, + "include": ["src"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..1f899a2 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"], + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "forceConsistentCasingInFileNames": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "noEmitOnError": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "noEmit": true + }, + "include": ["src", "tests", "scripts", "*.config.ts"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..1b6a808 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['src/**/*.test.ts', 'tests/**/*.test.ts'], + globalSetup: ['tests/global-setup.ts'], + // Database tests share one database, so files run one at a time. + fileParallelism: false, + }, +}); From 2941d5e9897a9c4b3043c1f7ae5bbf1f177933bf Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 002/199] feat(core): config, logging, feature registry and interaction router --- src/core/config.ts | 53 ++++++++++ src/core/define.ts | 82 +++++++++++++++ src/core/discord/client.ts | 22 ++++ src/core/discord/errors.ts | 34 +++++++ src/core/discord/registration.ts | 21 ++++ src/core/discord/router.test.ts | 148 +++++++++++++++++++++++++++ src/core/discord/router.ts | 167 +++++++++++++++++++++++++++++++ src/core/feature.ts | 122 ++++++++++++++++++++++ src/core/logger.ts | 15 +++ src/core/registry.test.ts | 82 +++++++++++++++ src/core/registry.ts | 84 ++++++++++++++++ src/shared/errors.ts | 17 ++++ 12 files changed, 847 insertions(+) create mode 100644 src/core/config.ts create mode 100644 src/core/define.ts create mode 100644 src/core/discord/client.ts create mode 100644 src/core/discord/errors.ts create mode 100644 src/core/discord/registration.ts create mode 100644 src/core/discord/router.test.ts create mode 100644 src/core/discord/router.ts create mode 100644 src/core/feature.ts create mode 100644 src/core/logger.ts create mode 100644 src/core/registry.test.ts create mode 100644 src/core/registry.ts create mode 100644 src/shared/errors.ts diff --git a/src/core/config.ts b/src/core/config.ts new file mode 100644 index 0000000..a40ea17 --- /dev/null +++ b/src/core/config.ts @@ -0,0 +1,53 @@ +import { IANAZone } from 'luxon'; +import { z } from 'zod'; + +// Blank values in .env files arrive as '' and mean "not set". +const optional = (schema: T) => + z.preprocess( + (value) => (value === '' ? undefined : value), + schema.optional(), + ); + +const snowflake = z.string().regex(/^\d{17,20}$/, 'must be a Discord ID'); + +const envSchema = z.object({ + DISCORD_TOKEN: z.string().min(1), + DISCORD_APPLICATION_ID: optional(snowflake), + DISCORD_GUILD_ID: optional(snowflake), + + DATABASE_URL: z.url(), + + LOG_LEVEL: z + .enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']) + .default('info'), + DEFAULT_TIMEZONE: z + .string() + .default('Europe/Tallinn') + .refine((zone) => IANAZone.isValidZone(zone), 'must be an IANA timezone'), + + ROLE_SELECTION_CHANNEL_ID: optional(snowflake), + TARKVARA_ROLE_ID: optional(snowflake), + HELPDESK_ROLE_ID: optional(snowflake), + KULTUUR_ROLE_ID: optional(snowflake), + + REDMINE_BASE_URL: optional(z.url()), + REDMINE_API_KEY: optional(z.string().min(1)), + CREDENTIAL_ENCRYPTION_KEY: optional( + z + .string() + .refine( + (key) => Buffer.from(key, 'base64').length === 32, + 'must be 32 bytes encoded as base64', + ), + ), +}); + +export type Config = z.infer; + +export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { + const result = envSchema.safeParse(env); + if (!result.success) { + throw new Error(`Invalid configuration:\n${z.prettifyError(result.error)}`); + } + return result.data; +} diff --git a/src/core/define.ts b/src/core/define.ts new file mode 100644 index 0000000..c7268b6 --- /dev/null +++ b/src/core/define.ts @@ -0,0 +1,82 @@ +import { MessageFlags, type ClientEvents } from 'discord.js'; +import type { z } from 'zod'; +import { PermanentError } from '../shared/errors.js'; +import { subcommandPath } from './discord/router.js'; +import type { + AppContext, + CommandInteraction, + EventListener, + Job, + JobInfo, + JobOutcome, + SlashCommand, +} from './feature.js'; + +export function defineJob(definition: { + type: string; + payload: S; + maxAttempts?: number; + handle: ( + payload: z.infer, + info: JobInfo, + ctx: AppContext, + ) => Promise; +}): Job> { + return { + type: definition.type, + maxAttempts: definition.maxAttempts ?? 5, + run: async (raw, info, ctx) => { + const parsed = definition.payload.safeParse(raw); + if (!parsed.success) { + throw new PermanentError(`Invalid payload: ${parsed.error.message}`); + } + return (await definition.handle(parsed.data, info, ctx)) ?? null; + }, + }; +} + +export function defineListener( + event: K, + handle: (ctx: AppContext, ...args: ClientEvents[K]) => Promise, +): EventListener { + return { + event, + attach: (client, ctx) => { + client.on(event, (...args) => { + handle(ctx, ...args).catch((error: unknown) => { + ctx.log.error({ err: error, event }, 'Event listener failed'); + }); + }); + }, + }; +} + +type SubcommandHandler = ( + interaction: CommandInteraction, + ctx: AppContext, +) => Promise; + +/** Dispatches a command to the handler for its subcommand path. */ +export function bySubcommand( + handlers: Record, +): SlashCommand['execute'] { + return async (interaction, ctx) => { + const path = subcommandPath(interaction); + const handler = handlers[path]; + if (!handler) { + throw new Error(`No handler for /${interaction.commandName} ${path}`); + } + await handler(interaction, ctx); + }; +} + +/** + * Acknowledges privately before running a handler that may take longer than + * Discord's three-second deadline. Reply with `respond()` afterwards. + */ +export function deferred(handler: SubcommandHandler): SubcommandHandler { + return async (interaction, ctx) => { + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await handler(interaction, ctx); + }; +} diff --git a/src/core/discord/client.ts b/src/core/discord/client.ts new file mode 100644 index 0000000..acd049e --- /dev/null +++ b/src/core/discord/client.ts @@ -0,0 +1,22 @@ +import { Client, GatewayIntentBits, Partials } from 'discord.js'; + +/** + * Only non-privileged intents are requested. Members are fetched over REST + * when needed, so the GuildMembers and MessageContent intents are not used. + * Partials let reaction events arrive for messages sent before a restart. + */ +export function createClient(): Client { + return new Client({ + intents: [ + GatewayIntentBits.Guilds, + GatewayIntentBits.GuildMessageReactions, + ], + partials: [ + Partials.Message, + Partials.Channel, + Partials.Reaction, + Partials.User, + ], + allowedMentions: { parse: [] }, + }); +} diff --git a/src/core/discord/errors.ts b/src/core/discord/errors.ts new file mode 100644 index 0000000..68e2652 --- /dev/null +++ b/src/core/discord/errors.ts @@ -0,0 +1,34 @@ +import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; +import { PermanentError } from '../../shared/errors.js'; + +const permanentCodes = new Set([ + RESTJSONErrorCodes.UnknownChannel, + RESTJSONErrorCodes.UnknownGuild, + RESTJSONErrorCodes.UnknownMember, + RESTJSONErrorCodes.UnknownMessage, + RESTJSONErrorCodes.UnknownRole, + RESTJSONErrorCodes.UnknownUser, + RESTJSONErrorCodes.MissingAccess, + RESTJSONErrorCodes.MissingPermissions, + RESTJSONErrorCodes.CannotSendMessagesToThisUser, +]); + +/** Deleted or inaccessible Discord objects; retrying will not help. */ +export function isPermanentDiscordError(error: unknown): boolean { + return error instanceof DiscordAPIError && permanentCodes.has(error.code); +} + +/** Rethrows permanent Discord failures as PermanentError for the scheduler. */ +export function asJobError(error: unknown): unknown { + return isPermanentDiscordError(error) && error instanceof Error + ? new PermanentError(error.message) + : error; +} + +export function isUnknownObject(error: unknown): boolean { + return ( + error instanceof DiscordAPIError && + (error.code === RESTJSONErrorCodes.UnknownMessage || + error.code === RESTJSONErrorCodes.UnknownChannel) + ); +} diff --git a/src/core/discord/registration.ts b/src/core/discord/registration.ts new file mode 100644 index 0000000..a683e4d --- /dev/null +++ b/src/core/discord/registration.ts @@ -0,0 +1,21 @@ +import { REST, Routes } from 'discord.js'; +import type { Registry } from '../registry.js'; + +/** Registers to one guild when given (instant), otherwise globally. */ +export async function registerCommands( + registry: Registry, + options: { + token: string; + applicationId: string; + guildId?: string | undefined; + }, +): Promise { + const body = [...registry.commands.values()].map((command) => command.data); + const rest = new REST().setToken(options.token); + const route = + options.guildId === undefined + ? Routes.applicationCommands(options.applicationId) + : Routes.applicationGuildCommands(options.applicationId, options.guildId); + await rest.put(route, { body }); + return body.length; +} diff --git a/src/core/discord/router.test.ts b/src/core/discord/router.test.ts new file mode 100644 index 0000000..c077bcd --- /dev/null +++ b/src/core/discord/router.test.ts @@ -0,0 +1,148 @@ +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { UserError } from '../../shared/errors.js'; +import type { AppContext, Feature } from '../feature.js'; +import { buildRegistry } from '../registry.js'; +import { createInteractionHandler } from './router.js'; + +function context(allowed: boolean) { + const require = vi.fn(async () => { + if (!allowed) { + throw new UserError('denied'); + } + }); + const ctx = { + log: pino({ level: 'silent' }), + authz: { require, can: vi.fn() }, + } as unknown as AppContext; + return { ctx, require }; +} + +function commandInteraction(commandName: string, subcommand: string | null) { + return { + inCachedGuild: () => true, + isAutocomplete: () => false, + isChatInputCommand: () => true, + isMessageComponent: () => false, + isModalSubmit: () => false, + commandName, + guildId: 'g', + user: { id: 'u' }, + member: { id: 'u' }, + options: { + getSubcommandGroup: () => null, + getSubcommand: () => subcommand, + }, + deferred: false, + replied: false, + reply: vi.fn(async () => undefined), + followUp: vi.fn(async () => undefined), + }; +} + +function componentInteraction(customId: string) { + return { + ...commandInteraction('', null), + isChatInputCommand: () => false, + isMessageComponent: () => true, + customId, + }; +} + +const execute = vi.fn(async () => undefined); +const features: Feature[] = [ + { + name: 'demo', + commands: [ + { + data: { name: 'demo', description: 'demo' }, + permissions: { manage: 'demo:manage' }, + execute, + }, + { + data: { name: 'boom', description: 'boom' }, + execute: async () => { + throw new Error('kaboom'); + }, + }, + ], + components: [{ prefix: 'demo:press', permission: 'demo:manage', execute }], + }, +]; + +describe('interaction router', () => { + const registry = buildRegistry(features); + + it('routes public subcommands without a permission check', async () => { + const { ctx, require } = context(false); + execute.mockClear(); + await createInteractionHandler( + registry, + ctx, + )(commandInteraction('demo', 'view') as never); + expect(require).not.toHaveBeenCalled(); + expect(execute).toHaveBeenCalledOnce(); + }); + + it('enforces declared permissions before executing', async () => { + const { ctx, require } = context(false); + execute.mockClear(); + const interaction = commandInteraction('demo', 'manage'); + await createInteractionHandler(registry, ctx)(interaction as never); + expect(require).toHaveBeenCalledWith(interaction.member, 'demo:manage'); + expect(execute).not.toHaveBeenCalled(); + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ content: 'denied' }), + ); + }); + + it('rechecks permissions on persistent components and passes arguments', async () => { + const allowed = context(true); + execute.mockClear(); + const interaction = componentInteraction('demo:press:42:x'); + await createInteractionHandler(registry, allowed.ctx)(interaction as never); + expect(allowed.require).toHaveBeenCalledWith( + interaction.member, + 'demo:manage', + ); + expect(execute).toHaveBeenCalledWith(interaction, ['42', 'x'], allowed.ctx); + }); + + it('answers unknown components instead of failing silently', async () => { + const { ctx } = context(true); + const interaction = componentInteraction('gone:button:1'); + await createInteractionHandler(registry, ctx)(interaction as never); + expect(interaction.reply).toHaveBeenCalledWith( + expect.objectContaining({ content: 'This control is no longer active.' }), + ); + }); + + it('hides unexpected errors behind a reference', async () => { + const { ctx } = context(true); + const interaction = commandInteraction('boom', null); + await createInteractionHandler(registry, ctx)(interaction as never); + const [[reply]] = interaction.reply.mock.calls as unknown as [ + [{ content: string }], + ]; + expect(reply.content).toMatch( + /^Something went wrong\. Reference: `\w{8}`$/, + ); + }); + + it('completes a deferred reply, or follows up after a real one', async () => { + const { ctx } = context(true); + const handle = createInteractionHandler(registry, ctx); + const pending = { + ...commandInteraction('boom', null), + deferred: true, + editReply: vi.fn(async () => undefined), + }; + await handle(pending as never); + expect(pending.editReply).toHaveBeenCalledOnce(); + expect(pending.reply).not.toHaveBeenCalled(); + + const answered = { ...commandInteraction('boom', null), replied: true }; + await handle(answered as never); + expect(answered.followUp).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/core/discord/router.ts b/src/core/discord/router.ts new file mode 100644 index 0000000..d52fa31 --- /dev/null +++ b/src/core/discord/router.ts @@ -0,0 +1,167 @@ +import { randomUUID } from 'node:crypto'; +import { + MessageFlags, + type AutocompleteInteraction, + type BaseMessageOptions, + type Interaction, +} from 'discord.js'; +import { ignore, UserError } from '../../shared/errors.js'; +import type { + AppContext, + CommandInteraction, + ComponentInteraction, +} from '../feature.js'; +import { parseCustomId, type Registry } from '../registry.js'; + +type Repliable = CommandInteraction | ComponentInteraction; + +/** + * Answers privately, whatever state the interaction is in: a fresh reply, + * the completion of a deferred reply, or a follow-up after an answer. + */ +export async function respond( + interaction: Repliable, + content: string | Pick, +): Promise { + const message = { + ...(typeof content === 'string' ? { content } : content), + allowedMentions: { parse: [] }, + }; + if (interaction.replied) { + await interaction.followUp({ ...message, flags: MessageFlags.Ephemeral }); + } else if (interaction.deferred) { + await interaction.editReply(message); + } else { + await interaction.reply({ ...message, flags: MessageFlags.Ephemeral }); + } +} + +export function subcommandPath(interaction: CommandInteraction): string { + return [ + interaction.options.getSubcommandGroup(false), + interaction.options.getSubcommand(false), + ] + .filter(Boolean) + .join(' '); +} + +async function runCommand( + registry: Registry, + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const command = registry.commands.get(interaction.commandName); + if (!command) { + throw new UserError('This command is no longer available.'); + } + const permissions = command.permissions ?? {}; + const required = permissions['*'] ?? permissions[subcommandPath(interaction)]; + if (required !== undefined) { + await ctx.authz.require(interaction.member, required); + } + await command.execute(interaction, ctx); +} + +async function runComponent( + registry: Registry, + interaction: ComponentInteraction, + ctx: AppContext, +): Promise { + const parsed = parseCustomId(interaction.customId); + const handler = parsed && registry.components.get(parsed.prefix); + if (!parsed || !handler) { + throw new UserError('This control is no longer active.'); + } + if (handler.permission !== undefined) { + await ctx.authz.require(interaction.member, handler.permission); + } + await handler.execute(interaction, parsed.args, ctx); +} + +async function runAutocomplete( + registry: Registry, + interaction: AutocompleteInteraction<'cached'>, + ctx: AppContext, +): Promise { + const command = registry.commands.get(interaction.commandName); + try { + await command?.autocomplete?.(interaction, ctx); + } catch (error) { + ctx.log.warn( + { err: error, command: interaction.commandName }, + 'Autocomplete failed', + ); + } + if (!interaction.responded) { + await interaction.respond([]).catch(ignore); + } +} + +function describe(interaction: Repliable): Record { + return { + guildId: interaction.guildId, + userId: interaction.user.id, + ...(interaction.isChatInputCommand() + ? { + command: + `${interaction.commandName} ${subcommandPath(interaction)}`.trim(), + } + : { customId: interaction.customId }), + }; +} + +/** The single error boundary for every interaction the bot receives. */ +export function createInteractionHandler( + registry: Registry, + ctx: AppContext, +): (interaction: Interaction) => Promise { + return async (interaction) => { + if (!interaction.inCachedGuild()) { + if (interaction.isRepliable()) { + await interaction + .reply({ + content: 'Please use me inside the server.', + flags: MessageFlags.Ephemeral, + }) + .catch(ignore); + } + return; + } + if (interaction.isAutocomplete()) { + await runAutocomplete(registry, interaction, ctx); + return; + } + if ( + !interaction.isChatInputCommand() && + !interaction.isMessageComponent() && + !interaction.isModalSubmit() + ) { + return; + } + + try { + await (interaction.isChatInputCommand() + ? runCommand(registry, interaction, ctx) + : runComponent(registry, interaction, ctx)); + } catch (error) { + let message: string; + if (error instanceof UserError) { + message = error.message; + ctx.log.debug( + { ...describe(interaction), reason: error.message }, + 'Interaction rejected', + ); + } else { + const ref = randomUUID().slice(0, 8); + ctx.log.error( + { err: error, ref, ...describe(interaction) }, + 'Interaction failed', + ); + message = `Something went wrong. Reference: \`${ref}\``; + } + await respond(interaction, message).catch((replyError: unknown) => { + ctx.log.warn({ err: replyError }, 'Could not report interaction error'); + }); + } + }; +} diff --git a/src/core/feature.ts b/src/core/feature.ts new file mode 100644 index 0000000..ec700cd --- /dev/null +++ b/src/core/feature.ts @@ -0,0 +1,122 @@ +import type { + AnySelectMenuInteraction, + AutocompleteInteraction, + ButtonInteraction, + ChatInputCommandInteraction, + Client, + ClientEvents, + GuildMember, + ModalSubmitInteraction, + RESTPostAPIChatInputApplicationCommandsJSONBody, +} from 'discord.js'; +import type { Db } from '../db/client.js'; +import type { Config } from './config.js'; +import type { Logger } from './logger.js'; + +/** Action identifiers such as `event:create`; features declare their own. */ +export type Permission = `${string}:${string}`; + +export type PermissionDefinition = { + id: Permission; + description: string; +}; + +export type Authorizer = { + can: (member: GuildMember, permission: Permission) => Promise; + /** Throws a UserError when the member lacks the permission. */ + require: (member: GuildMember, permission: Permission) => Promise; +}; + +export type ScheduleOptions = { + runAt: Date; + /** Scheduling again with the same key replaces the pending job. */ + key?: string; + maxAttempts?: number; +}; + +export type Scheduler = { + schedule:

( + job: Job

, + payload: P, + options: ScheduleOptions, + ) => Promise; + cancel: (key: string) => Promise; +}; + +export type AppContext = { + client: Client; + db: Db; + log: Logger; + config: Config; + authz: Authorizer; + scheduler: Scheduler; +}; + +export type CommandInteraction = ChatInputCommandInteraction<'cached'>; + +export type SlashCommand = { + data: RESTPostAPIChatInputApplicationCommandsJSONBody; + /** + * Permission required per subcommand path ("create", "panel create"), or + * `'*'` for the whole command. Unlisted subcommands are open to members. + */ + permissions?: Partial>; + execute: (interaction: CommandInteraction, ctx: AppContext) => Promise; + autocomplete?: ( + interaction: AutocompleteInteraction<'cached'>, + ctx: AppContext, + ) => Promise; +}; + +export type ComponentInteraction = + | ButtonInteraction<'cached'> + | AnySelectMenuInteraction<'cached'> + | ModalSubmitInteraction<'cached'>; + +/** + * Handles buttons, select menus and modals whose custom ID starts with + * `prefix` followed by `:`. Remaining `:`-separated segments become `args`. + */ +export type ComponentHandler = { + prefix: string; + permission?: Permission; + execute: ( + interaction: ComponentInteraction, + args: readonly string[], + ctx: AppContext, + ) => Promise; +}; + +export type EventListener = { + event: keyof ClientEvents; + attach: (client: Client, ctx: AppContext) => void; +}; + +export type JobInfo = { + id: number; + /** When the job was due; handlers decide what lateness means for them. */ + runAt: Date; + attempt: number; +}; + +/** Returning a date makes the job recur at that time. */ +export type JobOutcome = null | { rescheduleAt: Date }; + +export type Job

= { + type: string; + maxAttempts: number; + run: (raw: unknown, info: JobInfo, ctx: AppContext) => Promise; + /** Carries the payload type for `Scheduler.schedule`; never set. */ + payloadType?: P; +}; + +export type Feature = { + name: string; + permissions?: readonly PermissionDefinition[]; + commands?: readonly SlashCommand[]; + components?: readonly ComponentHandler[]; + events?: readonly EventListener[]; + jobs?: ReadonlyArray>; + /** Runs once after the client is ready and migrations have applied. */ + start?: (ctx: AppContext) => Promise; +}; diff --git a/src/core/logger.ts b/src/core/logger.ts new file mode 100644 index 0000000..2656aa1 --- /dev/null +++ b/src/core/logger.ts @@ -0,0 +1,15 @@ +import { pino, type Logger } from 'pino'; + +export type { Logger } from 'pino'; + +export function createLogger(level: string): Logger { + const pretty = process.stdout.isTTY && process.env.NODE_ENV !== 'production'; + return pino({ + level, + redact: { + paths: ['*.token', '*.apiKey', '*.api_key', '*.password', 'headers'], + censor: '[redacted]', + }, + ...(pretty && { transport: { target: 'pino-pretty' } }), + }); +} diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts new file mode 100644 index 0000000..fb96c76 --- /dev/null +++ b/src/core/registry.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest'; +import type { Feature } from './feature.js'; +import { buildRegistry, customId, parseCustomId } from './registry.js'; + +const noop = async () => undefined; +const noopJob = async () => null; +const command = (name: string) => ({ + data: { name, description: name }, + execute: noop, +}); + +describe('buildRegistry', () => { + it('collects declarations from every feature', () => { + const registry = buildRegistry([ + { + name: 'a', + commands: [command('alpha')], + components: [{ prefix: 'a:click', execute: noop }], + }, + { name: 'b', permissions: [{ id: 'b:do', description: '' }] }, + ]); + expect([...registry.commands.keys()]).toEqual(['alpha']); + expect([...registry.components.keys()]).toEqual(['a:click']); + expect([...registry.permissions.keys()]).toEqual(['b:do']); + }); + + it.each<[string, Feature[]]>([ + ['feature', [{ name: 'a' }, { name: 'a' }]], + [ + 'command', + [ + { name: 'a', commands: [command('x')] }, + { name: 'b', commands: [command('x')] }, + ], + ], + [ + 'component prefix', + [ + { name: 'a', components: [{ prefix: 'x:y', execute: noop }] }, + { name: 'b', components: [{ prefix: 'x:y', execute: noop }] }, + ], + ], + [ + 'job type', + [ + { name: 'a', jobs: [{ type: 'j', maxAttempts: 1, run: noopJob }] }, + { name: 'b', jobs: [{ type: 'j', maxAttempts: 1, run: noopJob }] }, + ], + ], + [ + 'permission', + [ + { name: 'a', permissions: [{ id: 'p:x', description: '' }] }, + { name: 'b', permissions: [{ id: 'p:x', description: '' }] }, + ], + ], + ])('rejects a duplicate %s', (what, features) => { + expect(() => buildRegistry(features)).toThrow(`Duplicate ${what}`); + }); + + it('rejects malformed component prefixes', () => { + expect(() => + buildRegistry([ + { name: 'a', components: [{ prefix: 'a:b:c', execute: noop }] }, + ]), + ).toThrow('Invalid component prefix'); + }); +}); + +describe('custom IDs', () => { + it('round-trips prefix and arguments', () => { + expect(parseCustomId(customId('polls:vote', 12, 'x'))).toEqual({ + prefix: 'polls:vote', + args: ['12', 'x'], + }); + expect(parseCustomId('garbage')).toBeUndefined(); + }); + + it('enforces the Discord length limit', () => { + expect(() => customId('a:b', 'x'.repeat(100))).toThrow('100 characters'); + }); +}); diff --git a/src/core/registry.ts b/src/core/registry.ts new file mode 100644 index 0000000..0220d12 --- /dev/null +++ b/src/core/registry.ts @@ -0,0 +1,84 @@ +import type { + ComponentHandler, + Feature, + Job, + Permission, + PermissionDefinition, + SlashCommand, +} from './feature.js'; + +export type Registry = { + features: readonly Feature[]; + commands: ReadonlyMap; + components: ReadonlyMap; + jobs: ReadonlyMap>; + permissions: ReadonlyMap; +}; + +const componentPrefix = /^[a-z][a-z-]*:[a-z][a-z-]*$/; + +function addUnique( + map: Map, + key: string, + value: V, + what: string, +): void { + if (map.has(key)) { + throw new Error(`Duplicate ${what} "${key}"`); + } + map.set(key, value); +} + +export function buildRegistry(features: readonly Feature[]): Registry { + const names = new Map(); + const commands = new Map(); + const components = new Map(); + const jobs = new Map>(); + const permissions = new Map(); + + for (const feature of features) { + addUnique(names, feature.name, feature, 'feature'); + for (const command of feature.commands ?? []) { + addUnique(commands, command.data.name, command, 'command'); + } + for (const component of feature.components ?? []) { + if (!componentPrefix.test(component.prefix)) { + throw new Error(`Invalid component prefix "${component.prefix}"`); + } + addUnique(components, component.prefix, component, 'component prefix'); + } + for (const job of feature.jobs ?? []) { + addUnique(jobs, job.type, job, 'job type'); + } + for (const permission of feature.permissions ?? []) { + if (permissions.has(permission.id)) { + throw new Error(`Duplicate permission "${permission.id}"`); + } + permissions.set(permission.id, permission); + } + } + + return { features, commands, components, jobs, permissions }; +} + +/** Splits `feature:action:arg...` into its handler prefix and arguments. */ +export function parseCustomId( + id: string, +): { prefix: string; args: string[] } | undefined { + const [feature, action, ...args] = id.split(':'); + if (feature === undefined || action === undefined) { + return undefined; + } + return { prefix: `${feature}:${action}`, args }; +} + +export function customId( + prefix: string, + ...args: Array +): string { + const id = [prefix, ...args].join(':'); + if (id.length > 100) { + throw new Error(`Custom ID exceeds 100 characters: ${id}`); + } + return id; +} diff --git a/src/shared/errors.ts b/src/shared/errors.ts new file mode 100644 index 0000000..f274219 --- /dev/null +++ b/src/shared/errors.ts @@ -0,0 +1,17 @@ +/** + * An expected failure caused by user input or current state. Its message is + * safe to show to the user and it is not logged as an error. + */ +export class UserError extends Error { + override readonly name = 'UserError'; +} + +/** A job failure that retrying cannot fix. */ +export class PermanentError extends Error { + override readonly name = 'PermanentError'; +} + +/** For best-effort calls whose failure needs no handling, e.g. a late reply. */ +export function ignore(): void { + // Intentionally empty. +} From d8c2e717cd4d5517cd393c1cdda2e64ac8e75942 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 003/199] feat(core): persistent job scheduler, RBAC and guild settings --- scripts/migrate.ts | 12 ++ src/core/guild-settings.ts | 38 +++++ src/core/permissions/authorizer.test.ts | 111 ++++++++++++++ src/core/permissions/authorizer.ts | 45 ++++++ src/core/permissions/schema.ts | 17 +++ src/core/permissions/store.ts | 83 +++++++++++ src/core/scheduler/scheduler.test.ts | 184 ++++++++++++++++++++++++ src/core/scheduler/scheduler.ts | 137 ++++++++++++++++++ src/core/scheduler/schema.ts | 49 +++++++ src/core/scheduler/store.ts | 126 ++++++++++++++++ src/db/client.ts | 28 ++++ tests/db.ts | 30 ++++ tests/global-setup.ts | 19 +++ 13 files changed, 879 insertions(+) create mode 100644 scripts/migrate.ts create mode 100644 src/core/guild-settings.ts create mode 100644 src/core/permissions/authorizer.test.ts create mode 100644 src/core/permissions/authorizer.ts create mode 100644 src/core/permissions/schema.ts create mode 100644 src/core/permissions/store.ts create mode 100644 src/core/scheduler/scheduler.test.ts create mode 100644 src/core/scheduler/scheduler.ts create mode 100644 src/core/scheduler/schema.ts create mode 100644 src/core/scheduler/store.ts create mode 100644 src/db/client.ts create mode 100644 tests/db.ts create mode 100644 tests/global-setup.ts diff --git a/scripts/migrate.ts b/scripts/migrate.ts new file mode 100644 index 0000000..c98abb7 --- /dev/null +++ b/scripts/migrate.ts @@ -0,0 +1,12 @@ +import { z } from 'zod'; +import { connectDatabase, runMigrations } from '../src/db/client.js'; + +// The bot also migrates on startup; this runs migrations without starting it. +const url = z.url().parse(process.env.DATABASE_URL); +const database = connectDatabase(url); +try { + await runMigrations(database.db); + console.log('Migrations applied.'); +} finally { + await database.close(); +} diff --git a/src/core/guild-settings.ts b/src/core/guild-settings.ts new file mode 100644 index 0000000..002e76a --- /dev/null +++ b/src/core/guild-settings.ts @@ -0,0 +1,38 @@ +import { eq } from 'drizzle-orm'; +import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; +import type { Db } from '../db/client.js'; + +export const guildSettings = pgTable('guild_settings', { + guildId: text('guild_id').primaryKey(), + timezone: text('timezone'), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .notNull() + .defaultNow(), +}); + +/** Guild setting stored in the database wins over DEFAULT_TIMEZONE. */ +export async function getGuildTimezone( + db: Db, + guildId: string, + fallback: string, +): Promise { + const [row] = await db + .select({ timezone: guildSettings.timezone }) + .from(guildSettings) + .where(eq(guildSettings.guildId, guildId)); + return row?.timezone ?? fallback; +} + +export async function setGuildTimezone( + db: Db, + guildId: string, + timezone: string, +): Promise { + await db + .insert(guildSettings) + .values({ guildId, timezone }) + .onConflictDoUpdate({ + target: guildSettings.guildId, + set: { timezone, updatedAt: new Date() }, + }); +} diff --git a/src/core/permissions/authorizer.test.ts b/src/core/permissions/authorizer.test.ts new file mode 100644 index 0000000..138b2de --- /dev/null +++ b/src/core/permissions/authorizer.test.ts @@ -0,0 +1,111 @@ +import type { GuildMember } from 'discord.js'; +import { beforeAll, describe, expect, it } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import { UserError } from '../../shared/errors.js'; +import { createAuthorizer } from './authorizer.js'; +import { grant, listGrants, revoke } from './store.js'; + +function member( + guildId: string, + roleIds: string[], + admin = false, +): GuildMember { + return { + guild: { id: guildId }, + permissions: { has: () => admin }, + roles: { cache: new Map(roleIds.map((id) => [id, {}])) }, + } as unknown as GuildMember; +} + +describe.skipIf(noDatabase)('authorizer', () => { + const guildId = snowflake(); + const otherGuild = snowflake(); + const organizers = snowflake(); + const helpers = snowflake(); + + beforeAll(async () => { + const db = testDb(); + await grant(db, { + guildId, + roleId: organizers, + permission: 'event:create', + grantedBy: 'x', + }); + await grant(db, { + guildId, + roleId: helpers, + permission: 'poll:create', + grantedBy: 'x', + }); + }); + + it('denies by default and allows granted roles', async () => { + const authz = createAuthorizer(testDb()); + expect(await authz.can(member(guildId, []), 'event:create')).toBe(false); + expect(await authz.can(member(guildId, [organizers]), 'event:create')).toBe( + true, + ); + expect(await authz.can(member(guildId, [organizers]), 'poll:create')).toBe( + false, + ); + }); + + it('combines grants from all of a member’s roles', async () => { + const authz = createAuthorizer(testDb()); + const both = member(guildId, [organizers, helpers]); + expect(await authz.can(both, 'event:create')).toBe(true); + expect(await authz.can(both, 'poll:create')).toBe(true); + }); + + it('isolates grants per guild', async () => { + const authz = createAuthorizer(testDb()); + expect( + await authz.can(member(otherGuild, [organizers]), 'event:create'), + ).toBe(false); + }); + + it('lets Discord administrators do everything', async () => { + const authz = createAuthorizer(testDb()); + expect( + await authz.can(member(guildId, [], true), 'permissions:manage'), + ).toBe(true); + }); + + it('stops allowing after revocation', async () => { + const db = testDb(); + const authz = createAuthorizer(db); + const role = snowflake(); + expect( + await grant(db, { + guildId, + roleId: role, + permission: 'movie:manage', + grantedBy: 'x', + }), + ).toBe(true); + expect( + await grant(db, { + guildId, + roleId: role, + permission: 'movie:manage', + grantedBy: 'x', + }), + ).toBe(false); + expect(await listGrants(db, guildId, role)).toEqual([ + { roleId: role, permission: 'movie:manage' }, + ]); + expect( + await revoke(db, { guildId, roleId: role, permission: 'movie:manage' }), + ).toBe(true); + expect(await authz.can(member(guildId, [role]), 'movie:manage')).toBe( + false, + ); + }); + + it('require throws a user-facing error', async () => { + const authz = createAuthorizer(testDb()); + await expect( + authz.require(member(guildId, []), 'event:create'), + ).rejects.toBeInstanceOf(UserError); + }); +}); diff --git a/src/core/permissions/authorizer.ts b/src/core/permissions/authorizer.ts new file mode 100644 index 0000000..a1c5e90 --- /dev/null +++ b/src/core/permissions/authorizer.ts @@ -0,0 +1,45 @@ +import { PermissionFlagsBits, type GuildMember } from 'discord.js'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import type { Authorizer, Permission } from '../feature.js'; +import { hasGrant } from './store.js'; + +/** + * Members with Discord's Administrator permission (which includes the guild + * owner) hold every bot permission. Everyone else needs a grant on one of + * their roles; granting to @everyone makes an action open to all members. + */ +export function isAdministrator(member: GuildMember): boolean { + return member.permissions.has(PermissionFlagsBits.Administrator); +} + +export function createAuthorizer(db: Db): Authorizer { + const can = async (member: GuildMember, permission: Permission) => + isAdministrator(member) || + hasGrant(db, member.guild.id, [...member.roles.cache.keys()], permission); + + return { + can, + require: async (member, permission) => { + if (!(await can(member, permission))) { + throw new UserError( + `You need the \`${permission}\` permission for this.`, + ); + } + }, + }; +} + +/** + * Bot permissions never extend a member's reach: they may only direct the + * bot to post where they could post themselves. + */ +export function requireCanPost(member: GuildMember, channelId: string): void { + const channel = member.guild.channels.cache.get(channelId); + const allowed = channel + ?.permissionsFor(member) + .has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages]); + if (allowed !== true) { + throw new UserError(`You cannot post in <#${channelId}> yourself.`); + } +} diff --git a/src/core/permissions/schema.ts b/src/core/permissions/schema.ts new file mode 100644 index 0000000..e24729e --- /dev/null +++ b/src/core/permissions/schema.ts @@ -0,0 +1,17 @@ +import { pgTable, primaryKey, text, timestamp } from 'drizzle-orm/pg-core'; + +export const rolePermissions = pgTable( + 'role_permissions', + { + guildId: text('guild_id').notNull(), + roleId: text('role_id').notNull(), + permission: text('permission').notNull(), + grantedBy: text('granted_by').notNull(), + grantedAt: timestamp('granted_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + primaryKey({ columns: [table.guildId, table.roleId, table.permission] }), + ], +); diff --git a/src/core/permissions/store.ts b/src/core/permissions/store.ts new file mode 100644 index 0000000..c5c6aae --- /dev/null +++ b/src/core/permissions/store.ts @@ -0,0 +1,83 @@ +import { and, eq, inArray } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { rolePermissions } from './schema.js'; + +export async function hasGrant( + db: Db, + guildId: string, + roleIds: readonly string[], + permission: string, +): Promise { + if (roleIds.length === 0) { + return false; + } + const rows = await db + .select({ roleId: rolePermissions.roleId }) + .from(rolePermissions) + .where( + and( + eq(rolePermissions.guildId, guildId), + eq(rolePermissions.permission, permission), + inArray(rolePermissions.roleId, [...roleIds]), + ), + ) + .limit(1); + return rows.length > 0; +} + +/** Returns false when the grant already existed. */ +export async function grant( + db: Db, + input: { + guildId: string; + roleId: string; + permission: string; + grantedBy: string; + }, +): Promise { + const rows = await db + .insert(rolePermissions) + .values(input) + .onConflictDoNothing() + .returning({ roleId: rolePermissions.roleId }); + return rows.length > 0; +} + +/** Returns false when there was nothing to revoke. */ +export async function revoke( + db: Db, + input: { guildId: string; roleId: string; permission: string }, +): Promise { + const rows = await db + .delete(rolePermissions) + .where( + and( + eq(rolePermissions.guildId, input.guildId), + eq(rolePermissions.roleId, input.roleId), + eq(rolePermissions.permission, input.permission), + ), + ) + .returning({ roleId: rolePermissions.roleId }); + return rows.length > 0; +} + +export async function listGrants( + db: Db, + guildId: string, + roleId?: string, +): Promise> { + return db + .select({ + roleId: rolePermissions.roleId, + permission: rolePermissions.permission, + }) + .from(rolePermissions) + .where( + and( + eq(rolePermissions.guildId, guildId), + roleId === undefined ? undefined : eq(rolePermissions.roleId, roleId), + ), + ) + .orderBy(rolePermissions.roleId, rolePermissions.permission) + .limit(500); +} diff --git a/src/core/scheduler/scheduler.test.ts b/src/core/scheduler/scheduler.test.ts new file mode 100644 index 0000000..660cf5e --- /dev/null +++ b/src/core/scheduler/scheduler.test.ts @@ -0,0 +1,184 @@ +import { eq, sql } from 'drizzle-orm'; +import { pino } from 'pino'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { z } from 'zod'; +import { noDatabase, testDb } from '../../../tests/db.js'; +import { PermanentError } from '../../shared/errors.js'; +import { defineJob } from '../define.js'; +import type { AppContext } from '../feature.js'; +import { createScheduler, retryDelayMs } from './scheduler.js'; +import { scheduledJobs } from './schema.js'; +import { claimDueJobs } from './store.js'; + +const log = pino({ level: 'silent' }); + +describe.skipIf(noDatabase)('scheduler', () => { + const db = noDatabase ? undefined : testDb(); + const handle = + vi.fn<(payload: { n: number }) => Promise>(); + const job = defineJob({ + type: 'test:job', + payload: z.object({ n: z.number() }), + maxAttempts: 3, + handle: (payload) => handle(payload), + }); + + const setup = () => { + if (!db) { + throw new Error('unreachable'); + } + const scheduler = createScheduler(db, new Map([[job.type, job]]), log); + const ctx = { db, log } as unknown as AppContext; + return { db, scheduler, ctx }; + }; + const past = () => new Date(Date.now() - 1000); + const row = async (key: string) => { + const { db: database } = setup(); + const [found] = await database + .select() + .from(scheduledJobs) + .where(eq(scheduledJobs.key, key)); + return found; + }; + + beforeEach(async () => { + handle.mockReset(); + await setup().db.delete(scheduledJobs); + }); + + it('runs due jobs once and marks them done', async () => { + const { scheduler, ctx } = setup(); + handle.mockResolvedValue(null); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'a' }); + await scheduler.schedule( + job, + { n: 2 }, + { runAt: new Date(Date.now() + 60_000), key: 'b' }, + ); + + expect(await scheduler.tick(ctx)).toBe(1); + expect(await scheduler.tick(ctx)).toBe(0); + expect(handle).toHaveBeenCalledExactlyOnceWith({ n: 1 }); + expect((await row('a'))?.status).toBe('done'); + expect((await row('b'))?.status).toBe('pending'); + }); + + it('replaces a pending job scheduled with the same key', async () => { + const { scheduler, ctx } = setup(); + handle.mockResolvedValue(null); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'same' }); + await scheduler.schedule(job, { n: 2 }, { runAt: past(), key: 'same' }); + await scheduler.tick(ctx); + expect(handle).toHaveBeenCalledExactlyOnceWith({ n: 2 }); + }); + + it('does not run cancelled jobs', async () => { + const { scheduler, ctx } = setup(); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'c' }); + await scheduler.cancel('c'); + expect(await scheduler.tick(ctx)).toBe(0); + expect((await row('c'))?.status).toBe('cancelled'); + }); + + it('retries transient failures with backoff, then fails', async () => { + const { db: database, scheduler, ctx } = setup(); + handle.mockRejectedValue(new Error('discord down')); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'r' }); + + for (let attempt = 1; attempt <= 3; attempt++) { + await scheduler.tick(ctx); + const current = await row('r'); + expect(current?.attempts).toBe(attempt); + if (attempt < 3) { + expect(current?.status).toBe('pending'); + expect(current?.runAt.getTime()).toBeGreaterThan(Date.now()); + await database + .update(scheduledJobs) + .set({ runAt: past() }) + .where(eq(scheduledJobs.key, 'r')); + } + } + expect((await row('r'))?.status).toBe('failed'); + expect((await row('r'))?.lastError).toBe('discord down'); + expect(retryDelayMs(1)).toBe(30_000); + expect(retryDelayMs(20)).toBe(3_600_000); + }); + + it('does not retry permanent failures or invalid payloads', async () => { + const { db: database, scheduler, ctx } = setup(); + handle.mockRejectedValue(new PermanentError('user blocked DMs')); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'p' }); + await database.insert(scheduledJobs).values({ + type: job.type, + payload: { n: 'x' }, + runAt: past(), + key: 'bad', + }); + await scheduler.tick(ctx); + expect((await row('p'))?.status).toBe('failed'); + expect((await row('bad'))?.status).toBe('failed'); + expect(handle).toHaveBeenCalledOnce(); + }); + + it('reschedules recurring jobs', async () => { + const { scheduler, ctx } = setup(); + const next = new Date(Date.now() + 86_400_000); + handle.mockResolvedValue({ rescheduleAt: next }); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'rec' }); + await scheduler.tick(ctx); + const current = await row('rec'); + expect(current?.status).toBe('pending'); + expect(current?.runAt.getTime()).toBe(next.getTime()); + expect(current?.attempts).toBe(0); + }); + + it('recovers jobs whose lease expired after a crash', async () => { + const { db: database, scheduler, ctx } = setup(); + handle.mockResolvedValue(null); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'crash' }); + // Simulate a worker that claimed the job and died. + await claimDueJobs(database, { + types: [job.type], + limit: 10, + leaseMs: 60_000, + }); + expect(await scheduler.tick(ctx)).toBe(0); + await database + .update(scheduledJobs) + .set({ lockedUntil: sql`now() - interval '1 second'` }) + .where(eq(scheduledJobs.key, 'crash')); + expect(await scheduler.tick(ctx)).toBe(1); + expect((await row('crash'))?.status).toBe('done'); + }); + + it('never hands the same job to concurrent claimers', async () => { + const { db: database, scheduler } = setup(); + for (let n = 0; n < 20; n++) { + await scheduler.schedule(job, { n }, { runAt: past(), key: `k${n}` }); + } + const claims = await Promise.all( + Array.from({ length: 5 }, () => + claimDueJobs(database, { + types: [job.type], + limit: 8, + leaseMs: 60_000, + }), + ), + ); + const ids = claims.flat().map((claimed) => claimed.id); + expect(new Set(ids).size).toBe(ids.length); + expect(ids).toHaveLength(20); + }); + + it('leaves jobs of unregistered types untouched', async () => { + const { db: database, scheduler, ctx } = setup(); + await database.insert(scheduledJobs).values({ + type: 'disabled:feature', + payload: {}, + runAt: past(), + key: 'off', + }); + expect(await scheduler.tick(ctx)).toBe(0); + expect((await row('off'))?.status).toBe('pending'); + }); +}); diff --git a/src/core/scheduler/scheduler.ts b/src/core/scheduler/scheduler.ts new file mode 100644 index 0000000..deda9b3 --- /dev/null +++ b/src/core/scheduler/scheduler.ts @@ -0,0 +1,137 @@ +import { setTimeout as sleep } from 'node:timers/promises'; +import type { Db } from '../../db/client.js'; +import { PermanentError } from '../../shared/errors.js'; +import type { AppContext, Job, Scheduler } from '../feature.js'; +import type { Logger } from '../logger.js'; +import type { JobRow } from './schema.js'; +import { cancelJob, claimDueJobs, finishJob, upsertJob } from './store.js'; + +export type SchedulerOptions = { + pollIntervalMs?: number; + batchSize?: number; + leaseMs?: number; +}; + +export type SchedulerRuntime = Scheduler & { + /** Claims and runs one batch; returns how many jobs were claimed. */ + tick: (ctx: AppContext) => Promise; + start: (ctx: AppContext) => void; + stop: () => Promise; +}; + +const maxBackoffMs = 60 * 60 * 1000; + +export function retryDelayMs(attempt: number): number { + return Math.min(30_000 * 2 ** (attempt - 1), maxBackoffMs); +} + +/** + * One persistent, database-backed scheduler shared by every feature. Delivery + * is at-least-once: a handler may run again if the process dies mid-job, so + * handlers must be idempotent. + */ +export function createScheduler( + db: Db, + jobs: ReadonlyMap>, + log: Logger, + options: SchedulerOptions = {}, +): SchedulerRuntime { + const pollIntervalMs = options.pollIntervalMs ?? 5000; + const batchSize = options.batchSize ?? 10; + const leaseMs = options.leaseMs ?? 5 * 60 * 1000; + const types = [...jobs.keys()]; + const abort = new AbortController(); + let loop: Promise | undefined; + + async function execute(row: JobRow, ctx: AppContext): Promise { + const job = jobs.get(row.type); + const jobLog = log.child({ jobId: row.id, jobType: row.type }); + if (!job) { + return; + } + if (row.attempts > row.maxAttempts) { + await finishJob(db, row.id, { + kind: 'failed', + error: 'Exceeded max attempts', + }); + return; + } + try { + const outcome = await job.run( + row.payload, + { id: row.id, runAt: row.runAt, attempt: row.attempts }, + { ...ctx, log: jobLog }, + ); + await finishJob( + db, + row.id, + outcome + ? { kind: 'reschedule', runAt: outcome.rescheduleAt } + : { kind: 'done' }, + ); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + const permanent = + error instanceof PermanentError || row.attempts >= row.maxAttempts; + jobLog.error( + { err: error, attempt: row.attempts, permanent }, + 'Job failed', + ); + await finishJob( + db, + row.id, + permanent + ? { kind: 'failed', error: message } + : { + kind: 'retry', + error: message, + runAt: new Date(Date.now() + retryDelayMs(row.attempts)), + }, + ); + } + } + + async function tick(ctx: AppContext): Promise { + const rows = await claimDueJobs(db, { types, limit: batchSize, leaseMs }); + await Promise.all(rows.map((row) => execute(row, ctx))); + return rows.length; + } + + async function run(ctx: AppContext): Promise { + while (!abort.signal.aborted) { + let claimed = 0; + try { + claimed = await tick(ctx); + } catch (error) { + log.error({ err: error }, 'Scheduler tick failed'); + } + // A full batch suggests a backlog, so poll again immediately. + if (claimed < batchSize) { + await sleep(pollIntervalMs, undefined, { signal: abort.signal }).catch( + () => false, + ); + } + } + } + + return { + schedule: async (job, payload, scheduleOptions) => { + await upsertJob(db, { + type: job.type, + payload, + runAt: scheduleOptions.runAt, + key: scheduleOptions.key, + maxAttempts: scheduleOptions.maxAttempts ?? job.maxAttempts, + }); + }, + cancel: (key) => cancelJob(db, key), + tick, + start: (ctx) => { + loop ??= run(ctx); + }, + stop: async () => { + abort.abort(); + await loop; + }, + }; +} diff --git a/src/core/scheduler/schema.ts b/src/core/scheduler/schema.ts new file mode 100644 index 0000000..5a446e3 --- /dev/null +++ b/src/core/scheduler/schema.ts @@ -0,0 +1,49 @@ +import { sql } from 'drizzle-orm'; +import { + bigserial, + index, + integer, + jsonb, + pgEnum, + pgTable, + text, + timestamp, +} from 'drizzle-orm/pg-core'; + +export const jobStatus = pgEnum('job_status', [ + 'pending', + 'running', + 'done', + 'failed', + 'cancelled', +]); + +export const scheduledJobs = pgTable( + 'scheduled_jobs', + { + id: bigserial('id', { mode: 'number' }).primaryKey(), + type: text('type').notNull(), + payload: jsonb('payload').$type().notNull(), + runAt: timestamp('run_at', { withTimezone: true }).notNull(), + status: jobStatus('status').notNull().default('pending'), + attempts: integer('attempts').notNull().default(0), + maxAttempts: integer('max_attempts').notNull().default(5), + lockedUntil: timestamp('locked_until', { withTimezone: true }), + lastError: text('last_error'), + key: text('key').unique(), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + finishedAt: timestamp('finished_at', { withTimezone: true }), + }, + (table) => [ + index('scheduled_jobs_due_idx') + .on(table.runAt) + .where(sql`${table.status} = 'pending'`), + index('scheduled_jobs_lease_idx') + .on(table.lockedUntil) + .where(sql`${table.status} = 'running'`), + ], +); + +export type JobRow = typeof scheduledJobs.$inferSelect; diff --git a/src/core/scheduler/store.ts b/src/core/scheduler/store.ts new file mode 100644 index 0000000..94091e4 --- /dev/null +++ b/src/core/scheduler/store.ts @@ -0,0 +1,126 @@ +import { and, asc, eq, inArray, lte, lt, or, sql } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { scheduledJobs, type JobRow } from './schema.js'; + +export type NewJob = { + type: string; + payload: unknown; + runAt: Date; + key?: string | undefined; + maxAttempts?: number | undefined; +}; + +/** Inserts a job, or replaces the job holding the same key. */ +export async function upsertJob(db: Db, job: NewJob): Promise { + const values = { + type: job.type, + payload: job.payload, + runAt: job.runAt, + key: job.key ?? null, + maxAttempts: job.maxAttempts ?? 5, + }; + await db + .insert(scheduledJobs) + .values(values) + .onConflictDoUpdate({ + target: scheduledJobs.key, + set: { + ...values, + status: 'pending', + attempts: 0, + lockedUntil: null, + lastError: null, + finishedAt: null, + }, + }); +} + +export async function cancelJob(db: Db, key: string): Promise { + await db + .update(scheduledJobs) + .set({ status: 'cancelled', finishedAt: new Date(), lockedUntil: null }) + .where( + and( + eq(scheduledJobs.key, key), + inArray(scheduledJobs.status, ['pending', 'running']), + ), + ); +} + +/** + * Claims due jobs, including running jobs whose lease expired because the + * process that claimed them died. SKIP LOCKED lets concurrent workers claim + * disjoint batches. + */ +export async function claimDueJobs( + db: Db, + options: { types: readonly string[]; limit: number; leaseMs: number }, +): Promise { + if (options.types.length === 0) { + return []; + } + const due = db + .select({ id: scheduledJobs.id }) + .from(scheduledJobs) + .where( + and( + inArray(scheduledJobs.type, [...options.types]), + or( + and( + eq(scheduledJobs.status, 'pending'), + lte(scheduledJobs.runAt, sql`now()`), + ), + and( + eq(scheduledJobs.status, 'running'), + lt(scheduledJobs.lockedUntil, sql`now()`), + ), + ), + ), + ) + .orderBy(asc(scheduledJobs.runAt)) + .limit(options.limit) + .for('update', { skipLocked: true }); + + return db + .update(scheduledJobs) + .set({ + status: 'running', + attempts: sql`${scheduledJobs.attempts} + 1`, + lockedUntil: sql`now() + ${options.leaseMs} * interval '1 millisecond'`, + }) + .where(inArray(scheduledJobs.id, due)) + .returning(); +} + +type Finish = + | { kind: 'done' } + | { kind: 'reschedule'; runAt: Date } + | { kind: 'retry'; runAt: Date; error: string } + | { kind: 'failed'; error: string }; + +/** + * Records a job's outcome. Only applies while the job is still running, so a + * concurrent cancel or replacement wins over a finishing handler. + */ +export async function finishJob( + db: Db, + id: number, + finish: Finish, +): Promise { + const now = new Date(); + const changes = { + done: { status: 'done', finishedAt: now }, + reschedule: { status: 'pending', attempts: 0, lastError: null }, + retry: { status: 'pending' }, + failed: { status: 'failed', finishedAt: now }, + } as const; + await db + .update(scheduledJobs) + .set({ + ...changes[finish.kind], + lockedUntil: null, + ...('runAt' in finish && { runAt: finish.runAt }), + ...('error' in finish && { lastError: finish.error.slice(0, 2000) }), + }) + .where(and(eq(scheduledJobs.id, id), eq(scheduledJobs.status, 'running'))); +} diff --git a/src/db/client.ts b/src/db/client.ts new file mode 100644 index 0000000..08a7d1a --- /dev/null +++ b/src/db/client.ts @@ -0,0 +1,28 @@ +import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { migrate } from 'drizzle-orm/postgres-js/migrator'; +import postgres from 'postgres'; +import { ignore } from '../shared/errors.js'; + +export type Db = PostgresJsDatabase; + +/** A database handle or an open transaction; both accept the same queries. */ +export type Tx = Parameters[0]>[0]; + +export type Database = { + db: Db; + close: () => Promise; +}; + +const migrationsFolder = new URL('../../drizzle', import.meta.url).pathname; + +export function connectDatabase(url: string): Database { + const sql = postgres(url, { max: 10, onnotice: ignore }); + return { + db: drizzle(sql), + close: () => sql.end({ timeout: 5 }), + }; +} + +export async function runMigrations(db: Db): Promise { + await migrate(db, { migrationsFolder }); +} diff --git a/tests/db.ts b/tests/db.ts new file mode 100644 index 0000000..28de6c2 --- /dev/null +++ b/tests/db.ts @@ -0,0 +1,30 @@ +import { afterAll } from 'vitest'; +import { connectDatabase, type Db } from '../src/db/client.js'; + +const url = process.env.TEST_DATABASE_URL; + +/** True when database tests cannot run; use with `describe.skipIf`. */ +export const noDatabase = url === undefined; + +let database: ReturnType | undefined; + +export function testDb(): Db { + if (url === undefined) { + throw new Error('TEST_DATABASE_URL is not set'); + } + database ??= connectDatabase(url); + return database.db; +} + +afterAll(async () => { + await database?.close(); + database = undefined; +}); + +let counter = 0; + +/** A unique snowflake-shaped ID so tests never collide on shared tables. */ +export function snowflake(): string { + counter += 1; + return `${Date.now()}${String(counter).padStart(5, '0')}`; +} diff --git a/tests/global-setup.ts b/tests/global-setup.ts new file mode 100644 index 0000000..fe2655b --- /dev/null +++ b/tests/global-setup.ts @@ -0,0 +1,19 @@ +import postgres from 'postgres'; +import { connectDatabase, runMigrations } from '../src/db/client.js'; + +/** Recreates the test database schema from migrations before the run. */ +export default async function setup(): Promise { + const url = process.env.TEST_DATABASE_URL; + if (url === undefined) { + console.warn('TEST_DATABASE_URL is not set; database tests are skipped.'); + return; + } + const sql = postgres(url, { onnotice: () => null }); + await sql`DROP SCHEMA IF EXISTS public CASCADE`; + await sql`DROP SCHEMA IF EXISTS drizzle CASCADE`; + await sql`CREATE SCHEMA public`; + await sql.end(); + const database = connectDatabase(url); + await runMigrations(database.db); + await database.close(); +} From f39c3e07311cda0204bc929b8c4eb8789f78648d Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 004/199] feat(roles): fix reaction roles and add select-menu role panels --- index.js | 111 ---------- src/features/roles/guards.ts | 57 +++++ src/features/roles/index.ts | 365 +++++++++++++++++++++++++++++++ src/features/roles/legacy.ts | 165 ++++++++++++++ src/features/roles/panels.ts | 163 ++++++++++++++ src/features/roles/roles.test.ts | 171 +++++++++++++++ src/features/roles/schema.ts | 51 +++++ src/features/roles/service.ts | 233 ++++++++++++++++++++ 8 files changed, 1205 insertions(+), 111 deletions(-) delete mode 100644 index.js create mode 100644 src/features/roles/guards.ts create mode 100644 src/features/roles/index.ts create mode 100644 src/features/roles/legacy.ts create mode 100644 src/features/roles/panels.ts create mode 100644 src/features/roles/roles.test.ts create mode 100644 src/features/roles/schema.ts create mode 100644 src/features/roles/service.ts diff --git a/index.js b/index.js deleted file mode 100644 index 77b0a25..0000000 --- a/index.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict'; - -require("dotenv").config({ path: "./.env" }); - -const { Client, Events, GatewayIntentBits, EmbedBuilder } = require("discord.js"); - -const client = new Client({ - intents: [ - GatewayIntentBits.Guilds, - GatewayIntentBits.GuildMembers, - GatewayIntentBits.MessageContent, - GatewayIntentBits.GuildMessageReactions - ], -}); - -const roleMap = { - '1️⃣': process.env.TARKVARA_ROLE_ID, - '2️⃣': process.env.HELPDESK_ROLE_ID, - '3️⃣': process.env.KULTUUR_ROLE_ID, - // '4️⃣': process.env.TURUNDUS_ROLE_ID -}; - -client.once(Events.ClientReady, async c => { - console.log(`Logged in as ${c.user.tag}`); - - const roleMessage = "Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur"; - await createMessageWithReactions(roleMessage); -}); - -async function createMessageWithReactions(roleMessage) { - const channel = await client.channels.fetch(process.env.ROLE_SELECTION_CHANNEL_ID); // make sure no one can send messages in this channel - const messages = await channel.messages.fetch({ limit: 5 }); // if more than 5 messages in channel, increase limit, - // if not planning to send any other messages in the channel - // can set limit to 1 - const existingMessage = messages.find(msg => msg.content === roleMessage); - - if (!existingMessage) { - const sentMessage = await channel.send(roleMessage); - - await sentMessage.react('1️⃣'); - await sentMessage.react('2️⃣'); - await sentMessage.react('3️⃣'); // kultuuritiim (turundus + üritused) - // await sentMessage.react('4️⃣'); // was turundus/uritused - - console.log("Message sent."); - } else { - console.log("Message already exists."); - } -} - -async function handleReaction(reaction, user, addRole) { - if (reaction.message.partial){ - await reaction.message.fetch(); - } - if (reaction.partial) { - await reaction.fetch(); - } - if (user.bot) { - return; - } - - const roleId = roleMap[reaction.emoji.name]; - - if (!roleId) { - return; - } - - const member = await reaction.message.guild.members.fetch(user.id); - if (addRole) { - await member.roles.add(roleId); - const role = await reaction.message.guild.roles.fetch(roleId); - console.log(`Assigned role ${role.name} to user ${user.tag}`); - } else { - await member.roles.remove(roleId); - const role = await reaction.message.guild.roles.fetch(roleId); - console.log(`Removed role ${role.name} from user ${user.tag}`); - } -} - -client.on(Events.MessageReactionAdd, async (reaction, user) => { - await handleReaction(reaction, user, true); -}); - -client.on(Events.MessageReactionRemove, async (reaction, user) => { - await handleReaction(reaction, user, false); -}); - -// Welcome message (not needer rn) - -// client.on(Events.GuildMemberAdd, async (member) => { -// try { -// const welcomeChannel = member.guild.channels.cache.get(process.env.WELCOME_CHANNEL_ID); - -// if (!welcomeChannel) { -// return console.error("Welcome channel not found!"); -// } - -// const highlight = `<@${member.user.id}>`; - -// const embed = new EmbedBuilder() -// .setTitle("Welcome to the Server!") -// .setDescription(`Hei <@${member.user.id}>! Valige endale sobiva rolli siin: <#${process.env.ROLE_SELECTION_CHANNEL_ID}>`) -// .setColor("#FFAC1C"); - -// await welcomeChannel.send({ content: highlight, embeds: [embed] }); -// } catch (error) { -// console.error("Error sending welcome message:", error); -// } -// }); - -client.login(process.env.DISCORD_TOKEN); diff --git a/src/features/roles/guards.ts b/src/features/roles/guards.ts new file mode 100644 index 0000000..6198c37 --- /dev/null +++ b/src/features/roles/guards.ts @@ -0,0 +1,57 @@ +import { PermissionFlagsBits, type GuildMember, type Role } from 'discord.js'; +import { UserError } from '../../shared/errors.js'; + +const moderatorPermissions = [ + PermissionFlagsBits.Administrator, + PermissionFlagsBits.ManageGuild, + PermissionFlagsBits.ManageRoles, + PermissionFlagsBits.ManageChannels, + PermissionFlagsBits.ManageMessages, + PermissionFlagsBits.ManageWebhooks, + PermissionFlagsBits.BanMembers, + PermissionFlagsBits.KickMembers, + PermissionFlagsBits.ModerateMembers, + PermissionFlagsBits.MentionEveryone, +]; + +/** Why the bot must not hand this role out, or undefined when it may. */ +export function selfAssignProblem(role: Role): string | undefined { + if (role.id === role.guild.id) { + return 'is the @everyone role'; + } + if (role.managed) { + return 'is managed by an integration'; + } + if (moderatorPermissions.some((flag) => role.permissions.has(flag))) { + return 'grants moderator permissions'; + } + if (!role.editable) { + return 'is above my highest role, or I lack Manage Roles'; + } + return undefined; +} + +export function requireSelfAssignable(role: Role): void { + const problem = selfAssignProblem(role); + if (problem !== undefined) { + throw new UserError(`${role.name} cannot be self-assigned: it ${problem}.`); + } +} + +/** Members may only manage roles strictly below their own highest role. */ +export function requireAbove(actor: GuildMember, role: Role): void { + if (actor.id === actor.guild.ownerId) { + return; + } + if (actor.roles.highest.comparePositionTo(role) <= 0) { + throw new UserError(`${role.name} is not below your highest role.`); + } +} + +export function requireEditable(role: Role): void { + if (role.managed || !role.editable) { + throw new UserError( + `I cannot manage ${role.name}: it is managed or above my highest role.`, + ); + } +} diff --git a/src/features/roles/index.ts b/src/features/roles/index.ts new file mode 100644 index 0000000..f556832 --- /dev/null +++ b/src/features/roles/index.ts @@ -0,0 +1,365 @@ +import { + ChannelType, + Events, + InteractionContextType, + SlashCommandBuilder, + type GuildMember, + type Role, +} from 'discord.js'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, deferred, defineListener } from '../../core/define.js'; +import type { + CommandInteraction, + Feature, + SlashCommand, +} from '../../core/feature.js'; +import { UserError } from '../../shared/errors.js'; +import { + requireAbove, + requireEditable, + requireSelfAssignable, +} from './guards.js'; +import { handleReaction, syncLegacyPanel } from './legacy.js'; +import { panelComponents, publishPanel } from './panels.js'; +import { + addPanelRole, + createPanel, + deletePanel, + listPanels, + listSelfAssignableRoles, + removePanelRole, + requirePanel, + setPanelTitle, +} from './service.js'; + +const data = new SlashCommandBuilder() + .setName('role') + .setDescription('Manage roles and role panels') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Create a role without permissions') + .addStringOption((o) => + o + .setName('name') + .setDescription('Role name') + .setRequired(true) + .setMaxLength(100), + ) + .addStringOption((o) => + o.setName('color').setDescription('Hex color, e.g. #FFAC1C'), + ) + .addBooleanOption((o) => + o.setName('mentionable').setDescription('Allow anyone to mention it'), + ), + ) + .addSubcommand((sub) => + sub + .setName('delete') + .setDescription('Delete a role') + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('assign') + .setDescription('Give a member a role') + .addUserOption((o) => + o.setName('member').setDescription('Member').setRequired(true), + ) + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription('Take a role from a member') + .addUserOption((o) => + o.setName('member').setDescription('Member').setRequired(true), + ) + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ), + ) + .addSubcommand((sub) => + sub.setName('list').setDescription('List self-assignable roles and panels'), + ) + .addSubcommandGroup((group) => + group + .setName('panel') + .setDescription('Role selection panels') + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Post a new role panel') + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Channel') + .setRequired(true) + .addChannelTypes(ChannelType.GuildText), + ) + .addStringOption((o) => + o + .setName('title') + .setDescription('Panel title') + .setRequired(true) + .setMaxLength(200), + ), + ) + .addSubcommand((sub) => + sub + .setName('update') + .setDescription('Add or remove roles, or rename a panel') + .addIntegerOption((o) => + o + .setName('panel') + .setDescription('Panel') + .setRequired(true) + .setAutocomplete(true), + ) + .addRoleOption((o) => o.setName('add').setDescription('Role to add')) + .addStringOption((o) => + o + .setName('label') + .setDescription('Label for the added role') + .setMaxLength(100), + ) + .addRoleOption((o) => + o.setName('remove').setDescription('Role to remove'), + ) + .addStringOption((o) => + o.setName('title').setDescription('New title').setMaxLength(200), + ), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription( + 'Delete a panel and its message (including the legacy reaction panel)', + ) + .addIntegerOption((o) => + o + .setName('panel') + .setDescription('Panel') + .setRequired(true) + .setAutocomplete(true), + ), + ), + ); + +function parseColor(value: string | null): number | undefined { + if (value === null) { + return undefined; + } + const match = /^#?([\da-f]{6})$/i.exec(value); + if (match?.[1] === undefined) { + throw new UserError('Color must be a hex value like #FFAC1C.'); + } + return Number.parseInt(match[1], 16); +} + +async function memberAndRole( + interaction: CommandInteraction, +): Promise<{ role: Role; member: GuildMember }> { + const role = interaction.options.getRole('role', true); + const user = interaction.options.getUser('member', true); + requireAbove(interaction.member, role); + requireEditable(role); + if ( + role.permissions.has('Administrator') && + !interaction.member.permissions.has('Administrator') + ) { + throw new UserError( + 'Only administrators can hand out administrator roles.', + ); + } + return { role, member: await interaction.guild.members.fetch(user.id) }; +} + +const command = { + data: data.toJSON(), + permissions: { + create: 'role:create', + delete: 'role:manage', + assign: 'role:assign', + remove: 'role:assign', + 'panel create': 'role:manage', + 'panel update': 'role:manage', + 'panel remove': 'role:manage', + }, + execute: bySubcommand({ + create: deferred(async (interaction) => { + const role = await interaction.guild.roles.create({ + name: interaction.options.getString('name', true), + permissions: [], + mentionable: interaction.options.getBoolean('mentionable') ?? false, + reason: `Requested by ${interaction.user.tag}`, + ...(() => { + const color = parseColor(interaction.options.getString('color')); + return color === undefined ? {} : { colors: { primaryColor: color } }; + })(), + }); + await respond(interaction, `Created ${role.toString()}.`); + }), + delete: deferred(async (interaction) => { + const role = interaction.options.getRole('role', true); + requireAbove(interaction.member, role); + requireEditable(role); + await role.delete(`Requested by ${interaction.user.tag}`); + await respond(interaction, `Deleted ${role.name}.`); + }), + assign: deferred(async (interaction) => { + const { role, member } = await memberAndRole(interaction); + await member.roles.add(role, `Assigned by ${interaction.user.tag}`); + await respond( + interaction, + `Gave ${role.toString()} to ${member.toString()}.`, + ); + }), + remove: deferred(async (interaction) => { + const { role, member } = await memberAndRole(interaction); + await member.roles.remove(role, `Removed by ${interaction.user.tag}`); + await respond( + interaction, + `Removed ${role.toString()} from ${member.toString()}.`, + ); + }), + list: async (interaction, ctx) => { + const [roles, panels] = await Promise.all([ + listSelfAssignableRoles(ctx.db, interaction.guildId), + listPanels(ctx.db, interaction.guildId), + ]); + const lines = [ + '**Self-assignable roles**', + ...(roles.length === 0 + ? ['None yet.'] + : roles.map((r) => `• <@&${r.roleId}>`)), + '', + '**Panels**', + ...(panels.length === 0 + ? ['None yet.'] + : panels.map( + (p) => `• #${p.id} ${p.title} (${p.kind}) in <#${p.channelId}>`, + )), + ]; + await respond(interaction, lines.join('\n')); + }, + 'panel create': deferred(async (interaction, ctx) => { + const channel = interaction.options.getChannel('channel', true, [ + ChannelType.GuildText, + ]); + const id = await createPanel(ctx.db, { + guildId: interaction.guildId, + channelId: channel.id, + kind: 'select', + title: interaction.options.getString('title', true), + createdBy: interaction.user.id, + }); + await publishPanel( + ctx, + await requirePanel(ctx.db, interaction.guildId, id), + ); + await respond( + interaction, + `Created panel #${id}. Add roles with \`/role panel update panel:${id} add:\`.`, + ); + }), + 'panel update': deferred(async (interaction, ctx) => { + const panel = await requirePanel( + ctx.db, + interaction.guildId, + interaction.options.getInteger('panel', true), + ); + if (panel.kind === 'reaction') { + throw new UserError( + 'The legacy reaction panel is configured through environment variables.', + ); + } + const add = interaction.options.getRole('add'); + const remove = interaction.options.getRole('remove'); + const title = interaction.options.getString('title'); + if (add) { + requireSelfAssignable(add); + requireAbove(interaction.member, add); + const label = interaction.options.getString('label') ?? add.name; + await addPanelRole(ctx.db, panel.id, { + roleId: add.id, + label, + emoji: null, + }); + } + if (remove && !(await removePanelRole(ctx.db, panel.id, remove.id))) { + throw new UserError(`${remove.name} is not on this panel.`); + } + if (title !== null) { + await setPanelTitle(ctx.db, panel.id, title); + } + await publishPanel( + ctx, + await requirePanel(ctx.db, interaction.guildId, panel.id), + ); + await respond(interaction, `Panel #${panel.id} updated.`); + }), + 'panel remove': deferred(async (interaction, ctx) => { + const panel = await requirePanel( + ctx.db, + interaction.guildId, + interaction.options.getInteger('panel', true), + ); + if (panel.messageId !== null) { + const channel = await ctx.client.channels + .fetch(panel.channelId) + .catch(() => null); + if (channel?.isTextBased() === true) { + await channel.messages.delete(panel.messageId).catch(() => null); + } + } + await deletePanel(ctx.db, panel.id); + const note = + panel.kind === 'reaction' + ? ' Unset ROLE_SELECTION_CHANNEL_ID, or it will be posted again on the next start.' + : ''; + await respond(interaction, `Removed panel #${panel.id}.${note}`); + }), + }), + autocomplete: async (interaction, ctx) => { + const query = interaction.options.getFocused().toLowerCase(); + const panels = await listPanels(ctx.db, interaction.guildId); + await interaction.respond( + panels + .filter( + (p) => + p.title.toLowerCase().includes(query) || String(p.id) === query, + ) + .slice(0, 25) + .map((p) => ({ + name: `#${p.id} ${p.title}`.slice(0, 100), + value: p.id, + })), + ); + }, +} satisfies SlashCommand; + +export const rolesFeature: Feature = { + name: 'roles', + permissions: [ + { id: 'role:create', description: 'Create roles' }, + { id: 'role:manage', description: 'Delete roles and manage role panels' }, + { id: 'role:assign', description: 'Assign roles to other members' }, + ], + commands: [command], + components: panelComponents, + events: [ + defineListener(Events.MessageReactionAdd, (ctx, reaction, user) => + handleReaction(ctx, reaction, user, true), + ), + defineListener(Events.MessageReactionRemove, (ctx, reaction, user) => + handleReaction(ctx, reaction, user, false), + ), + ], + start: syncLegacyPanel, +}; diff --git a/src/features/roles/legacy.ts b/src/features/roles/legacy.ts new file mode 100644 index 0000000..942468e --- /dev/null +++ b/src/features/roles/legacy.ts @@ -0,0 +1,165 @@ +import { + ChannelType, + type Message, + type MessageReaction, + type PartialMessageReaction, + type PartialUser, + type TextChannel, + type User, +} from 'discord.js'; +import type { AppContext } from '../../core/feature.js'; +import { + createPanel, + findReactionPanel, + findReactionRole, + replacePanelRoles, + setPanelMessage, +} from './service.js'; +import { selfAssignProblem } from './guards.js'; + +// Kept verbatim so the message posted by the previous bot is recognised. +export const legacyMessage = + 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur'; + +export function legacyRoles(ctx: Pick) { + const { config } = ctx; + return [ + { emoji: '1️⃣', roleId: config.TARKVARA_ROLE_ID, label: 'Tarkvara' }, + { emoji: '2️⃣', roleId: config.HELPDESK_ROLE_ID, label: 'Helpdesk' }, + { emoji: '3️⃣', roleId: config.KULTUUR_ROLE_ID, label: 'Kultuur' }, + ].flatMap(({ roleId, ...rest }) => + roleId === undefined ? [] : [{ roleId, ...rest }], + ); +} + +async function findOrPostMessage( + ctx: AppContext, + channel: TextChannel, + storedId: string | null, + post: () => Promise, +): Promise { + if (storedId !== null) { + try { + return await channel.messages.fetch(storedId); + } catch (error) { + ctx.log.warn( + { err: error, messageId: storedId }, + 'Stored role panel message is gone', + ); + } + } + const recent = await channel.messages.fetch({ limit: 50 }); + const existing = recent.find( + (message) => + message.author.id === ctx.client.user.id && + message.content === legacyMessage, + ); + return existing ?? post(); +} + +/** + * Ensures the env-configured reaction panel exists exactly once. Its message + * ID is persisted, so later restarts never search the channel or repost. + */ +export async function syncLegacyPanel(ctx: AppContext): Promise { + const channelId = ctx.config.ROLE_SELECTION_CHANNEL_ID; + if (channelId === undefined) { + return; + } + const channel = await ctx.client.channels.fetch(channelId); + if (channel?.type !== ChannelType.GuildText) { + ctx.log.error( + { channelId }, + 'ROLE_SELECTION_CHANNEL_ID is not a server text channel', + ); + return; + } + const roles = legacyRoles(ctx); + for (const { roleId, label } of roles) { + const role = await channel.guild.roles.fetch(roleId); + const problem = role ? selfAssignProblem(role) : 'does not exist'; + if (problem !== undefined) { + ctx.log.error( + { roleId, label, problem }, + 'Legacy panel role is not assignable', + ); + } + } + + const panel = (await findReactionPanel( + ctx.db, + channel.guildId, + channelId, + )) ?? { + id: await createPanel(ctx.db, { + guildId: channel.guildId, + channelId, + kind: 'reaction', + title: 'Role selection', + createdBy: ctx.client.user.id, + }), + messageId: null, + }; + await replacePanelRoles(ctx.db, panel.id, roles); + + const message = await findOrPostMessage( + ctx, + channel, + panel.messageId, + async () => { + ctx.log.info({ channelId }, 'Posting role selection message'); + return channel.send(legacyMessage); + }, + ); + if (message.id !== panel.messageId) { + await setPanelMessage(ctx.db, panel.id, message.id); + } + for (const { emoji } of roles) { + if (message.reactions.cache.get(emoji)?.me !== true) { + await message.react(emoji); + } + } +} + +export async function handleReaction( + ctx: AppContext, + reaction: MessageReaction | PartialMessageReaction, + user: User | PartialUser, + add: boolean, +): Promise { + const { message } = reaction; + const emoji = reaction.emoji.name; + if (user.bot || message.guildId === null || emoji === null) { + return; + } + // One indexed lookup filters out reactions on every other message. + const roleId = await findReactionRole(ctx.db, { + guildId: message.guildId, + channelId: message.channelId, + messageId: message.id, + emoji, + }); + if (roleId === undefined) { + return; + } + const guild = await ctx.client.guilds.fetch(message.guildId); + const role = await guild.roles.fetch(roleId); + const problem = role ? selfAssignProblem(role) : 'does not exist'; + if (!role || problem !== undefined) { + ctx.log.warn({ roleId, problem }, 'Skipping reaction role change'); + return; + } + const member = await guild.members.fetch(user.id); + if (member.user.bot) { + return; + } + if (add) { + await member.roles.add(role, 'Role selection reaction'); + } else { + await member.roles.remove(role, 'Role selection reaction removed'); + } + ctx.log.info( + { guildId: guild.id, userId: user.id, role: role.name, add }, + add ? 'Assigned role' : 'Removed role', + ); +} diff --git a/src/features/roles/panels.ts b/src/features/roles/panels.ts new file mode 100644 index 0000000..c4a57fc --- /dev/null +++ b/src/features/roles/panels.ts @@ -0,0 +1,163 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ChannelType, + EmbedBuilder, + MessageFlags, + StringSelectMenuBuilder, + type BaseMessageOptions, +} from 'discord.js'; +import { customId } from '../../core/registry.js'; +import type { AppContext, ComponentHandler } from '../../core/feature.js'; +import { UserError } from '../../shared/errors.js'; +import { selfAssignProblem } from './guards.js'; +import { requirePanel, setPanelMessage, type Panel } from './service.js'; + +export function renderPanel(panel: Panel): BaseMessageOptions { + const embed = new EmbedBuilder() + .setTitle(panel.title) + .setDescription( + panel.roles.length === 0 + ? 'No roles yet.' + : panel.roles.map((role) => `• <@&${role.roleId}>`).join('\n'), + ); + const open = new ButtonBuilder() + .setCustomId(customId('roles:open', panel.id)) + .setLabel('Choose roles') + .setStyle(ButtonStyle.Primary); + return { + embeds: [embed], + components: + panel.roles.length === 0 + ? [] + : [new ActionRowBuilder().addComponents(open)], + }; +} + +/** Re-renders a panel message, reposting it if it was deleted. */ +export async function publishPanel( + ctx: AppContext, + panel: Panel, +): Promise { + const channel = await ctx.client.channels + .fetch(panel.channelId) + .catch(() => null); + if (channel?.type !== ChannelType.GuildText) { + throw new UserError(`I can no longer access <#${panel.channelId}>.`); + } + const content = renderPanel(panel); + if (panel.messageId !== null) { + const existing = await channel.messages + .fetch(panel.messageId) + .catch(() => null); + if (existing) { + await existing.edit(content); + return; + } + } + const message = await channel.send(content); + await setPanelMessage(ctx.db, panel.id, message.id); +} + +function parsePanelId(args: readonly string[]): number { + const id = Number(args[0]); + if (!Number.isSafeInteger(id)) { + throw new UserError('This role panel is invalid.'); + } + return id; +} + +const openHandler: ComponentHandler = { + prefix: 'roles:open', + execute: async (interaction, args, ctx) => { + const panel = await requirePanel( + ctx.db, + interaction.guildId, + parsePanelId(args), + ); + if (panel.roles.length === 0) { + throw new UserError('This panel has no roles yet.'); + } + const select = new StringSelectMenuBuilder() + .setCustomId(customId('roles:choose', panel.id)) + .setPlaceholder('Select your roles') + .setMinValues(0) + .setMaxValues(panel.roles.length) + .addOptions( + panel.roles.map((role) => ({ + label: role.label, + value: role.roleId, + default: interaction.member.roles.cache.has(role.roleId), + })), + ); + await interaction.reply({ + content: + 'Pick the roles you want. Unselected roles from this panel are removed.', + components: [ + new ActionRowBuilder().addComponents(select), + ], + flags: MessageFlags.Ephemeral, + }); + }, +}; + +const chooseHandler: ComponentHandler = { + prefix: 'roles:choose', + execute: async (interaction, args, ctx) => { + if (!interaction.isStringSelectMenu()) { + return; + } + await interaction.deferUpdate(); + const panel = await requirePanel( + ctx.db, + interaction.guildId, + parsePanelId(args), + ); + const wanted = new Set(interaction.values); + const toAdd: string[] = []; + const toRemove: string[] = []; + const skipped: string[] = []; + + // Re-validated against the panel's current roles; submitted values are untrusted. + for (const { roleId, label } of panel.roles) { + const role = interaction.guild.roles.cache.get(roleId); + if (!role || selfAssignProblem(role) !== undefined) { + skipped.push(label); + continue; + } + const has = interaction.member.roles.cache.has(roleId); + if (wanted.has(roleId) && !has) { + toAdd.push(roleId); + } else if (!wanted.has(roleId) && has) { + toRemove.push(roleId); + } + } + if (toAdd.length > 0) { + await interaction.member.roles.add(toAdd, 'Role panel selection'); + } + if (toRemove.length > 0) { + await interaction.member.roles.remove(toRemove, 'Role panel selection'); + } + ctx.log.info( + { + guildId: interaction.guildId, + userId: interaction.user.id, + toAdd, + toRemove, + }, + 'Updated roles from panel', + ); + const lines = [ + toAdd.length + toRemove.length === 0 + ? 'No changes.' + : 'Your roles are updated.', + ...(skipped.length > 0 + ? [`Unavailable right now: ${skipped.join(', ')}`] + : []), + ]; + await interaction.editReply({ content: lines.join('\n'), components: [] }); + }, +}; + +export const panelComponents = [openHandler, chooseHandler]; diff --git a/src/features/roles/roles.test.ts b/src/features/roles/roles.test.ts new file mode 100644 index 0000000..985801a --- /dev/null +++ b/src/features/roles/roles.test.ts @@ -0,0 +1,171 @@ +import { + PermissionFlagsBits, + PermissionsBitField, + type Role, +} from 'discord.js'; +import { pino } from 'pino'; +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { requireAbove, selfAssignProblem } from './guards.js'; +import { handleReaction, legacyMessage, legacyRoles } from './legacy.js'; +import { + addPanelRole, + createPanel, + replacePanelRoles, + setPanelMessage, +} from './service.js'; + +function role( + overrides: Partial<{ + id: string; + managed: boolean; + editable: boolean; + permissions: bigint[]; + }> = {}, +) { + return { + id: overrides.id ?? 'r1', + name: 'Role', + guild: { id: 'guild' }, + managed: overrides.managed ?? false, + editable: overrides.editable ?? true, + permissions: new PermissionsBitField(overrides.permissions ?? []), + } as unknown as Role; +} + +describe('legacy role mapping', () => { + it('keeps the original message and emoji mapping', () => { + expect(legacyMessage).toBe( + 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur', + ); + const config = { + TARKVARA_ROLE_ID: 't', + HELPDESK_ROLE_ID: 'h', + KULTUUR_ROLE_ID: 'k', + }; + expect(legacyRoles({ config } as never)).toEqual([ + { emoji: '1️⃣', roleId: 't', label: 'Tarkvara' }, + { emoji: '2️⃣', roleId: 'h', label: 'Helpdesk' }, + { emoji: '3️⃣', roleId: 'k', label: 'Kultuur' }, + ]); + }); + + it('skips roles that are not configured', () => { + expect( + legacyRoles({ config: { HELPDESK_ROLE_ID: 'h' } } as never).map( + (r) => r.label, + ), + ).toEqual(['Helpdesk']); + }); +}); + +describe('role guards', () => { + it('accepts ordinary editable roles', () => { + expect(selfAssignProblem(role())).toBeUndefined(); + }); + + it.each([ + ['everyone', role({ id: 'guild' })], + ['managed', role({ managed: true })], + ['moderator', role({ permissions: [PermissionFlagsBits.BanMembers] })], + ['above the bot', role({ editable: false })], + ])('rejects %s roles', (_name, candidate) => { + expect(selfAssignProblem(candidate)).toBeDefined(); + }); + + it('only lets members manage roles below their highest role', () => { + const actor = (position: number) => + ({ + id: 'a', + guild: { ownerId: 'owner' }, + roles: { highest: { comparePositionTo: () => position } }, + }) as never; + expect(() => requireAbove(actor(1), role())).not.toThrow(); + expect(() => requireAbove(actor(0), role())).toThrow( + 'not below your highest role', + ); + }); +}); + +describe.skipIf(noDatabase)('reaction role handling', () => { + const guildId = snowflake(); + const channelId = snowflake(); + const messageId = snowflake(); + const roleId = snowflake(); + const add = vi.fn(async () => undefined); + const remove = vi.fn(async () => undefined); + const assignable = role({ id: roleId }); + const guild = { + id: guildId, + roles: { + fetch: vi.fn(async (id: string) => (id === roleId ? assignable : null)), + }, + members: { + fetch: vi.fn(async () => ({ + user: { bot: false }, + roles: { add, remove }, + })), + }, + }; + const ctx = { + db: noDatabase ? undefined : testDb(), + log: pino({ level: 'silent' }), + client: { guilds: { fetch: async () => guild } }, + } as unknown as AppContext; + const reaction = (emoji: string, message = messageId) => + ({ + emoji: { name: emoji }, + message: { id: message, guildId, channelId }, + }) as never; + const user = (bot = false) => ({ id: 'u', bot }) as never; + + beforeAll(async () => { + const panelId = await createPanel(ctx.db, { + guildId, + channelId, + kind: 'reaction', + title: 'Legacy', + createdBy: 'bot', + }); + await setPanelMessage(ctx.db, panelId, messageId); + await replacePanelRoles(ctx.db, panelId, [ + { roleId, label: 'Tarkvara', emoji: '1️⃣' }, + ]); + }); + + it('assigns and removes the mapped role', async () => { + await handleReaction(ctx, reaction('1️⃣'), user(), true); + expect(add).toHaveBeenCalledWith(assignable, expect.any(String)); + await handleReaction(ctx, reaction('1️⃣'), user(), false); + expect(remove).toHaveBeenCalledWith(assignable, expect.any(String)); + }); + + it('ignores reactions on unrelated messages, other emoji and bots', async () => { + add.mockClear(); + guild.members.fetch.mockClear(); + await handleReaction(ctx, reaction('1️⃣', snowflake()), user(), true); + await handleReaction(ctx, reaction('🎉'), user(), true); + await handleReaction(ctx, reaction('1️⃣'), user(true), true); + expect(add).not.toHaveBeenCalled(); + expect(guild.members.fetch).not.toHaveBeenCalled(); + }); + + it('skips roles that no longer exist', async () => { + const panelId = await createPanel(ctx.db, { + guildId, + channelId: snowflake(), + kind: 'select', + title: 'x', + createdBy: 'u', + }); + await addPanelRole(ctx.db, panelId, { + roleId: 'gone', + label: 'Gone', + emoji: '4️⃣', + }); + add.mockClear(); + await handleReaction(ctx, reaction('4️⃣'), user(), true); + expect(add).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/roles/schema.ts b/src/features/roles/schema.ts new file mode 100644 index 0000000..ad416af --- /dev/null +++ b/src/features/roles/schema.ts @@ -0,0 +1,51 @@ +import { + index, + integer, + pgEnum, + pgTable, + primaryKey, + serial, + text, + timestamp, + uniqueIndex, +} from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; + +export const rolePanelKind = pgEnum('role_panel_kind', ['reaction', 'select']); + +export const rolePanels = pgTable( + 'role_panels', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + channelId: text('channel_id').notNull(), + messageId: text('message_id').unique(), + kind: rolePanelKind('kind').notNull(), + title: text('title').notNull(), + createdBy: text('created_by').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + index('role_panels_guild_idx').on(table.guildId), + // The env-configured legacy panel exists at most once per channel. + uniqueIndex('role_panels_reaction_channel_idx') + .on(table.guildId, table.channelId) + .where(sql`${table.kind} = 'reaction'`), + ], +); + +export const rolePanelRoles = pgTable( + 'role_panel_roles', + { + panelId: integer('panel_id') + .notNull() + .references(() => rolePanels.id, { onDelete: 'cascade' }), + roleId: text('role_id').notNull(), + label: text('label').notNull(), + emoji: text('emoji'), + position: integer('position').notNull(), + }, + (table) => [primaryKey({ columns: [table.panelId, table.roleId] })], +); diff --git a/src/features/roles/service.ts b/src/features/roles/service.ts new file mode 100644 index 0000000..f9bc3cc --- /dev/null +++ b/src/features/roles/service.ts @@ -0,0 +1,233 @@ +import { and, asc, count, eq, max } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import { rolePanelRoles, rolePanels } from './schema.js'; + +export const maxPanelRoles = 25; + +export type PanelRole = { + roleId: string; + label: string; + emoji: string | null; +}; + +export type Panel = typeof rolePanels.$inferSelect & { roles: PanelRole[] }; + +/** The role bound to a reaction on a reaction panel, if that is what it is. */ +export async function findReactionRole( + db: Db, + reaction: { + guildId: string; + channelId: string; + messageId: string; + emoji: string; + }, +): Promise { + const [row] = await db + .select({ roleId: rolePanelRoles.roleId }) + .from(rolePanels) + .innerJoin(rolePanelRoles, eq(rolePanelRoles.panelId, rolePanels.id)) + .where( + and( + eq(rolePanels.messageId, reaction.messageId), + eq(rolePanels.guildId, reaction.guildId), + eq(rolePanels.channelId, reaction.channelId), + eq(rolePanels.kind, 'reaction'), + eq(rolePanelRoles.emoji, reaction.emoji), + ), + ) + .limit(1); + return row?.roleId; +} + +export async function getPanel( + db: Db, + guildId: string, + panelId: number, +): Promise { + const [panel] = await db + .select() + .from(rolePanels) + .where(and(eq(rolePanels.id, panelId), eq(rolePanels.guildId, guildId))); + if (!panel) { + return undefined; + } + const roles = await db + .select({ + roleId: rolePanelRoles.roleId, + label: rolePanelRoles.label, + emoji: rolePanelRoles.emoji, + }) + .from(rolePanelRoles) + .where(eq(rolePanelRoles.panelId, panelId)) + .orderBy(asc(rolePanelRoles.position)); + return { ...panel, roles }; +} + +export async function requirePanel( + db: Db, + guildId: string, + panelId: number, +): Promise { + const panel = await getPanel(db, guildId, panelId); + if (!panel) { + throw new UserError(`Role panel #${panelId} does not exist.`); + } + return panel; +} + +export async function listPanels(db: Db, guildId: string) { + return db + .select({ + id: rolePanels.id, + title: rolePanels.title, + kind: rolePanels.kind, + channelId: rolePanels.channelId, + }) + .from(rolePanels) + .where(eq(rolePanels.guildId, guildId)) + .orderBy(asc(rolePanels.id)) + .limit(100); +} + +/** Every role members can give themselves through a panel in this guild. */ +export async function listSelfAssignableRoles( + db: Db, + guildId: string, +): Promise> { + return db + .selectDistinctOn([rolePanelRoles.roleId], { + roleId: rolePanelRoles.roleId, + panelId: rolePanelRoles.panelId, + }) + .from(rolePanelRoles) + .innerJoin(rolePanels, eq(rolePanels.id, rolePanelRoles.panelId)) + .where(eq(rolePanels.guildId, guildId)) + .orderBy(rolePanelRoles.roleId) + .limit(500); +} + +export async function createPanel( + db: Db, + input: { + guildId: string; + channelId: string; + kind: 'reaction' | 'select'; + title: string; + createdBy: string; + }, +): Promise { + const [row] = await db + .insert(rolePanels) + .values(input) + .returning({ id: rolePanels.id }); + if (!row) { + throw new Error('Insert returned no row'); + } + return row.id; +} + +export async function findReactionPanel( + db: Db, + guildId: string, + channelId: string, +) { + const [panel] = await db + .select() + .from(rolePanels) + .where( + and( + eq(rolePanels.guildId, guildId), + eq(rolePanels.channelId, channelId), + eq(rolePanels.kind, 'reaction'), + ), + ); + return panel; +} + +export async function setPanelMessage( + db: Db, + panelId: number, + messageId: string | null, +): Promise { + await db + .update(rolePanels) + .set({ messageId }) + .where(eq(rolePanels.id, panelId)); +} + +export async function setPanelTitle( + db: Db, + panelId: number, + title: string, +): Promise { + await db.update(rolePanels).set({ title }).where(eq(rolePanels.id, panelId)); +} + +export async function replacePanelRoles( + db: Db, + panelId: number, + roles: readonly PanelRole[], +): Promise { + await db.transaction(async (tx) => { + await tx.delete(rolePanelRoles).where(eq(rolePanelRoles.panelId, panelId)); + if (roles.length > 0) { + await tx + .insert(rolePanelRoles) + .values( + roles.map((role, position) => ({ ...role, panelId, position })), + ); + } + }); +} + +export async function addPanelRole( + db: Db, + panelId: number, + role: PanelRole, +): Promise { + await db.transaction(async (tx) => { + // Lock the panel so concurrent additions cannot exceed the limit. + await tx + .select({ id: rolePanels.id }) + .from(rolePanels) + .where(eq(rolePanels.id, panelId)) + .for('update'); + const [stats] = await tx + .select({ total: count(), last: max(rolePanelRoles.position) }) + .from(rolePanelRoles) + .where(eq(rolePanelRoles.panelId, panelId)); + if ((stats?.total ?? 0) >= maxPanelRoles) { + throw new UserError(`A panel can hold at most ${maxPanelRoles} roles.`); + } + const inserted = await tx + .insert(rolePanelRoles) + .values({ ...role, panelId, position: (stats?.last ?? -1) + 1 }) + .onConflictDoNothing() + .returning({ roleId: rolePanelRoles.roleId }); + if (inserted.length === 0) { + throw new UserError('That role is already on this panel.'); + } + }); +} + +export async function removePanelRole( + db: Db, + panelId: number, + roleId: string, +): Promise { + const rows = await db + .delete(rolePanelRoles) + .where( + and( + eq(rolePanelRoles.panelId, panelId), + eq(rolePanelRoles.roleId, roleId), + ), + ) + .returning({ roleId: rolePanelRoles.roleId }); + return rows.length > 0; +} + +export async function deletePanel(db: Db, panelId: number): Promise { + await db.delete(rolePanels).where(eq(rolePanels.id, panelId)); +} From 8590251637844fc567ae714512333d6312d18879 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 005/199] feat: permission and settings commands --- src/features/permissions/index.ts | 194 +++++++++++++++++++ src/features/permissions/permissions.test.ts | 55 ++++++ src/features/settings/index.ts | 59 ++++++ 3 files changed, 308 insertions(+) create mode 100644 src/features/permissions/index.ts create mode 100644 src/features/permissions/permissions.test.ts create mode 100644 src/features/settings/index.ts diff --git a/src/features/permissions/index.ts b/src/features/permissions/index.ts new file mode 100644 index 0000000..ebeee08 --- /dev/null +++ b/src/features/permissions/index.ts @@ -0,0 +1,194 @@ +import { + InteractionContextType, + SlashCommandBuilder, + type GuildMember, + type Role, + type SlashCommandStringOption, +} from 'discord.js'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, deferred } from '../../core/define.js'; +import type { + AppContext, + CommandInteraction, + Feature, + Permission, + PermissionDefinition, +} from '../../core/feature.js'; +import { isAdministrator } from '../../core/permissions/authorizer.js'; +import { grant, listGrants, revoke } from '../../core/permissions/store.js'; +import { UserError } from '../../shared/errors.js'; + +const managePermission: Permission = 'permissions:manage'; + +const permissionOption = (o: SlashCommandStringOption) => + o + .setName('permission') + .setDescription('Permission') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('permissions') + .setDescription('Manage which roles may use restricted bot actions') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('grant') + .setDescription('Grant a permission to a role') + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ) + .addStringOption(permissionOption), + ) + .addSubcommand((sub) => + sub + .setName('revoke') + .setDescription('Revoke a permission from a role') + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ) + .addStringOption(permissionOption), + ) + .addSubcommand((sub) => + sub + .setName('list') + .setDescription('List granted permissions') + .addRoleOption((o) => o.setName('role').setDescription('Only this role')), + ) + .addSubcommand((sub) => + sub + .setName('check') + .setDescription('Check whether a member holds a permission') + .addUserOption((o) => + o.setName('member').setDescription('Member').setRequired(true), + ) + .addStringOption(permissionOption), + ); + +/** + * Stops members with `permissions:manage` from escalating: they may only hand + * out permissions they hold themselves, only to roles below their own, and + * never `permissions:manage` itself. Discord administrators are exempt. + */ +export async function checkDelegation( + ctx: Pick, + actor: GuildMember, + role: Role, + permission: Permission, +): Promise { + if (isAdministrator(actor)) { + return; + } + if (permission === managePermission) { + throw new UserError( + 'Only administrators can delegate permission management.', + ); + } + if (actor.roles.highest.comparePositionTo(role) <= 0) { + throw new UserError(`${role.name} is not below your highest role.`); + } + if (!(await ctx.authz.can(actor, permission))) { + throw new UserError('You can only grant permissions you hold yourself.'); + } +} + +export function createPermissionsFeature( + known: () => ReadonlyMap, +): Feature { + const readPermission = (interaction: CommandInteraction): Permission => { + const value = interaction.options.getString('permission', true); + const definition = [...known().values()].find((p) => p.id === value); + if (!definition) { + throw new UserError(`Unknown permission \`${value}\`.`); + } + return definition.id; + }; + + const change = + (action: 'grant' | 'revoke') => + async (interaction: CommandInteraction, ctx: AppContext) => { + const role = interaction.options.getRole('role', true); + const permission = readPermission(interaction); + await checkDelegation(ctx, interaction.member, role, permission); + const input = { + guildId: interaction.guildId, + roleId: role.id, + permission, + }; + const changed = + action === 'grant' + ? await grant(ctx.db, { ...input, grantedBy: interaction.user.id }) + : await revoke(ctx.db, input); + ctx.log.info( + { ...input, actorId: interaction.user.id, action, changed }, + 'Permission change', + ); + const verb = action === 'grant' ? 'Granted' : 'Revoked'; + await respond( + interaction, + changed + ? `${verb} \`${permission}\` for ${role.toString()}.` + : 'Nothing changed.', + ); + }; + + return { + name: 'permissions', + permissions: [ + { id: managePermission, description: 'Grant and revoke bot permissions' }, + ], + commands: [ + { + data: data.toJSON(), + permissions: { '*': managePermission }, + execute: bySubcommand({ + grant: change('grant'), + revoke: change('revoke'), + list: async (interaction, ctx) => { + const role = interaction.options.getRole('role'); + const grants = await listGrants( + ctx.db, + interaction.guildId, + role?.id, + ); + const lines = grants.map( + (g) => `<@&${g.roleId}> — \`${g.permission}\``, + ); + await respond( + interaction, + lines.length === 0 + ? 'No permissions granted. Administrators hold every permission.' + : lines.join('\n').slice(0, 2000), + ); + }, + check: deferred(async (interaction, ctx) => { + const user = interaction.options.getUser('member', true); + const member = await interaction.guild.members.fetch(user.id); + const permission = readPermission(interaction); + const allowed = await ctx.authz.can(member, permission); + await respond( + interaction, + `${member.toString()} ${allowed ? 'holds' : 'does not hold'} \`${permission}\`.`, + ); + }), + }), + autocomplete: async (interaction) => { + const query = interaction.options.getFocused().toLowerCase(); + await interaction.respond( + [...known().values()] + .filter( + (p) => + p.id.includes(query) || + p.description.toLowerCase().includes(query), + ) + .slice(0, 25) + .map((p) => ({ + name: `${p.id} — ${p.description}`.slice(0, 100), + value: p.id, + })), + ); + }, + }, + ], + }; +} diff --git a/src/features/permissions/permissions.test.ts b/src/features/permissions/permissions.test.ts new file mode 100644 index 0000000..7ffa408 --- /dev/null +++ b/src/features/permissions/permissions.test.ts @@ -0,0 +1,55 @@ +import type { GuildMember, Role } from 'discord.js'; +import { describe, expect, it } from 'vitest'; +import type { Authorizer } from '../../core/feature.js'; +import { checkDelegation } from './index.js'; + +const role = {} as Role; +const actor = (options: { admin?: boolean; above?: boolean }) => + ({ + permissions: { has: () => options.admin ?? false }, + roles: { + highest: { comparePositionTo: () => (options.above === false ? 0 : 1) }, + }, + }) as unknown as GuildMember; +const authz = (holds: boolean) => ({ + authz: { + can: async () => holds, + require: async () => undefined, + } as Authorizer, +}); + +describe('permission delegation', () => { + it('lets administrators grant anything', async () => { + await expect( + checkDelegation( + authz(false), + actor({ admin: true }), + role, + 'permissions:manage', + ), + ).resolves.toBeUndefined(); + }); + + it('never lets managers hand out permission management', async () => { + await expect( + checkDelegation(authz(true), actor({}), role, 'permissions:manage'), + ).rejects.toThrow('Only administrators'); + }); + + it('only allows permissions the manager holds, for roles below them', async () => { + await expect( + checkDelegation(authz(true), actor({}), role, 'event:create'), + ).resolves.toBeUndefined(); + await expect( + checkDelegation(authz(false), actor({}), role, 'event:create'), + ).rejects.toThrow('hold yourself'); + await expect( + checkDelegation( + authz(true), + actor({ above: false }), + role, + 'event:create', + ), + ).rejects.toThrow('below'); + }); +}); diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts new file mode 100644 index 0000000..66015e5 --- /dev/null +++ b/src/features/settings/index.ts @@ -0,0 +1,59 @@ +import { + InteractionContextType, + MessageFlags, + SlashCommandBuilder, +} from 'discord.js'; +import { bySubcommand } from '../../core/define.js'; +import type { Feature } from '../../core/feature.js'; +import { + getGuildTimezone, + setGuildTimezone, +} from '../../core/guild-settings.js'; +import { requireZone } from '../../shared/time.js'; + +const data = new SlashCommandBuilder() + .setName('settings') + .setDescription('Server-wide bot settings') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('timezone') + .setDescription('View or set the server timezone used for schedules') + .addStringOption((o) => + o.setName('zone').setDescription('IANA timezone, e.g. Europe/Tallinn'), + ), + ); + +export const settingsFeature: Feature = { + name: 'settings', + permissions: [ + { id: 'settings:manage', description: 'Change server-wide bot settings' }, + ], + commands: [ + { + data: data.toJSON(), + execute: bySubcommand({ + timezone: async (interaction, ctx) => { + const zone = interaction.options.getString('zone'); + if (zone !== null) { + await ctx.authz.require(interaction.member, 'settings:manage'); + await setGuildTimezone( + ctx.db, + interaction.guildId, + requireZone(zone), + ); + } + const current = await getGuildTimezone( + ctx.db, + interaction.guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + await interaction.reply({ + content: `Server timezone: **${current}**`, + flags: MessageFlags.Ephemeral, + }); + }, + }), + }, + ], +}; From bc119bc1bc2363c1fae94340fb5c983e8936b3b5 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 006/199] feat(reminders): personal, channel and recurring reminders --- src/features/reminders/index.ts | 299 +++++++++++++++++++++++ src/features/reminders/reminders.test.ts | 120 +++++++++ src/features/reminders/schema.ts | 45 ++++ src/features/reminders/service.ts | 105 ++++++++ src/shared/time.test.ts | 80 ++++++ src/shared/time.ts | 150 ++++++++++++ 6 files changed, 799 insertions(+) create mode 100644 src/features/reminders/index.ts create mode 100644 src/features/reminders/reminders.test.ts create mode 100644 src/features/reminders/schema.ts create mode 100644 src/features/reminders/service.ts create mode 100644 src/shared/time.test.ts create mode 100644 src/shared/time.ts diff --git a/src/features/reminders/index.ts b/src/features/reminders/index.ts new file mode 100644 index 0000000..4b70fa2 --- /dev/null +++ b/src/features/reminders/index.ts @@ -0,0 +1,299 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { z } from 'zod'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, defineJob } from '../../core/define.js'; +import { asJobError } from '../../core/discord/errors.js'; +import type { + AppContext, + CommandInteraction, + Feature, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { PermanentError, UserError } from '../../shared/errors.js'; +import { + discordTime, + nextFutureOccurrence, + parseFutureWhen, + recurrences, + requireZone, +} from '../../shared/time.js'; +import type { Reminder } from './schema.js'; +import { + getReminder, + insertReminder, + listActiveReminders, + requireOwnReminder, + updateReminder, + type NewReminder, +} from './service.js'; + +const jobKey = (id: number) => `reminder:${id}`; + +async function deliver(ctx: AppContext, reminder: Reminder): Promise { + const text = `⏰ **Reminder:** ${reminder.message}`; + if (reminder.channelId === null) { + const user = await ctx.client.users.fetch(reminder.userId); + await user.send({ content: text }); + return; + } + const channel = await ctx.client.channels.fetch(reminder.channelId); + if (channel?.isSendable() !== true) { + throw new PermanentError('Reminder channel is not a text channel'); + } + await channel.send({ + content: `<@${reminder.userId}> ${text}`, + allowedMentions: { users: [reminder.userId] }, + }); +} + +export const deliverJob = defineJob({ + type: 'reminders:deliver', + payload: z.object({ reminderId: z.number().int() }), + // Reminders are still useful late, so overdue ones are delivered on recovery. + handle: async ({ reminderId }, _info, ctx) => { + const reminder = await getReminder(ctx.db, reminderId); + if (reminder?.status !== 'active') { + return null; + } + try { + await deliver(ctx, reminder); + } catch (error) { + const jobError = asJobError(error); + if (jobError instanceof PermanentError) { + await updateReminder(ctx.db, reminder.id, { + status: 'failed', + failure: jobError.message, + }); + } + throw jobError; + } + if (reminder.recurrence === null) { + await updateReminder(ctx.db, reminder.id, { status: 'done' }); + return null; + } + const next = nextFutureOccurrence( + reminder.runAt, + reminder.recurrence, + reminder.timezone, + ); + await updateReminder(ctx.db, reminder.id, { runAt: next }); + return { rescheduleAt: next }; + }, +}); + +/** Public API: other features create reminders through this. */ +export async function createReminder( + ctx: AppContext, + input: NewReminder, +): Promise { + const reminder = await insertReminder(ctx.db, input); + await ctx.scheduler.schedule( + deliverJob, + { reminderId: reminder.id }, + { + runAt: reminder.runAt, + key: jobKey(reminder.id), + }, + ); + return reminder; +} + +export function describeReminder(reminder: Reminder): string { + const where = reminder.channelId === null ? 'DM' : `<#${reminder.channelId}>`; + const repeat = reminder.recurrence === null ? '' : `, ${reminder.recurrence}`; + return `#${reminder.id} ${discordTime(reminder.runAt, 'f')} (${where}${repeat}) — ${reminder.message.slice(0, 80)}`; +} + +const remindme = new SlashCommandBuilder() + .setName('remindme') + .setDescription('Set a reminder') + .setContexts(InteractionContextType.Guild) + .addStringOption((o) => + o + .setName('when') + .setDescription('e.g. 30m, 2h, 1d, 18:30, 2026-11-20 18:00') + .setRequired(true), + ) + .addStringOption((o) => + o + .setName('message') + .setDescription('What to remind about') + .setRequired(true) + .setMaxLength(1000), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Post in a channel instead of DM') + .addChannelTypes(ChannelType.GuildText), + ) + .addStringOption((o) => + o + .setName('repeat') + .setDescription('Repeat the reminder') + .addChoices(recurrences.map((r) => ({ name: r, value: r }))), + ) + .addStringOption((o) => + o.setName('timezone').setDescription('IANA timezone for absolute times'), + ); + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Reminder') + .setRequired(true) + .setAutocomplete(true); + +const manage = new SlashCommandBuilder() + .setName('reminders') + .setDescription('Manage your reminders') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub.setName('list').setDescription('List your active reminders'), + ) + .addSubcommand((sub) => + sub + .setName('edit') + .setDescription('Change a reminder') + .addIntegerOption(idOption) + .addStringOption((o) => o.setName('when').setDescription('New time')) + .addStringOption((o) => + o.setName('message').setDescription('New message').setMaxLength(1000), + ), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel a reminder') + .addIntegerOption(idOption), + ); + +async function zoneFor( + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const explicit = interaction.options.getString('timezone'); + return explicit === null + ? getGuildTimezone(ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE) + : requireZone(explicit); +} + +export const remindersFeature: Feature = { + name: 'reminders', + permissions: [ + { id: 'reminder:channel', description: 'Post reminders in channels' }, + ], + jobs: [deliverJob], + commands: [ + { + data: remindme.toJSON(), + execute: async (interaction, ctx) => { + const channel = interaction.options.getChannel('channel', false, [ + ChannelType.GuildText, + ]); + if (channel) { + await ctx.authz.require(interaction.member, 'reminder:channel'); + } + const timezone = await zoneFor(interaction, ctx); + const reminder = await createReminder(ctx, { + guildId: interaction.guildId, + userId: interaction.user.id, + channelId: channel?.id ?? null, + message: interaction.options.getString('message', true), + runAt: parseFutureWhen( + interaction.options.getString('when', true), + timezone, + ), + // Discord enforces the choices, but option values are still untrusted. + recurrence: + recurrences.find( + (r) => r === interaction.options.getString('repeat'), + ) ?? null, + timezone, + }); + const note = channel + ? '' + : ' Make sure you allow DMs from server members.'; + await respond( + interaction, + `Reminder set: ${describeReminder(reminder)}.${note}`, + ); + }, + }, + { + data: manage.toJSON(), + execute: bySubcommand({ + list: async (interaction, ctx) => { + const active = await listActiveReminders( + ctx.db, + interaction.guildId, + interaction.user.id, + ); + await respond( + interaction, + active.length === 0 + ? 'You have no active reminders.' + : active.map(describeReminder).join('\n'), + ); + }, + edit: async (interaction, ctx) => { + const reminder = await requireOwnReminder( + ctx.db, + interaction.guildId, + interaction.user.id, + interaction.options.getInteger('id', true), + ); + const when = interaction.options.getString('when'); + const message = + interaction.options.getString('message') ?? reminder.message; + if (when === null && message === reminder.message) { + throw new UserError('Give a new time or message.'); + } + const runAt = + when === null + ? reminder.runAt + : parseFutureWhen(when, reminder.timezone); + await updateReminder(ctx.db, reminder.id, { message, runAt }); + await ctx.scheduler.schedule( + deliverJob, + { reminderId: reminder.id }, + { runAt, key: jobKey(reminder.id) }, + ); + await respond( + interaction, + `Updated: ${describeReminder({ ...reminder, message, runAt })}`, + ); + }, + cancel: async (interaction, ctx) => { + const reminder = await requireOwnReminder( + ctx.db, + interaction.guildId, + interaction.user.id, + interaction.options.getInteger('id', true), + ); + await updateReminder(ctx.db, reminder.id, { status: 'cancelled' }); + await ctx.scheduler.cancel(jobKey(reminder.id)); + await respond(interaction, `Cancelled reminder #${reminder.id}.`); + }, + }), + autocomplete: async (interaction, ctx) => { + const active = await listActiveReminders( + ctx.db, + interaction.guildId, + interaction.user.id, + ); + await interaction.respond( + active.map((r) => ({ + name: `#${r.id} ${r.message}`.slice(0, 100), + value: r.id, + })), + ); + }, + }, + ], +}; diff --git a/src/features/reminders/reminders.test.ts b/src/features/reminders/reminders.test.ts new file mode 100644 index 0000000..361b35d --- /dev/null +++ b/src/features/reminders/reminders.test.ts @@ -0,0 +1,120 @@ +import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { PermanentError, UserError } from '../../shared/errors.js'; +import { createReminder, deliverJob } from './index.js'; +import { getReminder, insertReminder, maxActivePerUser } from './service.js'; + +const cannotDm = new DiscordAPIError( + { + code: RESTJSONErrorCodes.CannotSendMessagesToThisUser, + message: 'Cannot send messages to this user', + }, + RESTJSONErrorCodes.CannotSendMessagesToThisUser, + 403, + 'POST', + '/channels/x/messages', + {}, +); + +function context() { + const send = vi.fn(async () => undefined); + const schedule = vi.fn(async () => undefined); + const ctx = { + db: noDatabase ? undefined : testDb(), + log: pino({ level: 'silent' }), + client: { users: { fetch: async () => ({ send }) } }, + scheduler: { schedule, cancel: vi.fn() }, + } as unknown as AppContext; + return { ctx, send, schedule }; +} + +const info = { id: 1, runAt: new Date(), attempt: 1 }; +const base = () => ({ + guildId: snowflake(), + userId: snowflake(), + channelId: null, + message: 'stand-up', + runAt: new Date(Date.now() + 60_000), + recurrence: null, + timezone: 'Europe/Tallinn', +}); + +describe.skipIf(noDatabase)('reminders', () => { + it('schedules a job keyed to the reminder', async () => { + const { ctx, schedule } = context(); + const reminder = await createReminder(ctx, base()); + expect(schedule).toHaveBeenCalledWith( + deliverJob, + { reminderId: reminder.id }, + { + runAt: reminder.runAt, + key: `reminder:${reminder.id}`, + }, + ); + }); + + it('delivers one-off reminders by DM and completes them', async () => { + const { ctx, send } = context(); + const reminder = await insertReminder(ctx.db, base()); + expect( + await deliverJob.run({ reminderId: reminder.id }, info, ctx), + ).toBeNull(); + expect(send).toHaveBeenCalledWith({ content: '⏰ **Reminder:** stand-up' }); + expect((await getReminder(ctx.db, reminder.id))?.status).toBe('done'); + }); + + it('reschedules recurring reminders into the future', async () => { + const { ctx } = context(); + const reminder = await insertReminder(ctx.db, { + ...base(), + runAt: new Date(Date.now() - 3 * 86_400_000), + recurrence: 'daily', + }); + const outcome = await deliverJob.run( + { reminderId: reminder.id }, + info, + ctx, + ); + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); + expect(outcome?.rescheduleAt.getTime()).toBeLessThanOrEqual( + Date.now() + 86_400_000, + ); + expect((await getReminder(ctx.db, reminder.id))?.status).toBe('active'); + }); + + it('fails permanently when DMs are closed', async () => { + const { ctx, send } = context(); + send.mockRejectedValue(cannotDm); + const reminder = await insertReminder(ctx.db, base()); + await expect( + deliverJob.run({ reminderId: reminder.id }, info, ctx), + ).rejects.toBeInstanceOf(PermanentError); + expect((await getReminder(ctx.db, reminder.id))?.status).toBe('failed'); + }); + + it('skips cancelled reminders', async () => { + const { ctx, send } = context(); + const reminder = await insertReminder(ctx.db, base()); + const { updateReminder } = await import('./service.js'); + await updateReminder(ctx.db, reminder.id, { status: 'cancelled' }); + await deliverJob.run({ reminderId: reminder.id }, info, ctx); + expect(send).not.toHaveBeenCalled(); + }); + + it('limits active reminders per user and message length', async () => { + const { ctx } = context(); + const input = base(); + for (let n = 0; n < maxActivePerUser; n++) { + await insertReminder(ctx.db, input); + } + await expect(insertReminder(ctx.db, input)).rejects.toBeInstanceOf( + UserError, + ); + await expect( + insertReminder(ctx.db, { ...base(), message: 'x'.repeat(1001) }), + ).rejects.toThrow('at most'); + }); +}); diff --git a/src/features/reminders/schema.ts b/src/features/reminders/schema.ts new file mode 100644 index 0000000..617dfdd --- /dev/null +++ b/src/features/reminders/schema.ts @@ -0,0 +1,45 @@ +import { + index, + pgEnum, + pgTable, + serial, + text, + timestamp, +} from 'drizzle-orm/pg-core'; + +export const reminderRecurrence = pgEnum('reminder_recurrence', [ + 'daily', + 'weekly', + 'monthly', +]); +export const reminderStatus = pgEnum('reminder_status', [ + 'active', + 'done', + 'cancelled', + 'failed', +]); + +export const reminders = pgTable( + 'reminders', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + userId: text('user_id').notNull(), + /** Null delivers by direct message. */ + channelId: text('channel_id'), + message: text('message').notNull(), + runAt: timestamp('run_at', { withTimezone: true }).notNull(), + recurrence: reminderRecurrence('recurrence'), + timezone: text('timezone').notNull(), + status: reminderStatus('status').notNull().default('active'), + failure: text('failure'), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + index('reminders_user_idx').on(table.guildId, table.userId, table.status), + ], +); + +export type Reminder = typeof reminders.$inferSelect; diff --git a/src/features/reminders/service.ts b/src/features/reminders/service.ts new file mode 100644 index 0000000..54e4097 --- /dev/null +++ b/src/features/reminders/service.ts @@ -0,0 +1,105 @@ +import { and, asc, count, eq } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import type { Recurrence } from '../../shared/time.js'; +import { reminders, type Reminder } from './schema.js'; + +export const maxActivePerUser = 25; +export const maxMessageLength = 1000; + +export type NewReminder = { + guildId: string; + userId: string; + channelId: string | null; + message: string; + runAt: Date; + recurrence: Recurrence | null; + timezone: string; +}; + +export async function insertReminder( + db: Db, + input: NewReminder, +): Promise { + if (input.message.length > maxMessageLength) { + throw new UserError( + `Reminders can be at most ${maxMessageLength} characters.`, + ); + } + return db.transaction(async (tx) => { + // ponytail: two simultaneous requests can both pass this soft limit; fine for abuse prevention. + const [active] = await tx + .select({ total: count() }) + .from(reminders) + .where( + and( + eq(reminders.guildId, input.guildId), + eq(reminders.userId, input.userId), + eq(reminders.status, 'active'), + ), + ); + if ((active?.total ?? 0) >= maxActivePerUser) { + throw new UserError( + `You can have at most ${maxActivePerUser} active reminders.`, + ); + } + const [row] = await tx.insert(reminders).values(input).returning(); + if (!row) { + throw new Error('Insert returned no row'); + } + return row; + }); +} + +export async function getReminder( + db: Db, + id: number, +): Promise { + const [row] = await db.select().from(reminders).where(eq(reminders.id, id)); + return row; +} + +export async function listActiveReminders( + db: Db, + guildId: string, + userId: string, +): Promise { + return db + .select() + .from(reminders) + .where( + and( + eq(reminders.guildId, guildId), + eq(reminders.userId, userId), + eq(reminders.status, 'active'), + ), + ) + .orderBy(asc(reminders.runAt)) + .limit(maxActivePerUser); +} + +export async function updateReminder( + db: Db, + id: number, + changes: Partial>, +): Promise { + await db.update(reminders).set(changes).where(eq(reminders.id, id)); +} + +/** Active reminders the user owns in this guild; others are reported as missing. */ +export async function requireOwnReminder( + db: Db, + guildId: string, + userId: string, + id: number, +): Promise { + const reminder = await getReminder(db, id); + if ( + reminder?.guildId !== guildId || + reminder.userId !== userId || + reminder.status !== 'active' + ) { + throw new UserError(`You have no active reminder #${id}.`); + } + return reminder; +} diff --git a/src/shared/time.test.ts b/src/shared/time.test.ts new file mode 100644 index 0000000..ba25b39 --- /dev/null +++ b/src/shared/time.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; +import { UserError } from './errors.js'; +import { + nextFutureOccurrence, + nextOccurrence, + parseFutureWhen, + parseWhen, +} from './time.js'; + +const zone = 'Europe/Tallinn'; +const now = new Date('2026-03-10T10:00:00Z'); // 12:00 in Tallinn + +describe('parseWhen', () => { + it.each([ + ['10m', 10 * 60_000], + ['2h30m', 150 * 60_000], + ['in 1d 2h', 26 * 3_600_000], + ['1w', 7 * 86_400_000], + ])('reads relative "%s"', (input, offset) => { + expect(parseWhen(input, zone, now).getTime()).toBe(now.getTime() + offset); + }); + + it('reads absolute times in the given zone', () => { + expect(parseWhen('2026-11-20 18:00', zone, now).toISOString()).toBe( + '2026-11-20T16:00:00.000Z', + ); + expect(parseWhen('20.11.2026 18:00', zone, now).toISOString()).toBe( + '2026-11-20T16:00:00.000Z', + ); + expect(parseWhen('2026-07-01 18:00', 'UTC', now).toISOString()).toBe( + '2026-07-01T18:00:00.000Z', + ); + }); + + it('reads a bare clock time as its next occurrence', () => { + expect(parseWhen('18:30', zone, now).toISOString()).toBe( + '2026-03-10T16:30:00.000Z', + ); + expect(parseWhen('09:00', zone, now).toISOString()).toBe( + '2026-03-11T07:00:00.000Z', + ); + }); + + it('rejects nonsense, invalid zones and past times', () => { + expect(() => parseWhen('next tuesday-ish', zone, now)).toThrow(UserError); + expect(() => parseWhen('2026-01-01 10:00', 'Mars/Base', now)).toThrow( + 'Unknown timezone', + ); + expect(() => parseFutureWhen('2020-01-01 10:00', zone, now)).toThrow( + 'in the past', + ); + }); +}); + +describe('recurrence', () => { + it('keeps the wall-clock time across a DST change', () => { + // Tallinn moves to summer time on 2026-03-29. + const before = new Date('2026-03-28T07:00:00Z'); // 09:00 EET + expect(nextOccurrence(before, 'daily', zone).toISOString()).toBe( + '2026-03-29T06:00:00.000Z', + ); + }); + + it('skips occurrences missed while offline', () => { + const old = new Date('2026-03-01T10:00:00Z'); + expect(nextFutureOccurrence(old, 'weekly', 'UTC', now).toISOString()).toBe( + '2026-03-15T10:00:00.000Z', + ); + }); + + it('clamps monthly recurrences to shorter months', () => { + expect( + nextOccurrence( + new Date('2026-01-31T10:00:00Z'), + 'monthly', + 'UTC', + ).toISOString(), + ).toBe('2026-02-28T10:00:00.000Z'); + }); +}); diff --git a/src/shared/time.ts b/src/shared/time.ts new file mode 100644 index 0000000..2436128 --- /dev/null +++ b/src/shared/time.ts @@ -0,0 +1,150 @@ +import { DateTime, IANAZone } from 'luxon'; +import { UserError } from './errors.js'; + +const unitMs: Partial> = { + w: 604_800_000, + d: 86_400_000, + h: 3_600_000, + m: 60_000, +}; +const absoluteFormats = [ + 'yyyy-MM-dd HH:mm', + "yyyy-MM-dd'T'HH:mm", + 'd.M.yyyy HH:mm', + 'd.M.yyyy H:mm', + 'yyyy-MM-dd', + 'd.M.yyyy', +]; + +export const recurrences = ['daily', 'weekly', 'monthly'] as const; +export type Recurrence = (typeof recurrences)[number]; + +export function requireZone(zone: string): string { + if (!IANAZone.isValidZone(zone)) { + throw new UserError( + `Unknown timezone "${zone}". Use an IANA name like Europe/Tallinn.`, + ); + } + return zone; +} + +function parseRelative(input: string, now: Date): Date | undefined { + const compact = input + .trim() + .replace(/^in\s+/i, '') + .replaceAll(/\s+/g, ''); + if (!/^(?:\d+[wdhm])+$/i.test(compact)) { + return undefined; + } + let total = 0; + for (const part of compact.toLowerCase().split(/(?<=[wdhm])/)) { + total += Number(part.slice(0, -1)) * (unitMs[part.slice(-1)] ?? 0); + } + return new Date(now.getTime() + total); +} + +function parseAbsolute( + input: string, + zone: string, + now: Date, +): Date | undefined { + const trimmed = input.trim(); + const clock = /^(\d{1,2}):(\d{2})$/.exec(trimmed); + if (clock) { + // A bare time means its next occurrence. + const today = DateTime.fromJSDate(now, { zone }).set({ + hour: Number(clock[1]), + minute: Number(clock[2]), + second: 0, + millisecond: 0, + }); + if (!today.isValid) { + return undefined; + } + return ( + today.toMillis() <= now.getTime() ? today.plus({ days: 1 }) : today + ).toJSDate(); + } + for (const format of absoluteFormats) { + const parsed = DateTime.fromFormat(trimmed, format, { zone }); + if (parsed.isValid) { + return parsed.toJSDate(); + } + } + return undefined; +} + +/** + * Parses "10m", "2h30m", "1w 2d", "18:30", "2026-11-20 18:00" or + * "20.11.2026 18:00". Absolute times are read in the given IANA zone. + */ +export function parseWhen(input: string, zone: string, now = new Date()): Date { + const date = + parseRelative(input, now) ?? parseAbsolute(input, requireZone(zone), now); + if (date === undefined) { + throw new UserError( + `I could not read "${input}". Try "30m", "2h", "1d", "18:30" or "2026-11-20 18:00".`, + ); + } + return date; +} + +export function parseFutureWhen( + input: string, + zone: string, + now = new Date(), +): Date { + const date = parseWhen(input, zone, now); + if (date.getTime() <= now.getTime()) { + throw new UserError('That time is in the past.'); + } + return date; +} + +/** Advances by wall-clock time in the zone, so recurrences survive DST. */ +export function nextOccurrence( + from: Date, + recurrence: Recurrence, + zone: string, +): Date { + const step = { + daily: { days: 1 }, + weekly: { weeks: 1 }, + monthly: { months: 1 }, + }[recurrence]; + return DateTime.fromJSDate(from, { zone }).plus(step).toJSDate(); +} + +/** First occurrence strictly after `now`, skipping any missed while offline. */ +export function nextFutureOccurrence( + from: Date, + recurrence: Recurrence, + zone: string, + now = new Date(), +): Date { + let next = nextOccurrence(from, recurrence, zone); + while (next.getTime() <= now.getTime()) { + next = nextOccurrence(next, recurrence, zone); + } + return next; +} + +/** Discord renders these in each reader's own timezone. */ +export function discordTime( + date: Date, + style: 'F' | 'R' | 'f' | 'D' = 'F', +): string { + return ``; +} + +/** The next time the clock in `zone` reads `hour`:00, strictly after now. */ +export function nextDailyRun( + zone: string, + hour: number, + now = DateTime.now(), +): Date { + const today = now + .setZone(zone) + .set({ hour, minute: 0, second: 0, millisecond: 0 }); + return (today <= now ? today.plus({ days: 1 }) : today).toJSDate(); +} From ec219d633bbd18c6e66224ae0766f05f209b651d Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 007/199] feat(announcements): drafts, previews and scheduled publishing --- .../announcements/announcements.test.ts | 125 +++++ src/features/announcements/index.ts | 514 ++++++++++++++++++ src/features/announcements/schema.ts | 44 ++ src/features/announcements/service.ts | 100 ++++ 4 files changed, 783 insertions(+) create mode 100644 src/features/announcements/announcements.test.ts create mode 100644 src/features/announcements/index.ts create mode 100644 src/features/announcements/schema.ts create mode 100644 src/features/announcements/service.ts diff --git a/src/features/announcements/announcements.test.ts b/src/features/announcements/announcements.test.ts new file mode 100644 index 0000000..b8520f3 --- /dev/null +++ b/src/features/announcements/announcements.test.ts @@ -0,0 +1,125 @@ +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { render } from './index.js'; +import type { Announcement } from './schema.js'; +import { getAnnouncement, insertAnnouncement, transition } from './service.js'; + +const draft = (overrides: Partial = {}): Announcement => ({ + id: 1, + guildId: 'g', + authorId: 'a', + channelId: 'c', + title: 'Hello', + content: 'World', + embed: false, + mentionRoleId: null, + status: 'draft', + scheduledAt: null, + publishedAt: null, + messageId: null, + failure: null, + createdAt: new Date(), + ...overrides, +}); + +describe('announcement rendering', () => { + it('never parses mentions written into the text', () => { + expect(render(draft({ content: '@everyone hi' })).allowedMentions).toEqual({ + parse: [], + }); + }); + + it('only allows the chosen role or @everyone', () => { + expect(render(draft({ mentionRoleId: 'r' })).allowedMentions).toEqual({ + roles: ['r'], + }); + expect(render(draft({ mentionRoleId: 'g' })).allowedMentions).toEqual({ + parse: ['everyone'], + }); + }); + + it('rejects plain messages over the Discord limit', () => { + expect(() => render(draft({ content: 'x'.repeat(2001) }))).toThrow('2000'); + expect(() => + render(draft({ content: 'x'.repeat(2001), embed: true })), + ).not.toThrow(); + }); +}); + +const input = () => ({ + guildId: snowflake(), + authorId: 'a', + channelId: 'c', + title: 'Hello', + content: 'World', + embed: false, + mentionRoleId: null, +}); + +describe.skipIf(noDatabase)('announcement publishing', () => { + it('lets only one concurrent publish claim a draft', async () => { + const db = testDb(); + const row = await insertAnnouncement(db, input()); + const claims = await Promise.all( + Array.from({ length: 5 }, () => + transition(db, row.id, ['draft'], { status: 'publishing' }), + ), + ); + expect(claims.filter(Boolean)).toHaveLength(1); + }); + + it('skips scheduled announcements that are long overdue', async () => { + const db = testDb(); + const { announcementsFeature } = await import('./index.js'); + const job = announcementsFeature.jobs?.[0]; + const send = vi.fn(); + const ctx = { + db, + log: pino({ level: 'silent' }), + client: { + channels: { fetch: async () => ({ isSendable: () => true, send }) }, + }, + } as unknown as AppContext; + const row = await insertAnnouncement(db, input()); + await transition(db, row.id, ['draft'], { + status: 'scheduled', + scheduledAt: new Date(Date.now() - 2 * 3_600_000), + }); + await job?.run( + { announcementId: row.id }, + { id: 1, runAt: new Date(), attempt: 1 }, + ctx, + ); + expect(send).not.toHaveBeenCalled(); + expect((await getAnnouncement(db, row.id))?.status).toBe('failed'); + }); + + it('publishes due scheduled announcements once', async () => { + const db = testDb(); + const { announcementsFeature } = await import('./index.js'); + const job = announcementsFeature.jobs?.[0]; + const send = vi.fn(async () => ({ id: 'm1' })); + const ctx = { + db, + log: pino({ level: 'silent' }), + client: { + channels: { fetch: async () => ({ isSendable: () => true, send }) }, + }, + } as unknown as AppContext; + const row = await insertAnnouncement(db, input()); + await transition(db, row.id, ['draft'], { + status: 'scheduled', + scheduledAt: new Date(), + }); + const info = { id: 1, runAt: new Date(), attempt: 1 }; + await job?.run({ announcementId: row.id }, info, ctx); + await job?.run({ announcementId: row.id }, info, ctx); + expect(send).toHaveBeenCalledOnce(); + expect(await getAnnouncement(db, row.id)).toMatchObject({ + status: 'published', + messageId: 'm1', + }); + }); +}); diff --git a/src/features/announcements/index.ts b/src/features/announcements/index.ts new file mode 100644 index 0000000..8335cd7 --- /dev/null +++ b/src/features/announcements/index.ts @@ -0,0 +1,514 @@ +import { + ChannelType, + EmbedBuilder, + InteractionContextType, + LabelBuilder, + MessageFlags, + ModalBuilder, + PermissionFlagsBits, + SlashCommandBuilder, + TextInputBuilder, + TextInputStyle, + type BaseMessageOptions, + type GuildMember, + type MessageMentionOptions, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { z } from 'zod'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, defineJob } from '../../core/define.js'; +import { asJobError } from '../../core/discord/errors.js'; +import type { + AppContext, + CommandInteraction, + ComponentHandler, + Feature, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { customId } from '../../core/registry.js'; +import { PermanentError, UserError } from '../../shared/errors.js'; +import { discordTime, parseFutureWhen } from '../../shared/time.js'; +import type { Announcement } from './schema.js'; +import { + getAnnouncement, + insertAnnouncement, + listAnnouncements, + requireAnnouncement, + transition, + updateContent, +} from './service.js'; + +const jobKey = (id: number) => `announcement:${id}`; +/** A scheduled announcement this late is stale and is not posted. */ +const maxLatenessMs = 60 * 60 * 1000; +const maxContent = 4000; + +function mentions(announcement: Announcement): { + prefix: string; + allowed: MessageMentionOptions; +} { + const role = announcement.mentionRoleId; + if (role === null) { + return { prefix: '', allowed: { parse: [] } }; + } + if (role === announcement.guildId) { + return { prefix: '@everyone ', allowed: { parse: ['everyone'] } }; + } + return { prefix: `<@&${role}> `, allowed: { roles: [role] } }; +} + +export function render(announcement: Announcement): BaseMessageOptions { + const { prefix, allowed } = mentions(announcement); + if (announcement.embed) { + const embed = new EmbedBuilder() + .setDescription(announcement.content) + .setColor(0xff_ac_1c); + if (announcement.title !== null) { + embed.setTitle(announcement.title); + } + return { + ...(prefix === '' ? {} : { content: prefix.trim() }), + embeds: [embed], + allowedMentions: allowed, + }; + } + const heading = + announcement.title === null ? '' : `**${announcement.title}**\n`; + const content = `${prefix}${heading}${announcement.content}`; + if (content.length > 2000) { + throw new UserError( + 'Plain announcements are limited to 2000 characters; use an embed.', + ); + } + return { content, allowedMentions: allowed }; +} + +/** A private rendering that shows, but never sends, the mention. */ +function preview(announcement: Announcement, note: string) { + const rendered = render(announcement); + return { + content: [note, rendered.content].filter(Boolean).join('\n\n'), + embeds: rendered.embeds ?? [], + allowedMentions: { parse: [] }, + flags: MessageFlags.Ephemeral, + } as const; +} + +/** Claims, posts and records an announcement. Posting happens at most once. */ +async function publish( + ctx: AppContext, + id: number, + from: Array, +): Promise { + const claimed = await transition(ctx.db, id, from, { status: 'publishing' }); + if (!claimed) { + throw new UserError( + `Announcement #${id} cannot be published in its current state.`, + ); + } + try { + const channel = await ctx.client.channels.fetch(claimed.channelId); + if (channel?.isSendable() !== true) { + throw new PermanentError('Destination channel is not available'); + } + const message = await channel.send(render(claimed)); + const published = await transition(ctx.db, id, ['publishing'], { + status: 'published', + publishedAt: new Date(), + messageId: message.id, + failure: null, + }); + ctx.log.info( + { announcementId: id, messageId: message.id }, + 'Announcement published', + ); + return published ?? claimed; + } catch (error) { + const jobError = asJobError(error); + const permanent = + jobError instanceof PermanentError || error instanceof UserError; + const message = error instanceof Error ? error.message : String(error); + // Transient failures return to their previous state so they can be retried. + await transition(ctx.db, id, ['publishing'], { + status: permanent ? 'failed' : (from[0] ?? 'draft'), + failure: message, + }); + throw jobError; + } +} + +const publishJob = defineJob({ + type: 'announcements:publish', + payload: z.object({ announcementId: z.number().int() }), + handle: async ({ announcementId }, _info, ctx) => { + const announcement = await getAnnouncement(ctx.db, announcementId); + if (announcement?.status !== 'scheduled') { + return; + } + const due = announcement.scheduledAt ?? announcement.createdAt; + if (Date.now() - due.getTime() > maxLatenessMs) { + await transition(ctx.db, announcementId, ['scheduled'], { + status: 'failed', + failure: 'Skipped: the scheduled time passed while the bot was offline', + }); + ctx.log.warn({ announcementId }, 'Skipped stale scheduled announcement'); + return; + } + // Retries come back here while still 'scheduled'; publish() restores that state. + await publish(ctx, announcementId, ['scheduled']); + }, +}); + +function checkMention(member: GuildMember, roleId: string | null): void { + if (roleId === null) { + return; + } + const canPingAll = member.permissions.has( + PermissionFlagsBits.MentionEveryone, + ); + const role = member.guild.roles.cache.get(roleId); + if ( + roleId === member.guild.id + ? !canPingAll + : role?.mentionable !== true && !canPingAll + ) { + throw new UserError('You may not mention that role.'); + } +} + +function contentModal( + id: string, + title: string, + current?: Announcement, +): ModalBuilder { + const titleInput = new TextInputBuilder() + .setCustomId('title') + .setStyle(TextInputStyle.Short) + .setRequired(false) + .setMaxLength(256); + const contentInput = new TextInputBuilder() + .setCustomId('content') + .setStyle(TextInputStyle.Paragraph) + .setMaxLength(maxContent); + if (current?.title !== null && current?.title !== undefined) { + titleInput.setValue(current.title); + } + if (current) { + contentInput.setValue(current.content); + } + return new ModalBuilder() + .setCustomId(id) + .setTitle(title) + .addLabelComponents( + new LabelBuilder().setLabel('Title').setTextInputComponent(titleInput), + new LabelBuilder() + .setLabel('Content') + .setTextInputComponent(contentInput), + ); +} + +async function requireEditable( + interaction: CommandInteraction | Parameters[0], + ctx: AppContext, + id: number, +): Promise { + const announcement = await requireAnnouncement( + ctx.db, + interaction.guildId, + id, + ); + if (announcement.authorId !== interaction.user.id) { + await ctx.authz.require(interaction.member, 'announcement:publish'); + } + return announcement; +} + +const createModal: ComponentHandler = { + prefix: 'announcements:create', + permission: 'announcement:create', + execute: async (interaction, args, ctx) => { + if (!interaction.isModalSubmit()) { + return; + } + const [channelId = '', embed, role] = args; + const mentionRoleId = role === undefined || role === '-' ? null : role; + checkMention(interaction.member, mentionRoleId); + const title = interaction.fields.getTextInputValue('title').trim(); + const announcement = await insertAnnouncement(ctx.db, { + guildId: interaction.guildId, + authorId: interaction.user.id, + channelId, + title: title === '' ? null : title, + content: interaction.fields.getTextInputValue('content'), + embed: embed === '1', + mentionRoleId, + }); + await interaction.reply( + preview( + announcement, + `Draft #${announcement.id} for <#${channelId}>. Publish with \`/announce publish\` or \`/announce schedule\`.`, + ), + ); + }, +}; + +const editModal: ComponentHandler = { + prefix: 'announcements:edit', + execute: async (interaction, args, ctx) => { + if (!interaction.isModalSubmit()) { + return; + } + const announcement = await requireEditable( + interaction, + ctx, + Number(args[0]), + ); + const title = interaction.fields.getTextInputValue('title').trim(); + const updated = { + ...announcement, + title: title === '' ? null : title, + content: interaction.fields.getTextInputValue('content'), + }; + render(updated); // Validates length before saving. + await updateContent(ctx.db, announcement.id, updated); + if ( + announcement.status === 'published' && + announcement.messageId !== null + ) { + const channel = await ctx.client.channels.fetch(announcement.channelId); + if (channel?.isTextBased() === true) { + await channel.messages.edit(announcement.messageId, { + ...render(updated), + allowedMentions: { parse: [] }, + }); + } + } + await interaction.reply({ + content: `Announcement #${announcement.id} updated.`, + flags: MessageFlags.Ephemeral, + }); + }, +}; + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Announcement') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('announce') + .setDescription('Create and publish announcements') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Draft an announcement') + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post it') + .setRequired(true) + .addChannelTypes( + ChannelType.GuildText, + ChannelType.GuildAnnouncement, + ), + ) + .addBooleanOption((o) => + o.setName('embed').setDescription('Post as an embed (default yes)'), + ) + .addRoleOption((o) => + o.setName('mention').setDescription('Role to mention'), + ), + ) + .addSubcommand((sub) => + sub + .setName('preview') + .setDescription('Preview privately') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('publish') + .setDescription('Publish now') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('schedule') + .setDescription('Publish later') + .addIntegerOption(idOption) + .addStringOption((o) => + o + .setName('when') + .setDescription('e.g. 2h, 2026-11-20 18:00') + .setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('edit') + .setDescription('Edit the text') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel a draft or schedule') + .addIntegerOption(idOption), + ); + +export const announcementsFeature: Feature = { + name: 'announcements', + permissions: [ + { id: 'announcement:create', description: 'Draft announcements' }, + { + id: 'announcement:publish', + description: 'Publish and edit any announcement', + }, + { id: 'announcement:schedule', description: 'Schedule announcements' }, + ], + jobs: [publishJob], + components: [createModal, editModal], + commands: [ + { + data: data.toJSON(), + permissions: { + create: 'announcement:create', + publish: 'announcement:publish', + schedule: 'announcement:schedule', + }, + execute: bySubcommand({ + create: async (interaction) => { + const channel = interaction.options.getChannel('channel', true); + const role = interaction.options.getRole('mention'); + checkMention(interaction.member, role?.id ?? null); + const embed = interaction.options.getBoolean('embed') ?? true; + const id = customId( + 'announcements:create', + channel.id, + embed ? 1 : 0, + role?.id ?? '-', + ); + await interaction.showModal(contentModal(id, 'New announcement')); + }, + preview: async (interaction, ctx) => { + const announcement = await requireEditable( + interaction, + ctx, + interaction.options.getInteger('id', true), + ); + await interaction.reply( + preview( + announcement, + `Preview of #${announcement.id} (${announcement.status}):`, + ), + ); + }, + publish: async (interaction, ctx) => { + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const id = interaction.options.getInteger('id', true); + await requireAnnouncement(ctx.db, interaction.guildId, id); + await ctx.scheduler.cancel(jobKey(id)); + const published = await publish(ctx, id, [ + 'draft', + 'scheduled', + 'failed', + ]); + await interaction.editReply( + `Published #${id} in <#${published.channelId}>.`, + ); + }, + schedule: async (interaction, ctx) => { + const id = interaction.options.getInteger('id', true); + await requireAnnouncement(ctx.db, interaction.guildId, id); + const zone = await getGuildTimezone( + ctx.db, + interaction.guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + const runAt = parseFutureWhen( + interaction.options.getString('when', true), + zone, + ); + const scheduled = await transition( + ctx.db, + id, + ['draft', 'scheduled', 'failed'], + { + status: 'scheduled', + scheduledAt: runAt, + failure: null, + }, + ); + if (!scheduled) { + throw new UserError( + `Announcement #${id} cannot be scheduled in its current state.`, + ); + } + await ctx.scheduler.schedule( + publishJob, + { announcementId: id }, + { runAt, key: jobKey(id) }, + ); + await respond( + interaction, + `Announcement #${id} will be published ${discordTime(runAt)}.`, + ); + }, + edit: async (interaction, ctx) => { + const announcement = await requireEditable( + interaction, + ctx, + interaction.options.getInteger('id', true), + ); + await interaction.showModal( + contentModal( + customId('announcements:edit', announcement.id), + `Edit announcement #${announcement.id}`, + announcement, + ), + ); + }, + cancel: async (interaction, ctx) => { + const announcement = await requireEditable( + interaction, + ctx, + interaction.options.getInteger('id', true), + ); + const cancelled = await transition( + ctx.db, + announcement.id, + ['draft', 'scheduled', 'failed'], + { + status: 'cancelled', + }, + ); + if (!cancelled) { + throw new UserError( + `Announcement #${announcement.id} is already ${announcement.status}.`, + ); + } + await ctx.scheduler.cancel(jobKey(announcement.id)); + await respond( + interaction, + `Cancelled announcement #${announcement.id}.`, + ); + }, + }), + autocomplete: async (interaction, ctx) => { + const rows = await listAnnouncements(ctx.db, interaction.guildId); + await interaction.respond( + rows.map((row) => ({ + name: `#${row.id} [${row.status}] ${row.title ?? row.content}`.slice( + 0, + 100, + ), + value: row.id, + })), + ); + }, + }, + ], +}; diff --git a/src/features/announcements/schema.ts b/src/features/announcements/schema.ts new file mode 100644 index 0000000..5c857cc --- /dev/null +++ b/src/features/announcements/schema.ts @@ -0,0 +1,44 @@ +import { + boolean, + index, + pgEnum, + pgTable, + serial, + text, + timestamp, +} from 'drizzle-orm/pg-core'; + +export const announcementStatus = pgEnum('announcement_status', [ + 'draft', + 'scheduled', + 'publishing', + 'published', + 'cancelled', + 'failed', +]); + +export const announcements = pgTable( + 'announcements', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + authorId: text('author_id').notNull(), + channelId: text('channel_id').notNull(), + title: text('title'), + content: text('content').notNull(), + embed: boolean('embed').notNull().default(true), + /** A role ID, or the guild ID for @everyone. */ + mentionRoleId: text('mention_role_id'), + status: announcementStatus('status').notNull().default('draft'), + scheduledAt: timestamp('scheduled_at', { withTimezone: true }), + publishedAt: timestamp('published_at', { withTimezone: true }), + messageId: text('message_id'), + failure: text('failure'), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [index('announcements_guild_idx').on(table.guildId, table.status)], +); + +export type Announcement = typeof announcements.$inferSelect; diff --git a/src/features/announcements/service.ts b/src/features/announcements/service.ts new file mode 100644 index 0000000..9a3a0c9 --- /dev/null +++ b/src/features/announcements/service.ts @@ -0,0 +1,100 @@ +import { and, desc, eq, inArray } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import { announcements, type Announcement } from './schema.js'; + +type Status = Announcement['status']; + +export async function insertAnnouncement( + db: Db, + input: Pick< + Announcement, + | 'guildId' + | 'authorId' + | 'channelId' + | 'title' + | 'content' + | 'embed' + | 'mentionRoleId' + >, +): Promise { + const [row] = await db.insert(announcements).values(input).returning(); + if (!row) { + throw new Error('Insert returned no row'); + } + return row; +} + +export async function requireAnnouncement( + db: Db, + guildId: string, + id: number, +): Promise { + const [row] = await db + .select() + .from(announcements) + .where(and(eq(announcements.id, id), eq(announcements.guildId, guildId))); + if (!row) { + throw new UserError(`Announcement #${id} does not exist.`); + } + return row; +} + +export async function getAnnouncement( + db: Db, + id: number, +): Promise { + const [row] = await db + .select() + .from(announcements) + .where(eq(announcements.id, id)); + return row; +} + +export async function listAnnouncements(db: Db, guildId: string) { + return db + .select({ + id: announcements.id, + title: announcements.title, + content: announcements.content, + status: announcements.status, + }) + .from(announcements) + .where( + and( + eq(announcements.guildId, guildId), + inArray(announcements.status, ['draft', 'scheduled']), + ), + ) + .orderBy(desc(announcements.id)) + .limit(25); +} + +/** + * Moves an announcement between states only if it is currently in one of + * `from`. Publishing claims the row this way first, so concurrent publish + * attempts cannot post it twice. + */ +export async function transition( + db: Db, + id: number, + from: readonly Status[], + changes: Partial & { status: Status }, +): Promise { + const [row] = await db + .update(announcements) + .set(changes) + .where( + and(eq(announcements.id, id), inArray(announcements.status, [...from])), + ) + .returning(); + return row; +} + +export async function updateContent( + db: Db, + id: number, + changes: Pick, +): Promise { + await db.update(announcements).set(changes).where(eq(announcements.id, id)); +} From 3a2072d2aac06e2563b90e6c76f62c168530cbcf Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 008/199] feat(events): events with RSVPs, capacity and reminders --- src/features/events/events.test.ts | 125 ++++++ src/features/events/index.ts | 627 +++++++++++++++++++++++++++++ src/features/events/schema.ts | 70 ++++ src/features/events/service.ts | 164 ++++++++ 4 files changed, 986 insertions(+) create mode 100644 src/features/events/events.test.ts create mode 100644 src/features/events/index.ts create mode 100644 src/features/events/schema.ts create mode 100644 src/features/events/service.ts diff --git a/src/features/events/events.test.ts b/src/features/events/events.test.ts new file mode 100644 index 0000000..18e67b9 --- /dev/null +++ b/src/features/events/events.test.ts @@ -0,0 +1,125 @@ +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { UserError } from '../../shared/errors.js'; +import { createEvent, remindJob } from './index.js'; +import { + insertEvent, + listAttendees, + rsvpCounts, + setRsvp, + updateEvent, +} from './service.js'; + +const base = () => ({ + guildId: snowflake(), + title: 'Board game night', + startsAt: new Date(Date.now() + 3 * 3_600_000), + timezone: 'Europe/Tallinn', + organizerId: snowflake(), + channelId: snowflake(), +}); + +describe.skipIf(noDatabase)('event RSVPs', () => { + const db = noDatabase ? undefined : testDb(); + const database = () => { + if (!db) { + throw new Error('unreachable'); + } + return db; + }; + + it('records RSVPs and lets members change them without duplicates', async () => { + const event = await insertEvent(database(), base()); + const user = snowflake(); + await setRsvp(database(), event.id, user, 'going'); + await setRsvp(database(), event.id, user, 'maybe'); + await setRsvp(database(), event.id, user, 'maybe'); + expect(await listAttendees(database(), event.id)).toEqual([ + { userId: user, status: 'maybe' }, + ]); + expect(await rsvpCounts(database(), event.id)).toEqual({ + going: 0, + maybe: 1, + not_going: 0, + }); + }); + + it('enforces capacity but lets attendees keep their spot', async () => { + const event = await insertEvent(database(), { ...base(), capacity: 1 }); + const [first, second] = [snowflake(), snowflake()]; + await setRsvp(database(), event.id, first, 'going'); + await setRsvp(database(), event.id, first, 'going'); + await expect( + setRsvp(database(), event.id, second, 'going'), + ).rejects.toThrow('full'); + await setRsvp(database(), event.id, second, 'maybe'); + await setRsvp(database(), event.id, first, 'not_going'); + await setRsvp(database(), event.id, second, 'going'); + expect((await rsvpCounts(database(), event.id)).going).toBe(1); + }); + + it('never exceeds capacity under concurrent registrations', async () => { + const event = await insertEvent(database(), { ...base(), capacity: 3 }); + const results = await Promise.allSettled( + Array.from({ length: 15 }, () => + setRsvp(database(), event.id, snowflake(), 'going'), + ), + ); + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(3); + expect((await rsvpCounts(database(), event.id)).going).toBe(3); + }); + + it('closes RSVPs once cancelled', async () => { + const event = await insertEvent(database(), base()); + await updateEvent(database(), event.id, { status: 'cancelled' }); + await expect( + setRsvp(database(), event.id, snowflake(), 'going'), + ).rejects.toBeInstanceOf(UserError); + }); + + it('validates times and capacity', async () => { + const start = new Date(Date.now() + 3_600_000); + await expect( + insertEvent(database(), { ...base(), startsAt: start, endsAt: start }), + ).rejects.toThrow('end'); + await expect( + insertEvent(database(), { ...base(), capacity: 0 }), + ).rejects.toThrow('Capacity'); + }); + + it('publishes, schedules future reminders and skips reminders for cancelled events', async () => { + const send = vi.fn(async () => ({ id: snowflake() })); + const schedule = vi.fn(async () => undefined); + const ctx = { + db: database(), + log: pino({ level: 'silent' }), + client: { + channels: { fetch: async () => ({ isSendable: () => true, send }) }, + }, + scheduler: { schedule, cancel: vi.fn() }, + } as unknown as AppContext; + const event = await createEvent(ctx, { + ...base(), + reminderMinutes: [60, 600], + }); + expect(event.messageId).not.toBeNull(); + // 600 minutes before a start 3h away is already past, so only one job. + expect(schedule).toHaveBeenCalledOnce(); + expect(schedule).toHaveBeenCalledWith( + remindJob, + { eventId: event.id, minutes: 60 }, + expect.anything(), + ); + + send.mockClear(); + await updateEvent(database(), event.id, { status: 'cancelled' }); + await remindJob.run( + { eventId: event.id, minutes: 60 }, + { id: 1, runAt: new Date(), attempt: 1 }, + ctx, + ); + expect(send).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/events/index.ts b/src/features/events/index.ts new file mode 100644 index 0000000..cc33ea0 --- /dev/null +++ b/src/features/events/index.ts @@ -0,0 +1,627 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ChannelType, + EmbedBuilder, + GuildScheduledEventEntityType, + GuildScheduledEventPrivacyLevel, + InteractionContextType, + MessageFlags, + SlashCommandBuilder, + type BaseMessageOptions, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { z } from 'zod'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, defineJob } from '../../core/define.js'; +import { asJobError, isUnknownObject } from '../../core/discord/errors.js'; +import type { + AppContext, + CommandInteraction, + ComponentHandler, + Feature, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { customId } from '../../core/registry.js'; +import { UserError } from '../../shared/errors.js'; +import { + discordTime, + parseFutureWhen, + parseWhen, + requireZone, +} from '../../shared/time.js'; +import type { Event, RsvpStatus } from './schema.js'; +import { + getEvent, + insertEvent, + listAttendees, + listUpcoming, + requireEvent, + rsvpCounts, + rsvpStatuses, + setRsvp, + updateEvent, + type NewEvent, + type RsvpCounts, +} from './service.js'; + +const rsvpLabels: Record = { + going: 'Going', + maybe: 'Maybe', + not_going: 'Not going', +}; +const maxReminders = 3; +const defaultNativeDurationMs = 2 * 60 * 60 * 1000; + +export function renderEvent( + event: Event, + counts: RsvpCounts, +): BaseMessageOptions { + const cancelled = event.status === 'cancelled'; + const embed = new EmbedBuilder() + .setTitle(cancelled ? `[Cancelled] ${event.title}` : event.title) + .setColor(cancelled ? 0x80_80_80 : 0x2b_8a_3e) + .addFields( + { + name: 'When', + value: `${discordTime(event.startsAt)} (${discordTime(event.startsAt, 'R')})${ + event.endsAt ? ` – ${discordTime(event.endsAt, 'f')}` : '' + }`, + }, + ...(event.location === null + ? [] + : [{ name: 'Where', value: event.location }]), + { name: 'Organizer', value: `<@${event.organizerId}>`, inline: true }, + { + name: 'Going', + value: + event.capacity === null + ? String(counts.going) + : `${counts.going} / ${event.capacity}`, + inline: true, + }, + { name: 'Maybe', value: String(counts.maybe), inline: true }, + ) + .setFooter({ text: `Event #${event.id}` }); + if (event.description !== null) { + embed.setDescription(event.description); + } + const buttons = rsvpStatuses.map((status) => + new ButtonBuilder() + .setCustomId(customId('events:rsvp', event.id, status)) + .setLabel(rsvpLabels[status]) + .setStyle( + status === 'going' ? ButtonStyle.Success : ButtonStyle.Secondary, + ), + ); + return { + embeds: [embed], + components: cancelled + ? [] + : [new ActionRowBuilder().addComponents(buttons)], + }; +} + +async function refreshMessage(ctx: AppContext, event: Event): Promise { + if (event.messageId === null) { + return; + } + try { + const channel = await ctx.client.channels.fetch(event.channelId); + if (channel?.isTextBased() === true) { + await channel.messages.edit( + event.messageId, + renderEvent(event, await rsvpCounts(ctx.db, event.id)), + ); + } + } catch (error) { + if (!isUnknownObject(error)) { + throw error; + } + ctx.log.warn({ eventId: event.id }, 'Event message or channel was deleted'); + } +} + +const reminderKey = (id: number, minutes: number) => + `event:${id}:remind:${minutes}`; + +export const remindJob = defineJob({ + type: 'events:remind', + payload: z.object({ eventId: z.number().int(), minutes: z.number().int() }), + handle: async ({ eventId, minutes }, _info, ctx) => { + const event = await getEvent(ctx.db, eventId); + // A reminder after the start is pointless, so late ones are dropped. + if ( + event?.status !== 'scheduled' || + event.startsAt.getTime() <= Date.now() + ) { + return; + } + const attendees = await listAttendees(ctx.db, eventId); + const going = attendees + .filter((a) => a.status === 'going') + .slice(0, 90) + .map((a) => a.userId); + const link = + event.messageId === null + ? '' + : ` https://discord.com/channels/${event.guildId}/${event.channelId}/${event.messageId}`; + const pings = going.map((id) => `<@${id}>`).join(' '); + try { + const channel = await ctx.client.channels.fetch(event.channelId); + if (channel?.isSendable() === true) { + await channel.send({ + content: `⏰ **${event.title}** starts ${discordTime(event.startsAt, 'R')} (${minutes} min reminder).${link}\n${pings}`, + allowedMentions: { users: going }, + }); + } + } catch (error) { + throw asJobError(error); + } + }, +}); + +async function scheduleReminders( + ctx: AppContext, + event: Event, + previous: readonly number[] = [], +): Promise { + for (const minutes of previous) { + await ctx.scheduler.cancel(reminderKey(event.id, minutes)); + } + if (event.status !== 'scheduled') { + return; + } + for (const minutes of event.reminderMinutes) { + const runAt = new Date(event.startsAt.getTime() - minutes * 60_000); + if (runAt.getTime() > Date.now()) { + await ctx.scheduler.schedule( + remindJob, + { eventId: event.id, minutes }, + { runAt, key: reminderKey(event.id, minutes) }, + ); + } + } +} + +/** Mirrors the event as a native Discord scheduled event. Failures are not fatal. */ +async function syncNativeEvent( + ctx: AppContext, + event: Event, +): Promise { + try { + const guild = await ctx.client.guilds.fetch(event.guildId); + if (event.status === 'cancelled') { + if (event.discordEventId !== null) { + await guild.scheduledEvents.delete(event.discordEventId); + } + return null; + } + const details = { + name: event.title.slice(0, 100), + scheduledStartTime: event.startsAt, + scheduledEndTime: + event.endsAt ?? + new Date(event.startsAt.getTime() + defaultNativeDurationMs), + description: (event.description ?? '').slice(0, 1000), + entityMetadata: { + location: (event.location ?? 'See the event post').slice(0, 100), + }, + }; + if (event.discordEventId !== null) { + await guild.scheduledEvents.edit(event.discordEventId, details); + return event.discordEventId; + } + const created = await guild.scheduledEvents.create({ + ...details, + privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly, + entityType: GuildScheduledEventEntityType.External, + }); + return created.id; + } catch (error) { + ctx.log.warn( + { err: error, eventId: event.id }, + 'Could not sync native Discord event', + ); + return event.discordEventId; + } +} + +/** + * Public API: creates, publishes and schedules reminders for an event. Movie + * nights and any other feature that needs an event go through this. + */ +export async function createEvent( + ctx: AppContext, + input: NewEvent & { native?: boolean }, +): Promise { + const { native = false, ...values } = input; + const channel = await ctx.client.channels + .fetch(values.channelId) + .catch(() => null); + if (channel?.isSendable() !== true) { + throw new UserError('I cannot post in that channel.'); + } + let event = await insertEvent(ctx.db, values); + const message = await channel.send({ + ...renderEvent(event, { going: 0, maybe: 0, not_going: 0 }), + ...(event.mentionRoleId === null + ? {} + : { + content: `<@&${event.mentionRoleId}>`, + allowedMentions: { roles: [event.mentionRoleId] }, + }), + }); + const discordEventId = native ? await syncNativeEvent(ctx, event) : null; + event = await updateEvent(ctx.db, event.id, { + messageId: message.id, + discordEventId, + }); + await scheduleReminders(ctx, event); + return event; +} + +function parseReminderMinutes(value: string | null): number[] { + if (value === null) { + return [60]; + } + if (value.trim() === '') { + return []; + } + const minutes = value.split(',').map((part) => Number(part.trim())); + if ( + minutes.length > maxReminders || + minutes.some((m) => !Number.isInteger(m) || m < 1 || m > 10_080) + ) { + throw new UserError( + `Reminders are up to ${maxReminders} comma-separated minute values, e.g. "60,15".`, + ); + } + return [...new Set(minutes)]; +} + +async function requireManageable( + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const event = await requireEvent( + ctx.db, + interaction.guildId, + interaction.options.getInteger('id', true), + ); + if (event.organizerId !== interaction.user.id) { + await ctx.authz.require(interaction.member, 'event:manage'); + } + return event; +} + +const rsvpHandler: ComponentHandler = { + prefix: 'events:rsvp', + execute: async (interaction, [id, answer], ctx) => { + const status = rsvpStatuses.find((s) => s === answer); + const eventId = Number(id); + if ( + !interaction.isButton() || + status === undefined || + !Number.isSafeInteger(eventId) + ) { + throw new UserError('This button is invalid.'); + } + await setRsvp(ctx.db, eventId, interaction.user.id, status); + const event = await getEvent(ctx.db, eventId); + if (event) { + await interaction.update( + renderEvent(event, await rsvpCounts(ctx.db, eventId)), + ); + } + await interaction.followUp({ + content: `RSVP saved: **${rsvpLabels[status]}**.`, + flags: MessageFlags.Ephemeral, + }); + }, +}; + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Event') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('event') + .setDescription('Organise events') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Create and publish an event') + .addStringOption((o) => + o + .setName('title') + .setDescription('Title') + .setRequired(true) + .setMaxLength(200), + ) + .addStringOption((o) => + o + .setName('start') + .setDescription('e.g. 2026-11-20 18:00') + .setRequired(true), + ) + .addStringOption((o) => + o + .setName('description') + .setDescription('Description') + .setMaxLength(2000), + ) + .addStringOption((o) => o.setName('end').setDescription('End time')) + .addStringOption((o) => + o.setName('location').setDescription('Place or link').setMaxLength(200), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes( + ChannelType.GuildText, + ChannelType.GuildAnnouncement, + ), + ) + .addIntegerOption((o) => + o + .setName('capacity') + .setDescription('Maximum attendees') + .setMinValue(1) + .setMaxValue(10_000), + ) + .addRoleOption((o) => + o.setName('mention').setDescription('Role to notify'), + ) + .addStringOption((o) => + o + .setName('reminders') + .setDescription('Minutes before start, e.g. "60,15" (default 60)'), + ) + .addStringOption((o) => + o.setName('timezone').setDescription('IANA timezone for the times'), + ) + .addBooleanOption((o) => + o + .setName('native') + .setDescription('Also create a Discord scheduled event'), + ), + ) + .addSubcommand((sub) => + sub + .setName('edit') + .setDescription('Change an event') + .addIntegerOption(idOption) + .addStringOption((o) => + o.setName('title').setDescription('Title').setMaxLength(200), + ) + .addStringOption((o) => o.setName('start').setDescription('Start time')) + .addStringOption((o) => o.setName('end').setDescription('End time')) + .addStringOption((o) => + o + .setName('description') + .setDescription('Description') + .setMaxLength(2000), + ) + .addStringOption((o) => + o.setName('location').setDescription('Place or link').setMaxLength(200), + ) + .addIntegerOption((o) => + o + .setName('capacity') + .setDescription('Maximum attendees') + .setMinValue(1), + ), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel an event') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Upcoming events')) + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('Show an event') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('attendees') + .setDescription('Who is coming') + .addIntegerOption(idOption), + ); + +async function editEvent( + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const event = await requireManageable(interaction, ctx); + if (event.status !== 'scheduled') { + throw new UserError('Cancelled events cannot be edited.'); + } + const option = (name: string) => + interaction.options.getString(name) ?? undefined; + const start = option('start'); + const end = option('end'); + const changes = { + title: option('title') ?? event.title, + description: option('description') ?? event.description, + location: option('location') ?? event.location, + capacity: interaction.options.getInteger('capacity') ?? event.capacity, + startsAt: + start === undefined + ? event.startsAt + : parseFutureWhen(start, event.timezone), + endsAt: end === undefined ? event.endsAt : parseWhen(end, event.timezone), + }; + if (changes.endsAt && changes.endsAt <= changes.startsAt) { + throw new UserError('The end must be after the start.'); + } + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + let updated = await updateEvent(ctx.db, event.id, changes); + if (updated.discordEventId !== null) { + updated = await updateEvent(ctx.db, event.id, { + discordEventId: await syncNativeEvent(ctx, updated), + }); + } + await refreshMessage(ctx, updated); + await scheduleReminders(ctx, updated, event.reminderMinutes); + ctx.log.info( + { eventId: event.id, actorId: interaction.user.id }, + 'Event edited', + ); + await interaction.editReply(`Event #${event.id} updated.`); +} + +export const eventsFeature: Feature = { + name: 'events', + permissions: [ + { id: 'event:create', description: 'Create events' }, + { id: 'event:manage', description: 'Edit and cancel any event' }, + ], + jobs: [remindJob], + components: [rsvpHandler], + commands: [ + { + data: data.toJSON(), + permissions: { create: 'event:create' }, + execute: bySubcommand({ + create: async (interaction, ctx) => { + const zoneOption = interaction.options.getString('timezone'); + const timezone = + zoneOption === null + ? await getGuildTimezone( + ctx.db, + interaction.guildId, + ctx.config.DEFAULT_TIMEZONE, + ) + : requireZone(zoneOption); + const end = interaction.options.getString('end'); + const mention = interaction.options.getRole('mention'); + if ( + mention && + !mention.mentionable && + !interaction.member.permissions.has('MentionEveryone') + ) { + throw new UserError('You may not mention that role.'); + } + const input = { + guildId: interaction.guildId, + title: interaction.options.getString('title', true), + description: interaction.options.getString('description'), + startsAt: parseFutureWhen( + interaction.options.getString('start', true), + timezone, + ), + endsAt: end === null ? null : parseWhen(end, timezone), + timezone, + location: interaction.options.getString('location'), + organizerId: interaction.user.id, + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + capacity: interaction.options.getInteger('capacity'), + mentionRoleId: mention?.id ?? null, + reminderMinutes: parseReminderMinutes( + interaction.options.getString('reminders'), + ), + native: interaction.options.getBoolean('native') ?? false, + }; + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const event = await createEvent(ctx, input); + ctx.log.info( + { eventId: event.id, actorId: interaction.user.id }, + 'Event created', + ); + await interaction.editReply( + `Created event #${event.id} in <#${event.channelId}>.`, + ); + }, + edit: editEvent, + cancel: async (interaction, ctx) => { + const event = await requireManageable(interaction, ctx); + if (event.status === 'cancelled') { + throw new UserError('That event is already cancelled.'); + } + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const cancelled = await updateEvent(ctx.db, event.id, { + status: 'cancelled', + }); + await Promise.all([ + refreshMessage(ctx, cancelled), + scheduleReminders(ctx, cancelled, event.reminderMinutes), + cancelled.discordEventId === null + ? undefined + : syncNativeEvent(ctx, cancelled), + ]); + ctx.log.info( + { eventId: event.id, actorId: interaction.user.id }, + 'Event cancelled', + ); + await interaction.editReply(`Event #${event.id} is cancelled.`); + }, + list: async (interaction, ctx) => { + const upcoming = await listUpcoming(ctx.db, interaction.guildId); + await respond( + interaction, + upcoming.length === 0 + ? 'No upcoming events.' + : upcoming + .map( + (e) => + `#${e.id} **${e.title}** — ${discordTime(e.startsAt, 'f')}`, + ) + .join('\n'), + ); + }, + view: async (interaction, ctx) => { + const event = await requireEvent( + ctx.db, + interaction.guildId, + interaction.options.getInteger('id', true), + ); + const counts = await rsvpCounts(ctx.db, event.id); + await interaction.reply({ + embeds: renderEvent(event, counts).embeds ?? [], + flags: MessageFlags.Ephemeral, + }); + }, + attendees: async (interaction, ctx) => { + const event = await requireEvent( + ctx.db, + interaction.guildId, + interaction.options.getInteger('id', true), + ); + const attendees = await listAttendees(ctx.db, event.id); + const section = (status: RsvpStatus) => { + const ids = attendees + .filter((a) => a.status === status) + .map((a) => `<@${a.userId}>`); + return `**${rsvpLabels[status]} (${ids.length})**\n${ids.join(' ') || '—'}`; + }; + await respond( + interaction, + rsvpStatuses.map(section).join('\n\n').slice(0, 2000), + ); + }, + }), + autocomplete: async (interaction, ctx) => { + const upcoming = await listUpcoming(ctx.db, interaction.guildId); + await interaction.respond( + upcoming.map((e) => ({ + name: `#${e.id} ${e.title}`.slice(0, 100), + value: e.id, + })), + ); + }, + }, + ], +}; diff --git a/src/features/events/schema.ts b/src/features/events/schema.ts new file mode 100644 index 0000000..53bb715 --- /dev/null +++ b/src/features/events/schema.ts @@ -0,0 +1,70 @@ +import { + index, + integer, + pgEnum, + pgTable, + primaryKey, + serial, + text, + timestamp, +} from 'drizzle-orm/pg-core'; + +export const eventStatus = pgEnum('event_status', ['scheduled', 'cancelled']); +export const rsvpStatus = pgEnum('rsvp_status', [ + 'going', + 'maybe', + 'not_going', +]); + +/** + * The bot's events are the source of truth for RSVPs and reminders. A native + * Discord scheduled event, when enabled, is only a mirror of this row. + */ +export const events = pgTable( + 'events', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + title: text('title').notNull(), + description: text('description'), + startsAt: timestamp('starts_at', { withTimezone: true }).notNull(), + endsAt: timestamp('ends_at', { withTimezone: true }), + timezone: text('timezone').notNull(), + location: text('location'), + organizerId: text('organizer_id').notNull(), + channelId: text('channel_id').notNull(), + messageId: text('message_id'), + capacity: integer('capacity'), + mentionRoleId: text('mention_role_id'), + reminderMinutes: integer('reminder_minutes').array().notNull().default([]), + discordEventId: text('discord_event_id'), + status: eventStatus('status').notNull().default('scheduled'), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + index('events_guild_start_idx').on(table.guildId, table.startsAt), + ], +); + +export const eventRsvps = pgTable( + 'event_rsvps', + { + eventId: integer('event_id') + .notNull() + .references(() => events.id, { onDelete: 'cascade' }), + userId: text('user_id').notNull(), + status: rsvpStatus('status').notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + primaryKey({ columns: [table.eventId, table.userId] }), + index('event_rsvps_status_idx').on(table.eventId, table.status), + ], +); + +export type Event = typeof events.$inferSelect; +export type RsvpStatus = (typeof rsvpStatus.enumValues)[number]; diff --git a/src/features/events/service.ts b/src/features/events/service.ts new file mode 100644 index 0000000..cea4ad3 --- /dev/null +++ b/src/features/events/service.ts @@ -0,0 +1,164 @@ +import { and, asc, count, eq, gte, ne } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import { + eventRsvps, + events, + rsvpStatus, + type Event, + type RsvpStatus, +} from './schema.js'; + +export type NewEvent = Omit< + typeof events.$inferInsert, + 'id' | 'messageId' | 'discordEventId' | 'status' | 'createdAt' +>; + +export type RsvpCounts = Record; + +export const rsvpStatuses = rsvpStatus.enumValues; + +export async function insertEvent(db: Db, input: NewEvent): Promise { + if (input.endsAt && input.endsAt <= input.startsAt) { + throw new UserError('The end must be after the start.'); + } + if ( + input.capacity !== undefined && + input.capacity !== null && + input.capacity < 1 + ) { + throw new UserError('Capacity must be at least 1.'); + } + const [row] = await db.insert(events).values(input).returning(); + if (!row) { + throw new Error('Insert returned no row'); + } + return row; +} + +export async function getEvent(db: Db, id: number): Promise { + const [row] = await db.select().from(events).where(eq(events.id, id)); + return row; +} + +export async function requireEvent( + db: Db, + guildId: string, + id: number, +): Promise { + const event = await getEvent(db, id); + if (event?.guildId !== guildId) { + throw new UserError(`Event #${id} does not exist.`); + } + return event; +} + +export async function listUpcoming( + db: Db, + guildId: string, + limit = 25, +): Promise { + return db + .select() + .from(events) + .where( + and( + eq(events.guildId, guildId), + eq(events.status, 'scheduled'), + gte(events.startsAt, new Date()), + ), + ) + .orderBy(asc(events.startsAt)) + .limit(limit); +} + +export async function updateEvent( + db: Db, + id: number, + changes: Partial>, +): Promise { + const [row] = await db + .update(events) + .set(changes) + .where(eq(events.id, id)) + .returning(); + if (!row) { + throw new UserError(`Event #${id} does not exist.`); + } + return row; +} + +export async function rsvpCounts(db: Db, eventId: number): Promise { + const rows = await db + .select({ status: eventRsvps.status, total: count() }) + .from(eventRsvps) + .where(eq(eventRsvps.eventId, eventId)) + .groupBy(eventRsvps.status); + const counts: RsvpCounts = { going: 0, maybe: 0, not_going: 0 }; + for (const row of rows) { + counts[row.status] = row.total; + } + return counts; +} + +/** + * Records or changes a member's RSVP. The event row is locked so that + * concurrent "going" responses can never exceed the capacity. + */ +export async function setRsvp( + db: Db, + eventId: number, + userId: string, + status: RsvpStatus, +): Promise { + await db.transaction(async (tx) => { + const [event] = await tx + .select({ + status: events.status, + capacity: events.capacity, + startsAt: events.startsAt, + }) + .from(events) + .where(eq(events.id, eventId)) + .for('update'); + if (event?.status !== 'scheduled') { + throw new UserError('This event is no longer open for RSVPs.'); + } + if (status === 'going' && event.capacity !== null) { + const [others] = await tx + .select({ total: count() }) + .from(eventRsvps) + .where( + and( + eq(eventRsvps.eventId, eventId), + eq(eventRsvps.status, 'going'), + ne(eventRsvps.userId, userId), + ), + ); + if ((others?.total ?? 0) >= event.capacity) { + throw new UserError( + 'This event is full. You can still answer "Maybe".', + ); + } + } + await tx + .insert(eventRsvps) + .values({ eventId, userId, status }) + .onConflictDoUpdate({ + target: [eventRsvps.eventId, eventRsvps.userId], + set: { status, updatedAt: new Date() }, + }); + }); +} + +export async function listAttendees( + db: Db, + eventId: number, +): Promise> { + return db + .select({ userId: eventRsvps.userId, status: eventRsvps.status }) + .from(eventRsvps) + .where(eq(eventRsvps.eventId, eventId)) + .orderBy(asc(eventRsvps.updatedAt)) + .limit(1000); +} From 061aa8eaab965e4940ca561712d2af44c1a9a8eb Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 009/199] feat(birthdays): birthday announcements and temporary role --- src/features/birthdays/birthdays.test.ts | 204 +++++++++++++ src/features/birthdays/index.ts | 364 +++++++++++++++++++++++ src/features/birthdays/schema.ts | 45 +++ src/features/birthdays/service.ts | 178 +++++++++++ 4 files changed, 791 insertions(+) create mode 100644 src/features/birthdays/birthdays.test.ts create mode 100644 src/features/birthdays/index.ts create mode 100644 src/features/birthdays/schema.ts create mode 100644 src/features/birthdays/service.ts diff --git a/src/features/birthdays/birthdays.test.ts b/src/features/birthdays/birthdays.test.ts new file mode 100644 index 0000000..df63bb6 --- /dev/null +++ b/src/features/birthdays/birthdays.test.ts @@ -0,0 +1,204 @@ +import { DateTime } from 'luxon'; +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { nextDailyRun } from '../../shared/time.js'; +import { dailyJob } from './index.js'; +import { + celebratedOn, + claimTodaysBirthdays, + releaseClaims, + saveSettings, + setBirthday, + upcomingBirthdays, + validateDate, +} from './service.js'; + +describe('birthday dates', () => { + it('accepts 29 February and rejects impossible dates', () => { + expect(() => validateDate(2, 29)).not.toThrow(); + expect(() => validateDate(2, 30)).toThrow('valid date'); + expect(() => validateDate(4, 31)).toThrow('valid date'); + }); + + it('celebrates leap-day birthdays on 28 February in non-leap years', () => { + expect(celebratedOn(DateTime.local(2027, 2, 28))).toEqual([ + { month: 2, day: 28 }, + { month: 2, day: 29 }, + ]); + expect(celebratedOn(DateTime.local(2028, 2, 28))).toEqual([ + { month: 2, day: 28 }, + ]); + expect(celebratedOn(DateTime.local(2028, 2, 29))).toEqual([ + { month: 2, day: 29 }, + ]); + }); + + it('computes the next announcement hour in the guild timezone', () => { + const now = DateTime.fromISO('2026-06-01T10:00:00Z') as DateTime; + expect(nextDailyRun('Europe/Tallinn', 9, now).toISOString()).toBe( + '2026-06-02T06:00:00.000Z', + ); + expect(nextDailyRun('Europe/Tallinn', 15, now).toISOString()).toBe( + '2026-06-01T12:00:00.000Z', + ); + }); +}); + +describe.skipIf(noDatabase)('birthday announcements', () => { + const today = DateTime.local(2027, 2, 28); + + it('announces each birthday once per year and respects privacy', async () => { + const db = testDb(); + const guildId = snowflake(); + const [pub, announce, priv, leap, other] = [ + snowflake(), + snowflake(), + snowflake(), + snowflake(), + snowflake(), + ]; + await setBirthday(db, { + guildId, + userId: pub, + month: 2, + day: 28, + visibility: 'public', + }); + await setBirthday(db, { + guildId, + userId: announce, + month: 2, + day: 28, + visibility: 'announce', + }); + await setBirthday(db, { + guildId, + userId: priv, + month: 2, + day: 28, + visibility: 'private', + }); + await setBirthday(db, { + guildId, + userId: leap, + month: 2, + day: 29, + visibility: 'public', + }); + await setBirthday(db, { + guildId, + userId: other, + month: 3, + day: 1, + visibility: 'public', + }); + + const claimed = await claimTodaysBirthdays(db, guildId, today); + expect(claimed).toHaveLength(3); + expect(claimed).toEqual(expect.arrayContaining([pub, announce, leap])); + expect(await claimTodaysBirthdays(db, guildId, today)).toEqual([]); + expect( + await claimTodaysBirthdays(db, guildId, today.plus({ years: 1 })), + ).toHaveLength(2); + }); + + it('can release a claim after a failed post', async () => { + const db = testDb(); + const guildId = snowflake(); + const user = snowflake(); + await setBirthday(db, { + guildId, + userId: user, + month: 2, + day: 28, + visibility: 'public', + }); + await claimTodaysBirthdays(db, guildId, today); + await releaseClaims(db, guildId, [user], today.year); + expect(await claimTodaysBirthdays(db, guildId, today)).toEqual([user]); + }); + + it('lists only public birthdays, starting from today', async () => { + const db = testDb(); + const guildId = snowflake(); + const [jan, jun, dec, hidden] = [ + snowflake(), + snowflake(), + snowflake(), + snowflake(), + ]; + await setBirthday(db, { + guildId, + userId: jan, + month: 1, + day: 5, + visibility: 'public', + }); + await setBirthday(db, { + guildId, + userId: jun, + month: 6, + day: 5, + visibility: 'public', + }); + await setBirthday(db, { + guildId, + userId: dec, + month: 12, + day: 5, + visibility: 'public', + }); + await setBirthday(db, { + guildId, + userId: hidden, + month: 6, + day: 6, + visibility: 'announce', + }); + const list = await upcomingBirthdays( + db, + guildId, + DateTime.local(2026, 6, 1), + ); + expect(list.map((b) => b.userId)).toEqual([jun, dec, jan]); + }); + + it('posts one message and reschedules for the next day', async () => { + const db = testDb(); + const guildId = snowflake(); + const user = snowflake(); + const now = DateTime.now().setZone('Europe/Tallinn'); + await setBirthday(db, { + guildId, + userId: user, + month: now.month, + day: now.day, + visibility: 'public', + }); + await saveSettings(db, { + guildId, + channelId: snowflake(), + roleId: null, + hour: 9, + }); + const send = vi.fn(async () => undefined); + const ctx = { + db, + log: pino({ level: 'silent' }), + config: { DEFAULT_TIMEZONE: 'Europe/Tallinn' }, + client: { + channels: { fetch: async () => ({ isSendable: () => true, send }) }, + }, + } as unknown as AppContext; + const info = { id: 1, runAt: new Date(), attempt: 1 }; + const outcome = await dailyJob.run({ guildId }, info, ctx); + await dailyJob.run({ guildId }, info, ctx); + expect(send).toHaveBeenCalledOnce(); + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ allowedMentions: { users: [user] } }), + ); + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); + }); +}); diff --git a/src/features/birthdays/index.ts b/src/features/birthdays/index.ts new file mode 100644 index 0000000..a78217c --- /dev/null +++ b/src/features/birthdays/index.ts @@ -0,0 +1,364 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, + channelMention, + roleMention, + userMention, +} from 'discord.js'; +import { DateTime } from 'luxon'; +import { z } from 'zod'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, defineJob } from '../../core/define.js'; +import { isPermanentDiscordError } from '../../core/discord/errors.js'; +import type { + AppContext, + CommandInteraction, + Feature, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { UserError } from '../../shared/errors.js'; +import { nextDailyRun } from '../../shared/time.js'; +import { + birthdayVisibility, + type Birthday, + type BirthdayVisibility, +} from './schema.js'; +import { + claimTodaysBirthdays, + deleteSettings, + getBirthday, + getSettings, + releaseClaims, + removeBirthday, + saveSettings, + setBirthday, + upcomingBirthdays, +} from './service.js'; + +const dailyKey = (guildId: string) => `birthdays:${guildId}`; +const visibilities = birthdayVisibility.enumValues; + +const removeRoleJob = defineJob({ + type: 'birthdays:remove-role', + payload: z.object({ + guildId: z.string(), + userId: z.string(), + roleId: z.string(), + }), + handle: async ({ guildId, userId, roleId }, _info, ctx) => { + try { + const guild = await ctx.client.guilds.fetch(guildId); + const member = await guild.members.fetch(userId); + await member.roles.remove(roleId, 'Birthday is over'); + } catch (error) { + // A member who left, or a deleted role, needs no cleanup. + if (!isPermanentDiscordError(error)) { + throw error; + } + } + }, +}); + +async function giveRole( + ctx: AppContext, + guildId: string, + roleId: string, + userIds: string[], + zone: string, +) { + const guild = await ctx.client.guilds.fetch(guildId); + const midnight = DateTime.now() + .setZone(zone) + .plus({ days: 1 }) + .startOf('day') + .toJSDate(); + for (const userId of userIds) { + try { + const member = await guild.members.fetch(userId); + await member.roles.add(roleId, 'Birthday'); + await ctx.scheduler.schedule( + removeRoleJob, + { guildId, userId, roleId }, + { + runAt: midnight, + key: `birthday-role:${guildId}:${userId}`, + }, + ); + } catch (error) { + ctx.log.warn({ err: error, userId }, 'Could not give birthday role'); + } + } +} + +export const dailyJob = defineJob({ + type: 'birthdays:daily', + payload: z.object({ guildId: z.string() }), + // When the bot was down at the usual hour, today's birthdays are still + // announced on recovery; birthdays on days fully missed are not. + handle: async ({ guildId }, _info, ctx) => { + const settings = await getSettings(ctx.db, guildId); + if (!settings) { + return null; + } + const zone = await getGuildTimezone( + ctx.db, + guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + const today = DateTime.now().setZone(zone); + const userIds = await claimTodaysBirthdays(ctx.db, guildId, today); + if (userIds.length > 0) { + try { + const channel = await ctx.client.channels.fetch(settings.channelId); + if (channel?.isSendable() !== true) { + throw new UserError('Birthday channel is not available'); + } + await channel.send({ + content: `🎉 Palju õnne! Happy birthday ${userIds.map((id) => userMention(id)).join(', ')}!`, + allowedMentions: { users: userIds }, + }); + } catch (error) { + if (!isPermanentDiscordError(error) && !(error instanceof UserError)) { + await releaseClaims(ctx.db, guildId, userIds, today.year); + throw error; + } + ctx.log.error( + { err: error, guildId }, + 'Birthday channel is unusable; skipping today', + ); + } + if (settings.roleId !== null) { + await giveRole(ctx, guildId, settings.roleId, userIds, zone); + } + } + return { rescheduleAt: nextDailyRun(zone, settings.hour) }; + }, +}); + +function describe(birthday: Birthday): string { + const date = DateTime.local(2024, birthday.month, birthday.day).toFormat( + 'd LLLL', + ); + return `<@${birthday.userId}> — ${date}`; +} + +const data = new SlashCommandBuilder() + .setName('birthday') + .setDescription('Birthdays') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('set') + .setDescription('Save your birthday (no year needed)') + .addIntegerOption((o) => + o + .setName('day') + .setDescription('Day') + .setRequired(true) + .setMinValue(1) + .setMaxValue(31), + ) + .addIntegerOption((o) => + o + .setName('month') + .setDescription('Month') + .setRequired(true) + .setMinValue(1) + .setMaxValue(12), + ) + .addStringOption((o) => + o + .setName('visibility') + .setDescription( + 'public: announced and listed; announce: announced only; private: neither', + ) + .addChoices(visibilities.map((v) => ({ name: v, value: v }))), + ), + ) + .addSubcommand((sub) => + sub.setName('remove').setDescription('Delete your birthday data'), + ) + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('See a birthday') + .addUserOption((o) => + o.setName('member').setDescription('Member (default: you)'), + ), + ) + .addSubcommand((sub) => + sub.setName('upcoming').setDescription('Upcoming public birthdays'), + ) + .addSubcommand((sub) => + sub + .setName('settings') + .setDescription('Configure birthday announcements') + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Announcement channel') + .addChannelTypes(ChannelType.GuildText), + ) + .addRoleOption((o) => + o.setName('role').setDescription('Role to give for the day'), + ) + .addIntegerOption((o) => + o + .setName('hour') + .setDescription('Hour to announce (server time)') + .setMinValue(0) + .setMaxValue(23), + ) + .addBooleanOption((o) => + o.setName('disable').setDescription('Turn announcements off'), + ), + ); + +async function readSettings( + interaction: CommandInteraction, + ctx: AppContext, +): Promise<{ + guildId: string; + channelId: string; + roleId: string | null; + hour: number; +}> { + const current = await getSettings(ctx.db, interaction.guildId); + const channelId = + interaction.options.getChannel('channel')?.id ?? current?.channelId; + if (channelId === undefined) { + throw new UserError('Choose an announcement channel.'); + } + const role = interaction.options.getRole('role'); + if (role && (role.managed || !role.editable)) { + throw new UserError(`I cannot manage ${role.name}.`); + } + return { + guildId: interaction.guildId, + channelId, + roleId: role?.id ?? current?.roleId ?? null, + hour: interaction.options.getInteger('hour') ?? current?.hour ?? 9, + }; +} + +async function configure( + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const guildId = interaction.guildId; + if (interaction.options.getBoolean('disable') === true) { + await deleteSettings(ctx.db, guildId); + await ctx.scheduler.cancel(dailyKey(guildId)); + await respond(interaction, 'Birthday announcements are off.'); + return; + } + const settings = await readSettings(interaction, ctx); + await saveSettings(ctx.db, settings); + const zone = await getGuildTimezone( + ctx.db, + guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + await ctx.scheduler.schedule( + dailyJob, + { guildId }, + { runAt: nextDailyRun(zone, settings.hour), key: dailyKey(guildId) }, + ); + ctx.log.info( + { guildId, actorId: interaction.user.id, settings }, + 'Birthday settings changed', + ); + const role = + settings.roleId === null + ? '' + : ` with ${roleMention(settings.roleId)} for the day`; + await respond( + interaction, + `Birthdays are announced in ${channelMention(settings.channelId)} at ${settings.hour}:00 (${zone})${role}.`, + ); +} + +export const birthdaysFeature: Feature = { + name: 'birthdays', + permissions: [ + { id: 'birthday:manage', description: 'Configure birthday announcements' }, + ], + jobs: [dailyJob, removeRoleJob], + commands: [ + { + data: data.toJSON(), + permissions: { settings: 'birthday:manage' }, + execute: bySubcommand({ + set: async (interaction, ctx) => { + const visibility: BirthdayVisibility = + visibilities.find( + (v) => v === interaction.options.getString('visibility'), + ) ?? 'public'; + await setBirthday(ctx.db, { + guildId: interaction.guildId, + userId: interaction.user.id, + day: interaction.options.getInteger('day', true), + month: interaction.options.getInteger('month', true), + visibility, + }); + const leap = + interaction.options.getInteger('month', true) === 2 && + interaction.options.getInteger('day', true) === 29 + ? ' In non-leap years it is celebrated on 28 February.' + : ''; + await respond(interaction, `Saved (${visibility}).${leap}`); + }, + remove: async (interaction, ctx) => { + const removed = await removeBirthday( + ctx.db, + interaction.guildId, + interaction.user.id, + ); + await respond( + interaction, + removed + ? 'Your birthday data is deleted.' + : 'You had no birthday saved.', + ); + }, + view: async (interaction, ctx) => { + const user = + interaction.options.getUser('member') ?? interaction.user; + const birthday = await getBirthday( + ctx.db, + interaction.guildId, + user.id, + ); + const visible = + birthday && + (user.id === interaction.user.id || + birthday.visibility === 'public'); + await respond( + interaction, + visible === true ? describe(birthday) : 'No birthday to show.', + ); + }, + upcoming: async (interaction, ctx) => { + const zone = await getGuildTimezone( + ctx.db, + interaction.guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + const list = await upcomingBirthdays( + ctx.db, + interaction.guildId, + DateTime.now().setZone(zone), + ); + await respond( + interaction, + list.length === 0 + ? 'No public birthdays yet.' + : list.map(describe).join('\n'), + ); + }, + settings: configure, + }), + }, + ], +}; diff --git a/src/features/birthdays/schema.ts b/src/features/birthdays/schema.ts new file mode 100644 index 0000000..d17b09b --- /dev/null +++ b/src/features/birthdays/schema.ts @@ -0,0 +1,45 @@ +import { + index, + integer, + pgEnum, + pgTable, + primaryKey, + smallint, + text, +} from 'drizzle-orm/pg-core'; + +/** + * public: announced and listed. announce: announced but never listed. + * private: stored for the member only; never announced or shown to others. + */ +export const birthdayVisibility = pgEnum('birthday_visibility', [ + 'public', + 'announce', + 'private', +]); + +export const birthdays = pgTable( + 'birthdays', + { + guildId: text('guild_id').notNull(), + userId: text('user_id').notNull(), + month: smallint('month').notNull(), + day: smallint('day').notNull(), + visibility: birthdayVisibility('visibility').notNull().default('public'), + lastAnnouncedYear: integer('last_announced_year'), + }, + (table) => [ + primaryKey({ columns: [table.guildId, table.userId] }), + index('birthdays_date_idx').on(table.guildId, table.month, table.day), + ], +); + +export const birthdaySettings = pgTable('birthday_settings', { + guildId: text('guild_id').primaryKey(), + channelId: text('channel_id').notNull(), + roleId: text('role_id'), + hour: smallint('hour').notNull().default(9), +}); + +export type Birthday = typeof birthdays.$inferSelect; +export type BirthdayVisibility = Birthday['visibility']; diff --git a/src/features/birthdays/service.ts b/src/features/birthdays/service.ts new file mode 100644 index 0000000..3df54cf --- /dev/null +++ b/src/features/birthdays/service.ts @@ -0,0 +1,178 @@ +import { and, eq, inArray, isNull, lt, ne, or, sql } from 'drizzle-orm'; +import { DateTime } from 'luxon'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import { + birthdays, + birthdaySettings, + type Birthday, + type BirthdayVisibility, +} from './schema.js'; + +export function validateDate(month: number, day: number): void { + // 2024 is a leap year, so 29 February is accepted. + if (!DateTime.local(2024, month, day).isValid) { + throw new UserError('That is not a valid date.'); + } +} + +/** + * The (month, day) pairs celebrated on a date. 29 February birthdays are + * celebrated on 28 February in non-leap years. + */ +export function celebratedOn( + date: DateTime, +): Array<{ month: number; day: number }> { + const dates = [{ month: date.month, day: date.day }]; + if (date.month === 2 && date.day === 28 && !date.isInLeapYear) { + dates.push({ month: 2, day: 29 }); + } + return dates; +} + +export async function setBirthday( + db: Db, + input: { + guildId: string; + userId: string; + month: number; + day: number; + visibility: BirthdayVisibility; + }, +): Promise { + validateDate(input.month, input.day); + await db + .insert(birthdays) + .values(input) + .onConflictDoUpdate({ + target: [birthdays.guildId, birthdays.userId], + set: { month: input.month, day: input.day, visibility: input.visibility }, + }); +} + +export async function removeBirthday( + db: Db, + guildId: string, + userId: string, +): Promise { + const rows = await db + .delete(birthdays) + .where(and(eq(birthdays.guildId, guildId), eq(birthdays.userId, userId))) + .returning({ userId: birthdays.userId }); + return rows.length > 0; +} + +export async function getBirthday( + db: Db, + guildId: string, + userId: string, +): Promise { + const [row] = await db + .select() + .from(birthdays) + .where(and(eq(birthdays.guildId, guildId), eq(birthdays.userId, userId))); + return row; +} + +/** Public birthdays ordered from `today` onward, wrapping around the year. */ +export async function upcomingBirthdays( + db: Db, + guildId: string, + today: DateTime, + limit = 10, +): Promise { + const rows = await db + .select() + .from(birthdays) + .where( + and(eq(birthdays.guildId, guildId), eq(birthdays.visibility, 'public')), + ) + .limit(2000); + const key = (b: { month: number; day: number }) => b.month * 100 + b.day; + const start = key(today); + return rows + .toSorted((a, b) => { + const ka = (key(a) - start + 1300) % 1300; + const kb = (key(b) - start + 1300) % 1300; + return ka - kb; + }) + .slice(0, limit); +} + +/** + * Claims today's birthdays for announcement by stamping the year. Only rows + * not yet stamped are returned, so a rerun on the same day announces nobody. + */ +export async function claimTodaysBirthdays( + db: Db, + guildId: string, + today: DateTime, +): Promise { + const dates = celebratedOn(today); + const rows = await db + .update(birthdays) + .set({ lastAnnouncedYear: today.year }) + .where( + and( + eq(birthdays.guildId, guildId), + ne(birthdays.visibility, 'private'), + or( + ...dates.map((d) => + and(eq(birthdays.month, d.month), eq(birthdays.day, d.day)), + ), + ), + or( + isNull(birthdays.lastAnnouncedYear), + lt(birthdays.lastAnnouncedYear, today.year), + ), + ), + ) + .returning({ userId: birthdays.userId }); + return rows.map((row) => row.userId); +} + +/** Undoes a claim when the announcement could not be posted, so a retry can. */ +export async function releaseClaims( + db: Db, + guildId: string, + userIds: string[], + year: number, +): Promise { + if (userIds.length === 0) { + return; + } + await db + .update(birthdays) + .set({ lastAnnouncedYear: sql`${year} - 1` }) + .where( + and( + eq(birthdays.guildId, guildId), + inArray(birthdays.userId, userIds), + eq(birthdays.lastAnnouncedYear, year), + ), + ); +} + +export async function getSettings(db: Db, guildId: string) { + const [row] = await db + .select() + .from(birthdaySettings) + .where(eq(birthdaySettings.guildId, guildId)); + return row; +} + +export async function saveSettings( + db: Db, + settings: typeof birthdaySettings.$inferInsert, +): Promise { + await db + .insert(birthdaySettings) + .values(settings) + .onConflictDoUpdate({ target: birthdaySettings.guildId, set: settings }); +} + +export async function deleteSettings(db: Db, guildId: string): Promise { + await db + .delete(birthdaySettings) + .where(eq(birthdaySettings.guildId, guildId)); +} From 780f424f0a6d8eb8c67656c0df7c9564603f3ee8 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 010/199] feat(polls): persistent single and multiple choice polls --- src/features/polls/index.ts | 456 +++++++++++++++++++++++++++++++ src/features/polls/polls.test.ts | 145 ++++++++++ src/features/polls/schema.ts | 88 ++++++ src/features/polls/service.ts | 274 +++++++++++++++++++ 4 files changed, 963 insertions(+) create mode 100644 src/features/polls/index.ts create mode 100644 src/features/polls/polls.test.ts create mode 100644 src/features/polls/schema.ts create mode 100644 src/features/polls/service.ts diff --git a/src/features/polls/index.ts b/src/features/polls/index.ts new file mode 100644 index 0000000..8343464 --- /dev/null +++ b/src/features/polls/index.ts @@ -0,0 +1,456 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ChannelType, + EmbedBuilder, + InteractionContextType, + MessageFlags, + SlashCommandBuilder, + StringSelectMenuBuilder, + userMention, + type BaseMessageOptions, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { z } from 'zod'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, defineJob } from '../../core/define.js'; +import { isUnknownObject } from '../../core/discord/errors.js'; +import type { + AppContext, + CommandInteraction, + ComponentHandler, + Feature, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { customId } from '../../core/registry.js'; +import { UserError } from '../../shared/errors.js'; +import { discordTime, parseFutureWhen } from '../../shared/time.js'; +import type { Poll } from './schema.js'; +import { + castVote, + finishPoll, + getPoll, + getResults, + getVoterChoices, + getVoters, + insertPoll, + isOpen, + listOpenPolls, + requirePoll, + setPollMessage, + type NewPoll, + type PollResults, + type PollWithOptions, +} from './service.js'; + +export type { PollResults, PollWithOptions } from './service.js'; +export { getResults, latestPollBySource } from './service.js'; + +const closeKey = (id: number) => `poll:${id}:close`; + +function bar(votes: number, total: number): string { + const filled = total === 0 ? 0 : Math.round((votes / total) * 10); + return '█'.repeat(filled) + '░'.repeat(10 - filled); +} + +function describeOutcome(results: PollResults, leader: string): string { + const label = results.tie ? 'Tie' : leader; + return `**${label}:** ${results.winners.map((w) => w.label).join(', ')}`; +} + +export function renderPoll( + poll: PollWithOptions, + results: PollResults, +): BaseMessageOptions { + const open = isOpen(poll); + const showCounts = poll.showResults === 'live' || !open; + const lines = results.options.map((option) => + showCounts + ? `**${option.label}**\n${bar(option.votes, results.voters)} ${option.votes}` + : `• ${option.label}`, + ); + let status = poll.status === 'cancelled' ? 'Cancelled' : 'Closed'; + if (open) { + status = + poll.closesAt === null + ? 'Open' + : `Closes ${discordTime(poll.closesAt, 'R')}`; + } + const outcome = + !open && results.winners.length > 0 + ? `\n\n${describeOutcome(results, 'Winner')}` + : ''; + const embed = new EmbedBuilder() + .setTitle(poll.question) + .setDescription(`${lines.join('\n')}${outcome}`) + .setFooter({ + text: [ + `Poll #${poll.id}`, + poll.multiple ? 'multiple choice' : 'single choice', + poll.anonymous ? 'anonymous' : 'votes visible to organizers', + `${results.voters} voter${results.voters === 1 ? '' : 's'}`, + status, + ].join(' · '), + }); + if (!open) { + return { embeds: [embed], components: [] }; + } + const select = new StringSelectMenuBuilder() + .setCustomId(customId('polls:vote', poll.id)) + .setPlaceholder(poll.multiple ? 'Choose one or more' : 'Choose one') + .setMinValues(1) + .setMaxValues(poll.multiple ? poll.options.length : 1) + .addOptions( + poll.options.map((option) => ({ + label: option.label, + value: String(option.id), + })), + ); + const clear = new ButtonBuilder() + .setCustomId(customId('polls:clear', poll.id)) + .setLabel('Clear my vote') + .setStyle(ButtonStyle.Secondary); + return { + embeds: [embed], + components: [ + new ActionRowBuilder().addComponents(select), + new ActionRowBuilder().addComponents(clear), + ], + }; +} + +async function refreshMessage(ctx: AppContext, poll: Poll): Promise { + const full = await getPoll(ctx.db, poll.id); + if (full?.messageId === null || full?.messageId === undefined) { + return; + } + try { + const channel = await ctx.client.channels.fetch(full.channelId); + if (channel?.isTextBased() === true) { + await channel.messages.edit( + full.messageId, + renderPoll(full, await getResults(ctx.db, full)), + ); + } + } catch (error) { + if (!isUnknownObject(error)) { + throw error; + } + ctx.log.warn({ pollId: poll.id }, 'Poll message or channel was deleted'); + } +} + +export const closeJob = defineJob({ + type: 'polls:close', + payload: z.object({ pollId: z.number().int() }), + // Polls are closed even when the job runs late; only the message is updated. + handle: async ({ pollId }, _info, ctx) => { + const closed = await finishPoll(ctx.db, pollId, 'closed'); + if (closed) { + await refreshMessage(ctx, closed); + } + }, +}); + +/** Public API: publishes a poll and schedules its closing. */ +export async function createPoll( + ctx: AppContext, + input: NewPoll, +): Promise { + const channel = await ctx.client.channels + .fetch(input.channelId) + .catch(() => null); + if (channel?.isSendable() !== true) { + throw new UserError('I cannot post in that channel.'); + } + const poll = await insertPoll(ctx.db, input); + const message = await channel.send( + renderPoll(poll, await getResults(ctx.db, poll)), + ); + await setPollMessage(ctx.db, poll.id, message.id); + if (poll.closesAt !== null) { + await ctx.scheduler.schedule( + closeJob, + { pollId: poll.id }, + { runAt: poll.closesAt, key: closeKey(poll.id) }, + ); + } + return { ...poll, messageId: message.id }; +} + +/** Public API: closes a poll now. Returns false if it was not open. */ +export async function closePoll( + ctx: AppContext, + pollId: number, +): Promise { + const closed = await finishPoll(ctx.db, pollId, 'closed'); + if (!closed) { + return false; + } + await ctx.scheduler.cancel(closeKey(pollId)); + await refreshMessage(ctx, closed); + return true; +} + +async function vote( + interaction: Parameters[0], + pollId: number, + optionIds: number[], + ctx: AppContext, +): Promise { + await castVote(ctx.db, pollId, interaction.user.id, optionIds); + const poll = await getPoll(ctx.db, pollId); + if (!poll || interaction.isModalSubmit()) { + return; + } + const results = await getResults(ctx.db, poll); + await interaction.update(renderPoll(poll, results)); + const chosen = poll.options + .filter((o) => optionIds.includes(o.id)) + .map((o) => o.label); + await interaction.followUp({ + content: + chosen.length === 0 + ? 'Your vote is cleared.' + : `Your vote: **${chosen.join(', ')}**`, + flags: MessageFlags.Ephemeral, + }); +} + +function parseId(value: string | undefined): number { + const id = Number(value); + if (!Number.isSafeInteger(id)) { + throw new UserError('This poll control is invalid.'); + } + return id; +} + +const voteHandler: ComponentHandler = { + prefix: 'polls:vote', + execute: async (interaction, [id], ctx) => { + if (!interaction.isStringSelectMenu()) { + return; + } + await vote(interaction, parseId(id), interaction.values.map(Number), ctx); + }, +}; + +const clearHandler: ComponentHandler = { + prefix: 'polls:clear', + execute: async (interaction, [id], ctx) => { + const pollId = parseId(id); + const current = await getVoterChoices(ctx.db, pollId, interaction.user.id); + if (current.length === 0) { + throw new UserError('You have not voted.'); + } + await vote(interaction, pollId, [], ctx); + }, +}; + +async function requireManageable( + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const poll = await requirePoll( + ctx.db, + interaction.guildId, + interaction.options.getInteger('id', true), + ); + if (poll.creatorId !== interaction.user.id) { + await ctx.authz.require(interaction.member, 'poll:manage'); + } + return poll; +} + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Poll') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('poll') + .setDescription('Polls') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Start a poll') + .addStringOption((o) => + o + .setName('question') + .setDescription('Question') + .setRequired(true) + .setMaxLength(256), + ) + .addStringOption((o) => + o + .setName('options') + .setDescription('Options separated by | e.g. "Pizza | Sushi | Tacos"') + .setRequired(true), + ) + .addBooleanOption((o) => + o.setName('multiple').setDescription('Allow several choices'), + ) + .addBooleanOption((o) => + o.setName('anonymous').setDescription('Hide who voted for what'), + ) + .addStringOption((o) => + o + .setName('results') + .setDescription('When results are visible') + .addChoices( + { name: 'live', value: 'live' }, + { name: 'after closing', value: 'closed' }, + ), + ) + .addStringOption((o) => + o.setName('closes').setDescription('e.g. 1d, 2h, 2026-11-20 18:00'), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Open polls')) + .addSubcommand((sub) => + sub + .setName('results') + .setDescription('Show results') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('close') + .setDescription('Close a poll now') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel a poll') + .addIntegerOption(idOption), + ); + +async function showResults( + interaction: CommandInteraction, + ctx: AppContext, +): Promise { + const poll = await requirePoll( + ctx.db, + interaction.guildId, + interaction.options.getInteger('id', true), + ); + const manager = + poll.creatorId === interaction.user.id || + (await ctx.authz.can(interaction.member, 'poll:manage')); + if (poll.showResults === 'closed' && isOpen(poll) && !manager) { + throw new UserError('Results are shown when the poll closes.'); + } + const results = await getResults(ctx.db, poll); + const voters = + !poll.anonymous && manager ? await getVoters(ctx.db, poll.id) : undefined; + const lines = results.options.map((option) => { + const names = voters?.get(option.id)?.map((id) => userMention(id)) ?? []; + return [`**${option.label}** — ${option.votes}`, ...names].join(' '); + }); + const winner = + results.winners.length === 0 + ? 'No votes yet.' + : describeOutcome(results, 'Leading'); + await respond( + interaction, + [`**${poll.question}**`, ...lines, winner].join('\n').slice(0, 2000), + ); +} + +export const pollsFeature: Feature = { + name: 'polls', + permissions: [ + { id: 'poll:create', description: 'Start polls' }, + { id: 'poll:manage', description: 'Close and cancel any poll, see voters' }, + ], + jobs: [closeJob], + components: [voteHandler, clearHandler], + commands: [ + { + data: data.toJSON(), + permissions: { create: 'poll:create' }, + execute: bySubcommand({ + create: async (interaction, ctx) => { + const closes = interaction.options.getString('closes'); + const zone = await getGuildTimezone( + ctx.db, + interaction.guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const poll = await createPoll(ctx, { + guildId: interaction.guildId, + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + creatorId: interaction.user.id, + question: interaction.options.getString('question', true), + options: interaction.options + .getString('options', true) + .split('|') + .map((label) => ({ label })), + multiple: interaction.options.getBoolean('multiple') ?? false, + anonymous: interaction.options.getBoolean('anonymous') ?? false, + showResults: + interaction.options.getString('results') === 'closed' + ? 'closed' + : 'live', + closesAt: closes === null ? null : parseFutureWhen(closes, zone), + }); + await interaction.editReply( + `Poll #${poll.id} is up in <#${poll.channelId}>.`, + ); + }, + list: async (interaction, ctx) => { + const open = await listOpenPolls(ctx.db, interaction.guildId); + await respond( + interaction, + open.length === 0 + ? 'No open polls.' + : open + .map((p) => `#${p.id} ${p.question} — <#${p.channelId}>`) + .join('\n'), + ); + }, + results: showResults, + close: async (interaction, ctx) => { + const poll = await requireManageable(interaction, ctx); + if (!(await closePoll(ctx, poll.id))) { + throw new UserError('That poll is not open.'); + } + await respond(interaction, `Poll #${poll.id} is closed.`); + }, + cancel: async (interaction, ctx) => { + const poll = await requireManageable(interaction, ctx); + const cancelled = await finishPoll(ctx.db, poll.id, 'cancelled'); + if (!cancelled) { + throw new UserError('That poll is not open.'); + } + await ctx.scheduler.cancel(closeKey(poll.id)); + await refreshMessage(ctx, cancelled); + await respond(interaction, `Poll #${poll.id} is cancelled.`); + }, + }), + autocomplete: async (interaction, ctx) => { + const open = await listOpenPolls(ctx.db, interaction.guildId); + await interaction.respond( + open.map((p) => ({ + name: `#${p.id} ${p.question}`.slice(0, 100), + value: p.id, + })), + ); + }, + }, + ], +}; diff --git a/src/features/polls/polls.test.ts b/src/features/polls/polls.test.ts new file mode 100644 index 0000000..14e862c --- /dev/null +++ b/src/features/polls/polls.test.ts @@ -0,0 +1,145 @@ +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { UserError } from '../../shared/errors.js'; +import { closeJob, renderPoll } from './index.js'; +import { + castVote, + finishPoll, + getPoll, + getResults, + getVoterChoices, + insertPoll, + type NewPoll, +} from './service.js'; + +const base = (overrides: Partial = {}): NewPoll => ({ + guildId: snowflake(), + channelId: snowflake(), + creatorId: snowflake(), + question: 'Lunch?', + options: [{ label: 'Pizza' }, { label: 'Sushi' }, { label: 'Tacos' }], + ...overrides, +}); + +describe.skipIf(noDatabase)('polls', () => { + const db = () => testDb(); + + it('validates options', async () => { + await expect( + insertPoll(db(), base({ options: [{ label: 'Only' }] })), + ).rejects.toThrow('between 2'); + await expect( + insertPoll(db(), base({ options: [{ label: 'A' }, { label: 'a' }] })), + ).rejects.toThrow('distinct'); + }); + + it('replaces a single-choice vote instead of adding another', async () => { + const poll = await insertPoll(db(), base()); + const [pizza, sushi] = poll.options; + const user = snowflake(); + await castVote(db(), poll.id, user, [pizza?.id ?? 0]); + await castVote(db(), poll.id, user, [sushi?.id ?? 0]); + expect(await getVoterChoices(db(), poll.id, user)).toEqual([sushi?.id]); + await expect( + castVote(db(), poll.id, user, [pizza?.id ?? 0, sushi?.id ?? 0]), + ).rejects.toThrow('only one'); + }); + + it('accepts several choices in multiple-choice polls and clearing', async () => { + const poll = await insertPoll(db(), base({ multiple: true })); + const ids = poll.options.map((o) => o.id); + const user = snowflake(); + await castVote(db(), poll.id, user, ids); + expect((await getResults(db(), poll)).voters).toBe(1); + expect((await getResults(db(), poll)).options.map((o) => o.votes)).toEqual([ + 1, 1, 1, + ]); + await castVote(db(), poll.id, user, []); + expect((await getResults(db(), poll)).voters).toBe(0); + }); + + it('rejects options from another poll', async () => { + const poll = await insertPoll(db(), base()); + const other = await insertPoll(db(), base()); + await expect( + castVote(db(), poll.id, snowflake(), [other.options[0]?.id ?? 0]), + ).rejects.toThrow('not part'); + }); + + it('reports ties and winners', async () => { + const poll = await insertPoll(db(), base()); + const [pizza, sushi] = poll.options.map((o) => o.id); + await castVote(db(), poll.id, snowflake(), [pizza ?? 0]); + await castVote(db(), poll.id, snowflake(), [sushi ?? 0]); + const tied = await getResults(db(), poll); + expect(tied.tie).toBe(true); + expect(tied.winners.map((w) => w.label)).toEqual(['Pizza', 'Sushi']); + await castVote(db(), poll.id, snowflake(), [sushi ?? 0]); + const won = await getResults(db(), poll); + expect(won.tie).toBe(false); + expect(won.winners.map((w) => w.label)).toEqual(['Sushi']); + }); + + it('refuses votes after closing or the deadline', async () => { + const poll = await insertPoll(db(), base()); + expect(await finishPoll(db(), poll.id, 'closed')).toBeDefined(); + expect(await finishPoll(db(), poll.id, 'closed')).toBeUndefined(); + await expect( + castVote(db(), poll.id, snowflake(), [poll.options[0]?.id ?? 0]), + ).rejects.toBeInstanceOf(UserError); + + const expired = await insertPoll( + db(), + base({ closesAt: new Date(Date.now() - 1000) }), + ); + await expect( + castVote(db(), expired.id, snowflake(), [expired.options[0]?.id ?? 0]), + ).rejects.toThrow('closed'); + }); + + it('keeps counts exact under concurrent voting', async () => { + const poll = await insertPoll(db(), base()); + const [pizza, sushi] = poll.options.map((o) => o.id); + const user = snowflake(); + const voters = Array.from({ length: 20 }, () => snowflake()); + await Promise.all([ + ...voters.map((voter) => castVote(db(), poll.id, voter, [pizza ?? 0])), + // The same member switching rapidly must end with exactly one vote. + ...Array.from({ length: 10 }, (_, n) => + castVote(db(), poll.id, user, [(n % 2 === 0 ? pizza : sushi) ?? 0]), + ), + ]); + const results = await getResults(db(), poll); + expect(results.voters).toBe(21); + expect(await getVoterChoices(db(), poll.id, user)).toHaveLength(1); + }); + + it('closes on schedule and hides live counts when requested', async () => { + const poll = await insertPoll(db(), base({ showResults: 'closed' })); + await castVote(db(), poll.id, snowflake(), [poll.options[0]?.id ?? 0]); + const hidden = JSON.stringify( + renderPoll(poll, await getResults(db(), poll)).embeds, + ); + expect(hidden).not.toContain('█'); + + const ctx = { + db: db(), + log: pino({ level: 'silent' }), + client: { channels: { fetch: vi.fn() } }, + } as unknown as AppContext; + await closeJob.run( + { pollId: poll.id }, + { id: 1, runAt: new Date(), attempt: 1 }, + ctx, + ); + const closed = await getPoll(db(), poll.id); + expect(closed?.status).toBe('closed'); + if (closed) { + const rendered = renderPoll(closed, await getResults(db(), closed)); + expect(JSON.stringify(rendered.embeds)).toContain('Winner'); + expect(rendered.components).toEqual([]); + } + }); +}); diff --git a/src/features/polls/schema.ts b/src/features/polls/schema.ts new file mode 100644 index 0000000..093ea7e --- /dev/null +++ b/src/features/polls/schema.ts @@ -0,0 +1,88 @@ +import { + boolean, + index, + integer, + pgEnum, + pgTable, + primaryKey, + serial, + text, + timestamp, + unique, +} from 'drizzle-orm/pg-core'; + +export const pollStatus = pgEnum('poll_status', [ + 'open', + 'closed', + 'cancelled', +]); +export const pollResultVisibility = pgEnum('poll_result_visibility', [ + 'live', + 'closed', +]); + +export const polls = pgTable( + 'polls', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + channelId: text('channel_id').notNull(), + messageId: text('message_id'), + creatorId: text('creator_id').notNull(), + question: text('question').notNull(), + multiple: boolean('multiple').notNull().default(false), + anonymous: boolean('anonymous').notNull().default(false), + showResults: pollResultVisibility('show_results').notNull().default('live'), + closesAt: timestamp('closes_at', { withTimezone: true }), + status: pollStatus('status').notNull().default('open'), + /** The feature that created the poll, e.g. 'movies'; null for /poll. */ + source: text('source'), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + index('polls_guild_status_idx').on(table.guildId, table.status), + index('polls_source_idx').on(table.guildId, table.source, table.createdAt), + ], +); + +export const pollOptions = pgTable( + 'poll_options', + { + id: serial('id').primaryKey(), + pollId: integer('poll_id') + .notNull() + .references(() => polls.id, { onDelete: 'cascade' }), + position: integer('position').notNull(), + label: text('label').notNull(), + /** An identifier owned by the source feature, e.g. a movie suggestion. */ + ref: text('ref'), + }, + (table) => [ + unique('poll_options_position_unique').on(table.pollId, table.position), + ], +); + +export const pollVotes = pgTable( + 'poll_votes', + { + pollId: integer('poll_id') + .notNull() + .references(() => polls.id, { onDelete: 'cascade' }), + optionId: integer('option_id') + .notNull() + .references(() => pollOptions.id, { onDelete: 'cascade' }), + userId: text('user_id').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + primaryKey({ columns: [table.pollId, table.userId, table.optionId] }), + index('poll_votes_option_idx').on(table.optionId), + ], +); + +export type Poll = typeof polls.$inferSelect; +export type PollOption = typeof pollOptions.$inferSelect; diff --git a/src/features/polls/service.ts b/src/features/polls/service.ts new file mode 100644 index 0000000..505502c --- /dev/null +++ b/src/features/polls/service.ts @@ -0,0 +1,274 @@ +import { + and, + asc, + count, + countDistinct, + desc, + eq, + inArray, + sql, +} from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import { + pollOptions, + polls, + pollVotes, + type Poll, + type PollOption, +} from './schema.js'; + +export const maxOptions = 25; + +export type NewPoll = Pick< + Poll, + 'guildId' | 'channelId' | 'creatorId' | 'question' +> & + Partial< + Pick + > & { + options: ReadonlyArray<{ label: string; ref?: string | null }>; + }; + +export type PollWithOptions = Poll & { options: PollOption[] }; + +export type OptionResult = PollOption & { votes: number }; + +export type PollResults = { + options: OptionResult[]; + voters: number; + /** Options sharing the highest vote count; empty when nobody voted. */ + winners: OptionResult[]; + tie: boolean; +}; + +export async function insertPoll( + db: Db, + input: NewPoll, +): Promise { + const labels = input.options.map((option) => option.label.trim()); + if (labels.length < 2 || labels.length > maxOptions) { + throw new UserError(`A poll needs between 2 and ${maxOptions} options.`); + } + if (labels.some((label) => label === '' || label.length > 100)) { + throw new UserError('Options must be 1–100 characters.'); + } + if ( + new Set(labels.map((label) => label.toLowerCase())).size !== labels.length + ) { + throw new UserError('Options must be distinct.'); + } + return db.transaction(async (tx) => { + const { options, ...values } = input; + const [poll] = await tx.insert(polls).values(values).returning(); + if (!poll) { + throw new Error('Insert returned no row'); + } + const inserted = await tx + .insert(pollOptions) + .values( + options.map((option, position) => ({ + pollId: poll.id, + position, + label: labels[position] ?? '', + ref: option.ref ?? null, + })), + ) + .returning(); + return { + ...poll, + options: inserted.toSorted((a, b) => a.position - b.position), + }; + }); +} + +export async function getPoll( + db: Db, + id: number, +): Promise { + const [poll] = await db.select().from(polls).where(eq(polls.id, id)); + if (!poll) { + return undefined; + } + const options = await db + .select() + .from(pollOptions) + .where(eq(pollOptions.pollId, id)) + .orderBy(asc(pollOptions.position)); + return { ...poll, options }; +} + +export async function requirePoll( + db: Db, + guildId: string, + id: number, +): Promise { + const poll = await getPoll(db, id); + if (poll?.guildId !== guildId) { + throw new UserError(`Poll #${id} does not exist.`); + } + return poll; +} + +export function isOpen(poll: Poll, now = new Date()): boolean { + return ( + poll.status === 'open' && (poll.closesAt === null || poll.closesAt > now) + ); +} + +/** + * Replaces a member's votes with `optionIds` (empty clears them). The poll + * row is locked so a vote cannot race with closing or with the same member + * voting twice at once. + */ +export async function castVote( + db: Db, + pollId: number, + userId: string, + optionIds: readonly number[], +): Promise { + await db.transaction(async (tx) => { + const [poll] = await tx + .select() + .from(polls) + .where(eq(polls.id, pollId)) + .for('update'); + if (!poll || !isOpen(poll)) { + throw new UserError('This poll is closed.'); + } + const unique = [...new Set(optionIds)]; + if (!poll.multiple && unique.length > 1) { + throw new UserError('This poll allows only one choice.'); + } + if (unique.length > 0) { + const valid = await tx + .select({ id: pollOptions.id }) + .from(pollOptions) + .where( + and(eq(pollOptions.pollId, pollId), inArray(pollOptions.id, unique)), + ); + if (valid.length !== unique.length) { + throw new UserError('That option is not part of this poll.'); + } + } + await tx + .delete(pollVotes) + .where(and(eq(pollVotes.pollId, pollId), eq(pollVotes.userId, userId))); + if (unique.length > 0) { + await tx + .insert(pollVotes) + .values(unique.map((optionId) => ({ pollId, optionId, userId }))); + } + }); +} + +export async function getResults( + db: Db, + poll: PollWithOptions, +): Promise { + const [counts, [voters]] = await Promise.all([ + db + .select({ optionId: pollVotes.optionId, votes: count() }) + .from(pollVotes) + .where(eq(pollVotes.pollId, poll.id)) + .groupBy(pollVotes.optionId), + db + .select({ total: countDistinct(pollVotes.userId) }) + .from(pollVotes) + .where(eq(pollVotes.pollId, poll.id)), + ]); + const byOption = new Map(counts.map((row) => [row.optionId, row.votes])); + const options = poll.options.map((option) => ({ + ...option, + votes: byOption.get(option.id) ?? 0, + })); + const top = Math.max(0, ...options.map((option) => option.votes)); + const winners = + top === 0 ? [] : options.filter((option) => option.votes === top); + return { + options, + voters: voters?.total ?? 0, + winners, + tie: winners.length > 1, + }; +} + +export async function getVoterChoices( + db: Db, + pollId: number, + userId: string, +): Promise { + const rows = await db + .select({ optionId: pollVotes.optionId }) + .from(pollVotes) + .where(and(eq(pollVotes.pollId, pollId), eq(pollVotes.userId, userId))); + return rows.map((row) => row.optionId); +} + +/** Voter IDs per option. Never call this for anonymous polls. */ +export async function getVoters( + db: Db, + pollId: number, +): Promise> { + const rows = await db + .select({ optionId: pollVotes.optionId, userId: pollVotes.userId }) + .from(pollVotes) + .where(eq(pollVotes.pollId, pollId)) + .orderBy(asc(pollVotes.createdAt)) + .limit(5000); + const voters = new Map(); + for (const row of rows) { + voters.set(row.optionId, [...(voters.get(row.optionId) ?? []), row.userId]); + } + return voters; +} + +/** Returns the poll if this call closed it, so closing side effects run once. */ +export async function finishPoll( + db: Db, + id: number, + status: 'closed' | 'cancelled', +): Promise { + const [row] = await db + .update(polls) + .set({ + status, + ...(status === 'closed' && { + closesAt: sql`least(${polls.closesAt}, now())`, + }), + }) + .where(and(eq(polls.id, id), eq(polls.status, 'open'))) + .returning(); + return row; +} + +export async function setPollMessage( + db: Db, + id: number, + messageId: string, +): Promise { + await db.update(polls).set({ messageId }).where(eq(polls.id, id)); +} + +export async function listOpenPolls(db: Db, guildId: string): Promise { + return db + .select() + .from(polls) + .where(and(eq(polls.guildId, guildId), eq(polls.status, 'open'))) + .orderBy(desc(polls.id)) + .limit(25); +} + +export async function latestPollBySource( + db: Db, + guildId: string, + source: string, +): Promise { + const [row] = await db + .select({ id: polls.id }) + .from(polls) + .where(and(eq(polls.guildId, guildId), eq(polls.source, source))) + .orderBy(desc(polls.createdAt), desc(polls.id)) + .limit(1); + return row ? getPoll(db, row.id) : undefined; +} From ee12a56639001d1e753093ed993fe4bce332854f Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 011/199] feat(movies): suggestions, votes and movie nights --- src/features/movies/index.ts | 340 +++++++++++++++++++++++++++++ src/features/movies/movies.test.ts | 112 ++++++++++ src/features/movies/schema.ts | 60 +++++ src/features/movies/service.ts | 207 ++++++++++++++++++ 4 files changed, 719 insertions(+) create mode 100644 src/features/movies/index.ts create mode 100644 src/features/movies/movies.test.ts create mode 100644 src/features/movies/schema.ts create mode 100644 src/features/movies/service.ts diff --git a/src/features/movies/index.ts b/src/features/movies/index.ts new file mode 100644 index 0000000..268e341 --- /dev/null +++ b/src/features/movies/index.ts @@ -0,0 +1,340 @@ +import { + ChannelType, + InteractionContextType, + MessageFlags, + SlashCommandBuilder, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand } from '../../core/define.js'; +import type { + AppContext, + CommandInteraction, + Feature, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { UserError } from '../../shared/errors.js'; +import { discordTime, parseFutureWhen, parseWhen } from '../../shared/time.js'; +import { createEvent } from '../events/index.js'; +import { createPoll, getResults, latestPollBySource } from '../polls/index.js'; +import type { MovieSuggestion } from './schema.js'; +import { + listUnwatched, + markWatched, + recordScreening, + removeSuggestion, + requireSuggestion, + suggestMovie, + watchHistory, +} from './service.js'; + +const pollSource = 'movies'; + +const label = (movie: Pick) => + movie.year === null ? movie.title : `${movie.title} (${movie.year})`; + +/** + * The movie for a screening: the one given, otherwise the winner of the most + * recent movie poll. Ties are never broken automatically. + */ +export async function pickMovie( + ctx: AppContext, + guildId: string, + movieId: number | null, +) { + if (movieId !== null) { + return { + movie: await requireSuggestion(ctx.db, guildId, movieId), + pollId: null, + }; + } + const poll = await latestPollBySource(ctx.db, guildId, pollSource); + if (poll?.status !== 'closed') { + throw new UserError('Pick a movie, or close a `/movie vote` poll first.'); + } + const { winners, tie } = await getResults(ctx.db, poll); + if (winners.length === 0) { + throw new UserError('The last movie poll had no votes. Pick a movie.'); + } + if (tie) { + const tied = winners.map((w) => `#${w.ref ?? '?'} ${w.label}`).join(', '); + throw new UserError( + `The last poll is a tie between ${tied}. Pick one with the \`movie\` option.`, + ); + } + const winner = winners[0]; + return { + movie: await requireSuggestion(ctx.db, guildId, Number(winner?.ref)), + pollId: poll.id, + }; +} + +const movieOption = (o: SlashCommandIntegerOption) => + o.setName('movie').setDescription('Movie').setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('movie') + .setDescription('Movie suggestions and movie nights') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('suggest') + .setDescription('Suggest a movie') + .addStringOption((o) => + o + .setName('title') + .setDescription('Title') + .setRequired(true) + .setMaxLength(200), + ) + .addIntegerOption((o) => + o + .setName('year') + .setDescription('Release year') + .setMinValue(1880) + .setMaxValue(2100), + ) + .addStringOption((o) => + o.setName('note').setDescription('Why watch it?').setMaxLength(300), + ), + ) + .addSubcommand((sub) => + sub.setName('suggestions').setDescription('Movies waiting to be watched'), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription('Remove a suggestion') + .addIntegerOption((o) => movieOption(o).setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('vote') + .setDescription('Start a poll over the suggestions') + .addIntegerOption((o) => + o + .setName('count') + .setDescription('How many movies (default 10)') + .setMinValue(2) + .setMaxValue(25), + ) + .addStringOption((o) => + o.setName('closes').setDescription('When voting ends (default 2d)'), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => + sub + .setName('night') + .setDescription( + 'Schedule a movie night (defaults to the last poll winner)', + ) + .addStringOption((o) => + o + .setName('start') + .setDescription('e.g. 2026-11-20 19:00') + .setRequired(true), + ) + .addIntegerOption(movieOption) + .addStringOption((o) => + o.setName('location').setDescription('Where').setMaxLength(200), + ) + .addIntegerOption((o) => + o.setName('capacity').setDescription('Seats').setMinValue(1), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => + sub + .setName('watched') + .setDescription('Mark a movie as watched') + .addIntegerOption((o) => movieOption(o).setRequired(true)) + .addStringOption((o) => + o.setName('date').setDescription('When (default: now)'), + ), + ) + .addSubcommand((sub) => + sub.setName('history').setDescription('Movies we have watched'), + ); + +const zoneOf = (interaction: CommandInteraction, ctx: AppContext) => + getGuildTimezone(ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE); + +export const moviesFeature: Feature = { + name: 'movies', + permissions: [ + { + id: 'movie:manage', + description: 'Run movie votes and movie nights, remove suggestions', + }, + ], + commands: [ + { + data: data.toJSON(), + permissions: { + vote: 'movie:manage', + night: 'movie:manage', + watched: 'movie:manage', + }, + execute: bySubcommand({ + suggest: async (interaction, ctx) => { + const movie = await suggestMovie(ctx.db, { + guildId: interaction.guildId, + title: interaction.options.getString('title', true), + year: interaction.options.getInteger('year'), + note: interaction.options.getString('note'), + suggestedBy: interaction.user.id, + }); + await respond( + interaction, + `Added #${movie.id} ${label(movie)} to the list.`, + ); + }, + suggestions: async (interaction, ctx) => { + const movies = await listUnwatched(ctx.db, interaction.guildId); + await respond( + interaction, + movies.length === 0 + ? 'No suggestions yet. Add one with `/movie suggest`.' + : movies + .map((m) => `#${m.id} ${label(m)} — <@${m.suggestedBy}>`) + .join('\n'), + ); + }, + remove: async (interaction, ctx) => { + const movie = await requireSuggestion( + ctx.db, + interaction.guildId, + interaction.options.getInteger('movie', true), + ); + if (movie.suggestedBy !== interaction.user.id) { + await ctx.authz.require(interaction.member, 'movie:manage'); + } + await removeSuggestion(ctx.db, movie.id); + await respond(interaction, `Removed ${label(movie)}.`); + }, + vote: async (interaction, ctx) => { + const movies = await listUnwatched( + ctx.db, + interaction.guildId, + interaction.options.getInteger('count') ?? 10, + ); + if (movies.length < 2) { + throw new UserError( + 'At least two unwatched suggestions are needed for a vote.', + ); + } + const closesAt = parseFutureWhen( + interaction.options.getString('closes') ?? '2d', + await zoneOf(interaction, ctx), + ); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const poll = await createPoll(ctx, { + guildId: interaction.guildId, + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + creatorId: interaction.user.id, + question: '🎬 What should we watch next?', + options: movies.map((m) => ({ + label: label(m).slice(0, 100), + ref: String(m.id), + })), + closesAt, + source: pollSource, + }); + await interaction.editReply( + `Movie poll #${poll.id} closes ${discordTime(closesAt, 'R')}.`, + ); + }, + night: async (interaction, ctx) => { + const { movie, pollId } = await pickMovie( + ctx, + interaction.guildId, + interaction.options.getInteger('movie'), + ); + const timezone = await zoneOf(interaction, ctx); + const startsAt = parseFutureWhen( + interaction.options.getString('start', true), + timezone, + ); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const event = await createEvent(ctx, { + guildId: interaction.guildId, + title: `🎬 Movie night: ${label(movie)}`.slice(0, 200), + description: movie.note, + startsAt, + timezone, + location: interaction.options.getString('location'), + organizerId: interaction.user.id, + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + capacity: interaction.options.getInteger('capacity'), + reminderMinutes: [60], + }); + await recordScreening(ctx.db, { + guildId: interaction.guildId, + suggestionId: movie.id, + eventId: event.id, + pollId, + scheduledFor: startsAt, + }); + await interaction.editReply( + `Movie night for ${label(movie)} is event #${event.id}.`, + ); + }, + watched: async (interaction, ctx) => { + const movie = await requireSuggestion( + ctx.db, + interaction.guildId, + interaction.options.getInteger('movie', true), + ); + const date = interaction.options.getString('date'); + const watchedAt = + date === null + ? new Date() + : parseWhen(date, await zoneOf(interaction, ctx)); + await markWatched(ctx.db, interaction.guildId, movie.id, watchedAt); + await respond(interaction, `Marked ${label(movie)} as watched.`); + }, + history: async (interaction, ctx) => { + const history = await watchHistory(ctx.db, interaction.guildId); + await respond( + interaction, + history.length === 0 + ? 'No movies watched yet.' + : history + .map( + (h) => + `${h.watchedAt ? discordTime(h.watchedAt, 'D') : ''} ${label(h)}`, + ) + .join('\n'), + ); + }, + }), + autocomplete: async (interaction, ctx) => { + const query = interaction.options.getFocused().toLowerCase(); + const movies = await listUnwatched(ctx.db, interaction.guildId); + await interaction.respond( + movies + .filter((m) => m.title.toLowerCase().includes(query)) + .map((m) => ({ + name: `#${m.id} ${label(m)}`.slice(0, 100), + value: m.id, + })), + ); + }, + }, + ], +}; diff --git a/src/features/movies/movies.test.ts b/src/features/movies/movies.test.ts new file mode 100644 index 0000000..8d5e91d --- /dev/null +++ b/src/features/movies/movies.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { AppContext } from '../../core/feature.js'; +import { castVote, finishPoll, insertPoll } from '../polls/service.js'; +import { pickMovie } from './index.js'; +import { + listUnwatched, + markWatched, + normalizeTitle, + recordScreening, + suggestMovie, + watchHistory, +} from './service.js'; + +describe('normalizeTitle', () => { + it('ignores case, punctuation and spacing', () => { + expect(normalizeTitle('The Matrix!')).toBe( + normalizeTitle(' the MATRIX '), + ); + expect(normalizeTitle('Amélie')).toBe(normalizeTitle('amélie')); + }); +}); + +describe.skipIf(noDatabase)('movies', () => { + const ctx = () => ({ db: testDb() }) as unknown as AppContext; + const suggest = (guildId: string, title: string) => + suggestMovie(testDb(), { + guildId, + title, + year: null, + note: null, + suggestedBy: snowflake(), + }); + + it('rejects duplicate suggestions and points out watched ones', async () => { + const guildId = snowflake(); + const movie = await suggest(guildId, 'Paprika'); + await expect(suggest(guildId, 'paprika!')).rejects.toThrow( + 'already suggested', + ); + await markWatched( + testDb(), + guildId, + movie.id, + new Date('2026-01-02T20:00:00Z'), + ); + await expect(suggest(guildId, 'Paprika')).rejects.toThrow( + 'already watched (2026-01-02)', + ); + expect(await suggest(snowflake(), 'Paprika')).toBeDefined(); + }); + + it('picks the winner of the latest movie poll and refuses ties', async () => { + const guildId = snowflake(); + const [a, b] = [ + await suggest(guildId, 'Alien'), + await suggest(guildId, 'Brazil'), + ]; + const poll = await insertPoll(testDb(), { + guildId, + channelId: snowflake(), + creatorId: snowflake(), + question: 'Next?', + source: 'movies', + options: [a, b].map((m) => ({ label: m.title, ref: String(m.id) })), + }); + await expect(pickMovie(ctx(), guildId, null)).rejects.toThrow('close'); + + const [optionA, optionB] = poll.options.map((o) => o.id); + await castVote(testDb(), poll.id, snowflake(), [optionA ?? 0]); + await castVote(testDb(), poll.id, snowflake(), [optionB ?? 0]); + await finishPoll(testDb(), poll.id, 'closed'); + await expect(pickMovie(ctx(), guildId, null)).rejects.toThrow('tie'); + expect((await pickMovie(ctx(), guildId, b.id)).movie.title).toBe('Brazil'); + + const second = await insertPoll(testDb(), { + guildId, + channelId: snowflake(), + creatorId: snowflake(), + question: 'Again?', + source: 'movies', + options: [a, b].map((m) => ({ label: m.title, ref: String(m.id) })), + }); + await castVote(testDb(), second.id, snowflake(), [ + second.options[0]?.id ?? 0, + ]); + await finishPoll(testDb(), second.id, 'closed'); + expect(await pickMovie(ctx(), guildId, null)).toMatchObject({ + movie: { title: 'Alien' }, + pollId: second.id, + }); + }); + + it('tracks screenings and history', async () => { + const guildId = snowflake(); + const movie = await suggest(guildId, 'Heat'); + await recordScreening(testDb(), { + guildId, + suggestionId: movie.id, + eventId: 1, + scheduledFor: new Date(), + }); + expect((await listUnwatched(testDb(), guildId)).map((m) => m.id)).toEqual([ + movie.id, + ]); + await markWatched(testDb(), guildId, movie.id, new Date()); + expect(await listUnwatched(testDb(), guildId)).toEqual([]); + expect((await watchHistory(testDb(), guildId)).map((h) => h.title)).toEqual( + ['Heat'], + ); + }); +}); diff --git a/src/features/movies/schema.ts b/src/features/movies/schema.ts new file mode 100644 index 0000000..7de3250 --- /dev/null +++ b/src/features/movies/schema.ts @@ -0,0 +1,60 @@ +import { sql } from 'drizzle-orm'; +import { + index, + integer, + pgTable, + serial, + smallint, + text, + timestamp, + uniqueIndex, +} from 'drizzle-orm/pg-core'; + +export const movieSuggestions = pgTable( + 'movie_suggestions', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + title: text('title').notNull(), + normalizedTitle: text('normalized_title').notNull(), + year: smallint('year'), + note: text('note'), + suggestedBy: text('suggested_by').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + removedAt: timestamp('removed_at', { withTimezone: true }), + }, + (table) => [ + uniqueIndex('movie_suggestions_unique_idx') + .on(table.guildId, table.normalizedTitle) + .where(sql`${table.removedAt} IS NULL`), + ], +); + +/** + * A movie night. Voting and scheduling live in the polls and events features; + * these IDs only link to them, so they carry no foreign keys across features. + */ +export const movieScreenings = pgTable( + 'movie_screenings', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + suggestionId: integer('suggestion_id') + .notNull() + .references(() => movieSuggestions.id), + eventId: integer('event_id'), + pollId: integer('poll_id'), + scheduledFor: timestamp('scheduled_for', { withTimezone: true }), + watchedAt: timestamp('watched_at', { withTimezone: true }), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + index('movie_screenings_guild_idx').on(table.guildId, table.watchedAt), + ], +); + +export type MovieSuggestion = typeof movieSuggestions.$inferSelect; diff --git a/src/features/movies/service.ts b/src/features/movies/service.ts new file mode 100644 index 0000000..42fd753 --- /dev/null +++ b/src/features/movies/service.ts @@ -0,0 +1,207 @@ +import { and, asc, desc, eq, isNotNull, isNull, notExists } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import { UserError } from '../../shared/errors.js'; +import { + movieScreenings, + movieSuggestions, + type MovieSuggestion, +} from './schema.js'; + +/** "The Matrix!" and "the matrix" are the same suggestion. */ +export function normalizeTitle(title: string): string { + return title + .normalize('NFKD') + .toLowerCase() + .replaceAll(/[^\p{L}\p{N}]+/gu, ' ') + .trim(); +} + +const watched = (db: Db) => + db + .select({ id: movieScreenings.id }) + .from(movieScreenings) + .where( + and( + eq(movieScreenings.suggestionId, movieSuggestions.id), + isNotNull(movieScreenings.watchedAt), + ), + ); + +export async function suggestMovie( + db: Db, + input: { + guildId: string; + title: string; + year: number | null; + note: string | null; + suggestedBy: string; + }, +): Promise { + const normalizedTitle = normalizeTitle(input.title); + if (normalizedTitle === '') { + throw new UserError('Give a movie title.'); + } + const [row] = await db + .insert(movieSuggestions) + .values({ ...input, title: input.title.trim(), normalizedTitle }) + .onConflictDoNothing() + .returning(); + if (!row) { + const existing = await findActive(db, input.guildId, normalizedTitle); + const when = existing && (await lastWatched(db, existing.id)); + throw new UserError( + when + ? `That movie was already watched (${when.toISOString().slice(0, 10)}).` + : 'That movie is already suggested.', + ); + } + return row; +} + +async function findActive(db: Db, guildId: string, normalizedTitle: string) { + const [row] = await db + .select() + .from(movieSuggestions) + .where( + and( + eq(movieSuggestions.guildId, guildId), + eq(movieSuggestions.normalizedTitle, normalizedTitle), + isNull(movieSuggestions.removedAt), + ), + ); + return row; +} + +export async function lastWatched( + db: Db, + suggestionId: number, +): Promise { + const [row] = await db + .select({ watchedAt: movieScreenings.watchedAt }) + .from(movieScreenings) + .where( + and( + eq(movieScreenings.suggestionId, suggestionId), + isNotNull(movieScreenings.watchedAt), + ), + ) + .orderBy(desc(movieScreenings.watchedAt)) + .limit(1); + return row?.watchedAt ?? undefined; +} + +export async function requireSuggestion( + db: Db, + guildId: string, + id: number, +): Promise { + const [row] = await db + .select() + .from(movieSuggestions) + .where( + and( + eq(movieSuggestions.id, id), + eq(movieSuggestions.guildId, guildId), + isNull(movieSuggestions.removedAt), + ), + ); + if (!row) { + throw new UserError(`Movie #${id} is not on the list.`); + } + return row; +} + +/** Suggestions not yet watched, oldest first so long-waiting ones get a turn. */ +export async function listUnwatched( + db: Db, + guildId: string, + limit = 25, +): Promise { + return db + .select() + .from(movieSuggestions) + .where( + and( + eq(movieSuggestions.guildId, guildId), + isNull(movieSuggestions.removedAt), + notExists(watched(db)), + ), + ) + .orderBy(asc(movieSuggestions.createdAt)) + .limit(limit); +} + +export async function removeSuggestion(db: Db, id: number): Promise { + await db + .update(movieSuggestions) + .set({ removedAt: new Date() }) + .where(eq(movieSuggestions.id, id)); +} + +export async function recordScreening( + db: Db, + input: { + guildId: string; + suggestionId: number; + eventId?: number | null; + pollId?: number | null; + scheduledFor?: Date | null; + }, +): Promise { + const [row] = await db + .insert(movieScreenings) + .values(input) + .returning({ id: movieScreenings.id }); + if (!row) { + throw new Error('Insert returned no row'); + } + return row.id; +} + +/** Marks the latest unwatched screening as watched, or records a new one. */ +export async function markWatched( + db: Db, + guildId: string, + suggestionId: number, + watchedAt: Date, +): Promise { + const [pending] = await db + .select({ id: movieScreenings.id }) + .from(movieScreenings) + .where( + and( + eq(movieScreenings.suggestionId, suggestionId), + isNull(movieScreenings.watchedAt), + ), + ) + .orderBy(desc(movieScreenings.createdAt)) + .limit(1); + await (pending + ? db + .update(movieScreenings) + .set({ watchedAt }) + .where(eq(movieScreenings.id, pending.id)) + : db.insert(movieScreenings).values({ guildId, suggestionId, watchedAt })); +} + +export async function watchHistory(db: Db, guildId: string, limit = 25) { + return db + .select({ + title: movieSuggestions.title, + year: movieSuggestions.year, + watchedAt: movieScreenings.watchedAt, + }) + .from(movieScreenings) + .innerJoin( + movieSuggestions, + eq(movieSuggestions.id, movieScreenings.suggestionId), + ) + .where( + and( + eq(movieScreenings.guildId, guildId), + isNotNull(movieScreenings.watchedAt), + ), + ) + .orderBy(desc(movieScreenings.watchedAt)) + .limit(limit); +} From 6f0f4a17697a30ec3af28a4f501daef55355009d Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 012/199] feat(redmine): typed client, account linking and notifications --- src/features/redmine/index.ts | 605 ++++++++++++++++++++++++ src/features/redmine/notifications.ts | 181 +++++++ src/features/redmine/redmine.test.ts | 184 +++++++ src/features/redmine/schema.ts | 55 +++ src/features/redmine/service.ts | 179 +++++++ src/integrations/redmine/client.test.ts | 104 ++++ src/integrations/redmine/client.ts | 317 +++++++++++++ src/shared/crypto.test.ts | 28 ++ src/shared/crypto.ts | 52 ++ 9 files changed, 1705 insertions(+) create mode 100644 src/features/redmine/index.ts create mode 100644 src/features/redmine/notifications.ts create mode 100644 src/features/redmine/redmine.test.ts create mode 100644 src/features/redmine/schema.ts create mode 100644 src/features/redmine/service.ts create mode 100644 src/integrations/redmine/client.test.ts create mode 100644 src/integrations/redmine/client.ts create mode 100644 src/shared/crypto.test.ts create mode 100644 src/shared/crypto.ts diff --git a/src/features/redmine/index.ts b/src/features/redmine/index.ts new file mode 100644 index 0000000..d173d7d --- /dev/null +++ b/src/features/redmine/index.ts @@ -0,0 +1,605 @@ +import { + ChannelType, + EmbedBuilder, + InteractionContextType, + LabelBuilder, + MessageFlags, + ModalBuilder, + SlashCommandBuilder, + TextInputBuilder, + TextInputStyle, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { DateTime } from 'luxon'; +import { respond } from '../../core/discord/router.js'; +import { bySubcommand, deferred } from '../../core/define.js'; +import type { Config } from '../../core/config.js'; +import type { + AppContext, + CommandInteraction, + ComponentHandler, + Feature, + SlashCommand, +} from '../../core/feature.js'; +import { getGuildTimezone } from '../../core/guild-settings.js'; +import { + RedmineClient, + RedmineError, + type RedmineIssue, + type RedmineUser, +} from '../../integrations/redmine/client.js'; +import { createSecretBox, type SecretBox } from '../../shared/crypto.js'; +import { UserError } from '../../shared/errors.js'; +import { createReminder } from '../reminders/index.js'; +import { createNotificationJobs } from './notifications.js'; +import { + addSubscription, + deleteLink, + getLink, + removeSubscription, + saveLink, +} from './service.js'; + +type Handler = ( + interaction: CommandInteraction, + ctx: AppContext, +) => Promise; + +/** Redmine failures become user-facing messages; nothing about keys leaks. */ +function withRedmineErrors(handler: Handler): Handler { + return async (interaction, ctx) => { + try { + await handler(interaction, ctx); + } catch (error) { + if (error instanceof RedmineError) { + ctx.log.warn( + { kind: error.kind, userId: interaction.user.id }, + 'Redmine request failed', + ); + throw new UserError(error.message); + } + throw error; + } + }; +} + +const issueOption = (o: SlashCommandIntegerOption) => + o + .setName('issue') + .setDescription('Issue number') + .setRequired(true) + .setMinValue(1); + +const data = new SlashCommandBuilder() + .setName('redmine') + .setDescription('Redmine projects and issues') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub.setName('projects').setDescription('Projects you can see'), + ) + .addSubcommand((sub) => + sub + .setName('issues') + .setDescription('List issues') + .addStringOption((o) => + o.setName('project').setDescription('Project identifier'), + ) + .addBooleanOption((o) => + o.setName('mine').setDescription('Only issues assigned to me'), + ) + .addStringOption((o) => + o + .setName('status') + .setDescription('Status filter') + .addChoices( + { name: 'open', value: 'open' }, + { name: 'closed', value: 'closed' }, + { name: 'all', value: '*' }, + ), + ), + ) + .addSubcommandGroup((group) => + group + .setName('issue') + .setDescription('A single issue') + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('Show an issue') + .addIntegerOption(issueOption), + ) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Create an issue') + .addStringOption((o) => + o + .setName('project') + .setDescription('Project identifier') + .setRequired(true), + ) + .addStringOption((o) => + o + .setName('subject') + .setDescription('Subject') + .setRequired(true) + .setMaxLength(255), + ) + .addStringOption((o) => + o + .setName('description') + .setDescription('Description') + .setMaxLength(4000), + ) + .addBooleanOption((o) => + o.setName('assign_to_me').setDescription('Assign it to me'), + ), + ) + .addSubcommand((sub) => + sub + .setName('update') + .setDescription('Change status or add notes') + .addIntegerOption(issueOption) + .addIntegerOption((o) => + o + .setName('status') + .setDescription('New status') + .setAutocomplete(true), + ) + .addStringOption((o) => + o.setName('notes').setDescription('Notes').setMaxLength(4000), + ), + ) + .addSubcommand((sub) => + sub + .setName('assign') + .setDescription('Assign an issue') + .addIntegerOption(issueOption) + .addUserOption((o) => + o.setName('member').setDescription('Linked member (default: you)'), + ), + ) + .addSubcommand((sub) => + sub + .setName('comment') + .setDescription('Comment on an issue') + .addIntegerOption(issueOption) + .addStringOption((o) => + o + .setName('text') + .setDescription('Comment') + .setRequired(true) + .setMaxLength(4000), + ), + ) + .addSubcommand((sub) => + sub + .setName('remind') + .setDescription('DM me before the due date') + .addIntegerOption(issueOption) + .addIntegerOption((o) => + o + .setName('days_before') + .setDescription('Days before (default 1)') + .setMinValue(0) + .setMaxValue(30), + ), + ), + ) + .addSubcommand((sub) => + sub + .setName('link') + .setDescription('Link your Redmine account with your API key'), + ) + .addSubcommand((sub) => + sub.setName('unlink').setDescription('Remove your stored Redmine key'), + ) + .addSubcommand((sub) => + sub + .setName('subscribe') + .setDescription('Post project updates in a channel') + .addStringOption((o) => + o + .setName('project') + .setDescription('Project identifier') + .setRequired(true), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Channel (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => + sub + .setName('unsubscribe') + .setDescription('Stop project updates in a channel') + .addStringOption((o) => + o + .setName('project') + .setDescription('Project identifier') + .setRequired(true), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Channel (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ); + +function issueLine(baseUrl: string, issue: RedmineIssue): string { + const assignee = issue.assigned_to ? ` · ${issue.assigned_to.name}` : ''; + return `[#${issue.id}](<${baseUrl}issues/${issue.id}>) **${issue.subject}** — ${issue.status.name}${assignee}`; +} + +function issueEmbed(baseUrl: string, issue: RedmineIssue): EmbedBuilder { + return new EmbedBuilder() + .setTitle(`#${issue.id} ${issue.subject}`.slice(0, 256)) + .setURL(`${baseUrl}issues/${issue.id}`) + .setDescription((issue.description ?? '').slice(0, 1500) || null) + .addFields( + { name: 'Project', value: issue.project.name, inline: true }, + { name: 'Status', value: issue.status.name, inline: true }, + { name: 'Priority', value: issue.priority.name, inline: true }, + { name: 'Assignee', value: issue.assigned_to?.name ?? '—', inline: true }, + { name: 'Due', value: issue.due_date ?? '—', inline: true }, + ); +} + +/** + * Discord-side permission is necessary but never sufficient: every request + * below runs with the member's own Redmine key, so Redmine still decides. + */ +export function createRedmineFeature(config: Config): Feature | undefined { + const base = config.REDMINE_BASE_URL; + if (base === undefined) { + return undefined; + } + if (config.CREDENTIAL_ENCRYPTION_KEY === undefined) { + throw new Error( + 'CREDENTIAL_ENCRYPTION_KEY is required when REDMINE_BASE_URL is set', + ); + } + const baseUrl = base.endsWith('/') ? base : `${base}/`; + const box: SecretBox = createSecretBox(config.CREDENTIAL_ENCRYPTION_KEY); + const service = + config.REDMINE_API_KEY === undefined + ? undefined + : new RedmineClient(baseUrl, config.REDMINE_API_KEY); + const notifications = service && createNotificationJobs(service, baseUrl); + + async function clientFor( + ctx: AppContext, + userId: string, + ): Promise<{ client: RedmineClient; redmineUserId: number }> { + const link = await getLink(ctx.db, userId); + if (!link) { + throw new UserError( + 'Link your Redmine account first with `/redmine link`.', + ); + } + return { + client: new RedmineClient(baseUrl, box.decrypt(link.encryptedApiKey)), + redmineUserId: link.redmineUserId, + }; + } + + const requireService = (): RedmineClient => { + if (!service) { + throw new UserError( + 'Redmine notifications are not configured (REDMINE_API_KEY).', + ); + } + return service; + }; + + const subscription = + (action: 'subscribe' | 'unsubscribe'): Handler => + async (interaction, ctx) => { + const channelId = + interaction.options.getChannel('channel')?.id ?? interaction.channelId; + // The project must be visible to the member and to the service account. + const { client } = await clientFor(ctx, interaction.user.id); + const identifier = interaction.options.getString('project', true); + const { projects } = await client.listProjects(0, 100); + const project = projects.find( + (p) => p.identifier === identifier || String(p.id) === identifier, + ); + if (!project) { + throw new UserError( + `Project "${identifier}" not found among your projects.`, + ); + } + if (action === 'unsubscribe') { + const removed = await removeSubscription( + ctx.db, + interaction.guildId, + channelId, + project.id, + ); + await respond( + interaction, + removed + ? `Unsubscribed <#${channelId}> from ${project.name}.` + : 'No such subscription.', + ); + return; + } + await requireService().listIssues({ projectId: project.id, limit: 1 }); + const added = await addSubscription(ctx.db, { + guildId: interaction.guildId, + channelId, + projectId: project.id, + projectName: project.name, + createdBy: interaction.user.id, + }); + ctx.log.info( + { + guildId: interaction.guildId, + channelId, + projectId: project.id, + actorId: interaction.user.id, + }, + 'Redmine subscription added', + ); + await respond( + interaction, + added + ? `<#${channelId}> now gets updates for ${project.name}. Everyone who can read the channel will see them.` + : 'That channel is already subscribed.', + ); + }; + + const handlers: Record = { + projects: async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const { projects, total } = await client.listProjects(); + const lines = projects.map((p) => `\`${p.identifier}\` ${p.name}`); + await respond( + interaction, + [ + ...lines, + total > projects.length ? `…and ${total - projects.length} more` : '', + ].join('\n') || 'No projects.', + ); + }, + issues: async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const status = interaction.options.getString('status'); + const project = interaction.options.getString('project'); + const { issues, total } = await client.listIssues({ + ...(project === null ? {} : { projectId: project }), + assignedToMe: interaction.options.getBoolean('mine') ?? false, + status: status === 'closed' || status === '*' ? status : 'open', + limit: 15, + }); + const lines = issues.map((issue) => issueLine(baseUrl, issue)); + await respond( + interaction, + lines.length === 0 + ? 'No issues.' + : `${lines.join('\n')}\n${issues.length} of ${total}`.slice(0, 2000), + ); + }, + 'issue view': async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const issue = await client.getIssue( + interaction.options.getInteger('issue', true), + ); + await respond(interaction, { embeds: [issueEmbed(baseUrl, issue)] }); + }, + 'issue create': async (interaction, ctx) => { + const { client, redmineUserId } = await clientFor( + ctx, + interaction.user.id, + ); + const description = interaction.options.getString('description'); + const issue = await client.createIssue({ + project_id: interaction.options.getString('project', true), + subject: interaction.options.getString('subject', true), + ...(description === null ? {} : { description }), + ...(interaction.options.getBoolean('assign_to_me') === true + ? { assigned_to_id: redmineUserId } + : {}), + }); + await respond(interaction, `Created ${issueLine(baseUrl, issue)}`); + }, + 'issue update': async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const status = interaction.options.getInteger('status'); + const notes = interaction.options.getString('notes'); + if (status === null && notes === null) { + throw new UserError('Give a new status or notes.'); + } + const id = interaction.options.getInteger('issue', true); + await client.updateIssue(id, { + ...(status === null ? {} : { status_id: status }), + ...(notes === null ? {} : { notes }), + }); + await respond(interaction, `Updated #${id}.`); + }, + 'issue assign': async (interaction, ctx) => { + const { client, redmineUserId } = await clientFor( + ctx, + interaction.user.id, + ); + const member = interaction.options.getUser('member'); + let assignee = redmineUserId; + if (member && member.id !== interaction.user.id) { + const link = await getLink(ctx.db, member.id); + if (!link) { + throw new UserError( + `${member.username} has not linked a Redmine account.`, + ); + } + assignee = link.redmineUserId; + } + const id = interaction.options.getInteger('issue', true); + await client.updateIssue(id, { assigned_to_id: assignee }); + await respond(interaction, `Assigned #${id}.`); + }, + 'issue comment': async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const id = interaction.options.getInteger('issue', true); + await client.updateIssue(id, { + notes: interaction.options.getString('text', true), + }); + await respond(interaction, `Commented on #${id}.`); + }, + 'issue remind': async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const issue = await client.getIssue( + interaction.options.getInteger('issue', true), + ); + if (issue.due_date === undefined || issue.due_date === null) { + throw new UserError(`#${issue.id} has no due date.`); + } + const timezone = await getGuildTimezone( + ctx.db, + interaction.guildId, + ctx.config.DEFAULT_TIMEZONE, + ); + const runAt = DateTime.fromISO(issue.due_date, { zone: timezone }) + .minus({ days: interaction.options.getInteger('days_before') ?? 1 }) + .set({ hour: 9 }) + .toJSDate(); + if (runAt.getTime() <= Date.now()) { + throw new UserError('That reminder time has already passed.'); + } + const reminder = await createReminder(ctx, { + guildId: interaction.guildId, + userId: interaction.user.id, + channelId: null, + message: `Redmine #${issue.id} "${issue.subject}" is due ${issue.due_date}: ${baseUrl}issues/${issue.id}`, + runAt, + recurrence: null, + timezone, + }); + await respond( + interaction, + `I will DM you (reminder #${reminder.id}).`, + ); + }, + link: async (interaction) => { + const key = new TextInputBuilder() + .setCustomId('key') + .setStyle(TextInputStyle.Short) + .setMinLength(20) + .setMaxLength(100); + await interaction.showModal( + new ModalBuilder() + .setCustomId('redmine:link') + .setTitle('Link Redmine') + .addLabelComponents( + new LabelBuilder() + .setLabel('API key') + .setDescription( + 'Redmine → My account → API access key. Stored encrypted.', + ) + .setTextInputComponent(key), + ), + ); + }, + unlink: async (interaction, ctx) => { + const removed = await deleteLink(ctx.db, interaction.user.id); + ctx.log.info( + { userId: interaction.user.id, removed }, + 'Redmine account unlinked', + ); + await respond( + interaction, + removed ? 'Your Redmine key is deleted.' : 'You had no linked account.', + ); + }, + subscribe: subscription('subscribe'), + unsubscribe: subscription('unsubscribe'), + }; + + const linkModal: ComponentHandler = { + prefix: 'redmine:link', + execute: async (interaction, _args, ctx) => { + if (!interaction.isModalSubmit()) { + return; + } + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const apiKey = interaction.fields.getTextInputValue('key').trim(); + let user: RedmineUser; + try { + user = await new RedmineClient(baseUrl, apiKey).currentUser(); + } catch (error) { + if (error instanceof RedmineError) { + throw new UserError( + error.kind === 'auth' + ? 'Redmine did not accept that API key.' + : error.message, + ); + } + throw error; + } + await saveLink(ctx.db, { + userId: interaction.user.id, + redmineUserId: user.id, + redmineLogin: user.login, + encryptedApiKey: box.encrypt(apiKey), + }); + ctx.log.info( + { userId: interaction.user.id, redmineUserId: user.id }, + 'Redmine account linked', + ); + await interaction.editReply(`Linked to Redmine user **${user.login}**.`); + }, + }; + + const command: SlashCommand = { + data: data.toJSON(), + permissions: { + 'issue create': 'redmine:issue:create', + 'issue update': 'redmine:issue:update', + 'issue comment': 'redmine:issue:update', + 'issue assign': 'redmine:issue:assign', + subscribe: 'redmine:subscription:manage', + unsubscribe: 'redmine:subscription:manage', + }, + // Redmine can be slow, so everything but the modal is deferred first. + execute: bySubcommand( + Object.fromEntries( + Object.entries(handlers).map(([path, handler]) => [ + path, + path === 'link' ? handler : deferred(withRedmineErrors(handler)), + ]), + ), + ), + autocomplete: async (interaction, ctx) => { + const { client } = await clientFor(ctx, interaction.user.id); + const statuses = await client.listStatuses(); + await interaction.respond( + statuses.slice(0, 25).map((s) => ({ name: s.name, value: s.id })), + ); + }, + }; + + return { + name: 'redmine', + permissions: [ + { + id: 'redmine:issue:create', + description: 'Create Redmine issues (Redmine permissions still apply)', + }, + { + id: 'redmine:issue:update', + description: 'Update and comment on Redmine issues', + }, + { id: 'redmine:issue:assign', description: 'Assign Redmine issues' }, + { + id: 'redmine:subscription:manage', + description: 'Subscribe channels to Redmine projects', + }, + ], + commands: [command], + components: [linkModal], + jobs: notifications?.jobs ?? [], + ...(notifications && { start: notifications.start }), + }; +} diff --git a/src/features/redmine/notifications.ts b/src/features/redmine/notifications.ts new file mode 100644 index 0000000..306c845 --- /dev/null +++ b/src/features/redmine/notifications.ts @@ -0,0 +1,181 @@ +import { MessageFlags } from 'discord.js'; +import { DateTime } from 'luxon'; +import { z } from 'zod'; +import { defineJob } from '../../core/define.js'; +import type { AppContext } from '../../core/feature.js'; +import type { + RedmineClient, + RedmineStatus, +} from '../../integrations/redmine/client.js'; +import { nextDailyRun } from '../../shared/time.js'; +import type { RedmineSubscription } from './schema.js'; +import { + claimNotification, + issueNotifications, + listSubscriptions, + setCheckpoint, +} from './service.js'; + +const pollIntervalMs = 2 * 60 * 1000; +const issuesPerPoll = 25; +const deadlineHour = 9; + +export const pollKey = 'redmine:poll'; +export const deadlineKey = 'redmine:deadlines'; + +async function forEachSubscription( + ctx: AppContext, + handle: (subscription: RedmineSubscription) => Promise, +): Promise { + let afterId = 0; + for (;;) { + const page = await listSubscriptions(ctx.db, afterId); + for (const subscription of page) { + try { + await handle(subscription); + } catch (error) { + ctx.log.warn( + { err: error, subscriptionId: subscription.id }, + 'Redmine subscription update failed', + ); + } + } + const last = page.at(-1); + if (last === undefined) { + return; + } + afterId = last.id; + } +} + +async function sendOnce( + ctx: AppContext, + subscription: RedmineSubscription, + key: string, + text: string, +) { + if (!(await claimNotification(ctx.db, subscription.id, key))) { + return; + } + const channel = await ctx.client.channels.fetch(subscription.channelId); + if (channel?.isSendable() === true) { + await channel.send({ + content: text.slice(0, 2000), + allowedMentions: { parse: [] }, + flags: MessageFlags.SuppressEmbeds, + }); + } +} + +/** + * Incremental polling: each subscription remembers the newest update it has + * processed and only asks Redmine for issues updated since. Notifications + * are claimed in the database before sending, so none repeat. + */ +async function pollSubscription( + ctx: AppContext, + redmine: RedmineClient, + baseUrl: string, + subscription: RedmineSubscription, + statuses: ReadonlyMap, +): Promise { + const { issues } = await redmine.listIssues({ + projectId: subscription.projectId, + status: '*', + updatedSince: subscription.checkpoint, + sort: 'updated_on:asc', + limit: issuesPerPoll, + }); + let checkpoint = subscription.checkpoint; + for (const summary of issues) { + const issue = await redmine.getIssue(summary.id, true); + const url = new URL(`issues/${issue.id}`, baseUrl).href; + for (const notification of issueNotifications( + issue, + subscription.checkpoint, + statuses, + url, + )) { + await sendOnce(ctx, subscription, notification.key, notification.text); + } + const updated = new Date(issue.updated_on); + if (updated > checkpoint) { + checkpoint = updated; + } + } + if (checkpoint > subscription.checkpoint) { + await setCheckpoint(ctx.db, subscription.id, checkpoint); + } +} + +export function createNotificationJobs( + redmine: RedmineClient, + baseUrl: string, +) { + const root = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; + + const pollJob = defineJob({ + type: 'redmine:poll', + payload: z.object({}), + handle: async (_payload, _info, ctx) => { + // Without statuses, notifications show "?" names instead of failing. + const known = await redmine.listStatuses().catch(() => []); + const statuses = new Map(known.map((status) => [status.id, status])); + await forEachSubscription(ctx, (subscription) => + pollSubscription(ctx, redmine, root, subscription, statuses), + ); + return { rescheduleAt: new Date(Date.now() + pollIntervalMs) }; + }, + }); + + const deadlineJob = defineJob({ + type: 'redmine:deadlines', + payload: z.object({}), + handle: async (_payload, _info, ctx) => { + const zone = ctx.config.DEFAULT_TIMEZONE; + const tomorrow = + DateTime.now().setZone(zone).plus({ days: 1 }).toISODate() ?? ''; + await forEachSubscription(ctx, async (subscription) => { + const { issues } = await redmine.listIssues({ + projectId: subscription.projectId, + dueDate: tomorrow, + limit: 50, + }); + for (const issue of issues.filter((i) => i.is_private !== true)) { + const url = new URL(`issues/${issue.id}`, root).href; + await sendOnce( + ctx, + subscription, + `due:${issue.id}:${tomorrow}`, + [ + `⏳ Due tomorrow: [#${issue.id}](${url}) ${issue.subject}`, + issue.assigned_to?.name, + ] + .filter(Boolean) + .join(' · '), + ); + } + }); + return { rescheduleAt: nextDailyRun(zone, deadlineHour) }; + }, + }); + + return { + jobs: [pollJob, deadlineJob], + start: async (ctx: AppContext) => { + await ctx.scheduler.schedule( + pollJob, + {}, + { runAt: new Date(Date.now() + 10_000), key: pollKey }, + ); + await ctx.scheduler.schedule( + deadlineJob, + {}, + { + runAt: nextDailyRun(ctx.config.DEFAULT_TIMEZONE, deadlineHour), + key: deadlineKey, + }, + ); + }, + }; +} diff --git a/src/features/redmine/redmine.test.ts b/src/features/redmine/redmine.test.ts new file mode 100644 index 0000000..dde73b4 --- /dev/null +++ b/src/features/redmine/redmine.test.ts @@ -0,0 +1,184 @@ +import { randomBytes } from 'node:crypto'; +import { pino } from 'pino'; +import { describe, expect, it, vi } from 'vitest'; +import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; +import type { Config } from '../../core/config.js'; +import type { AppContext } from '../../core/feature.js'; +import type { + RedmineClient, + RedmineIssue, +} from '../../integrations/redmine/client.js'; +import { createRedmineFeature } from './index.js'; +import { createNotificationJobs } from './notifications.js'; +import { + addSubscription, + issueNotifications, + listSubscriptions, +} from './service.js'; + +const since = new Date('2026-11-10T00:00:00Z'); +const statuses = new Map([ + [1, { id: 1, name: 'New' }], + [2, { id: 2, name: 'In Progress' }], +]); +const issue = (overrides: Partial = {}): RedmineIssue => ({ + id: 42, + project: { id: 1, name: 'Web' }, + tracker: { id: 1, name: 'Bug' }, + status: { id: 2, name: 'In Progress' }, + priority: { id: 2, name: 'Normal' }, + author: { id: 3, name: 'Mari' }, + assigned_to: { id: 5, name: 'Jaan' }, + subject: 'Fix login', + created_on: '2026-11-11T10:00:00Z', + updated_on: '2026-11-12T10:00:00Z', + journals: [], + ...overrides, +}); +const journal = (id: number, overrides: object) => ({ + id, + user: { id: 3, name: 'Mari' }, + created_on: '2026-11-12T10:00:00Z', + details: [], + ...overrides, +}); + +describe('issueNotifications', () => { + it('reports new issues, status changes, assignments and comments', () => { + const notifications = issueNotifications( + issue({ + journals: [ + journal(1, { + details: [ + { + property: 'attr', + name: 'status_id', + old_value: '1', + new_value: '2', + }, + ], + }), + journal(2, { + details: [ + { + property: 'attr', + name: 'assigned_to_id', + old_value: null, + new_value: '5', + }, + ], + }), + journal(3, { notes: 'Looks good' }), + journal(4, { created_on: '2026-11-01T00:00:00Z', notes: 'old' }), + ], + }), + since, + statuses, + 'https://r/issues/42', + ); + expect(notifications.map((n) => n.key)).toEqual([ + 'issue:42:created', + 'journal:1', + 'journal:2', + 'journal:3', + ]); + expect(notifications[1]?.text).toContain('status New → In Progress'); + expect(notifications[2]?.text).toContain('assigned to Jaan'); + expect(notifications[3]?.text).toContain('> Looks good'); + }); + + it('never reveals private issues or private notes', () => { + expect( + issueNotifications(issue({ is_private: true }), since, statuses, 'u'), + ).toEqual([]); + const notes = issueNotifications( + issue({ + created_on: '2026-01-01T00:00:00Z', + journals: [journal(9, { notes: 'secret', private_notes: true })], + }), + since, + statuses, + 'u', + ); + expect(notes).toEqual([]); + }); +}); + +describe('createRedmineFeature', () => { + it('is disabled without a base URL and requires an encryption key with one', () => { + expect(createRedmineFeature({} as Config)).toBeUndefined(); + expect(() => + createRedmineFeature({ REDMINE_BASE_URL: 'https://r' } as Config), + ).toThrow('CREDENTIAL_ENCRYPTION_KEY'); + const feature = createRedmineFeature({ + REDMINE_BASE_URL: 'https://r', + CREDENTIAL_ENCRYPTION_KEY: randomBytes(32).toString('base64'), + } as Config); + expect(feature?.jobs).toEqual([]); + }); +}); + +describe.skipIf(noDatabase)('redmine polling', () => { + it('notifies once per change and advances the checkpoint', async () => { + const db = testDb(); + const channelId = snowflake(); + await addSubscription(db, { + guildId: snowflake(), + channelId, + projectId: 1, + projectName: 'Web', + createdBy: 'u', + checkpoint: since, + }); + const full = issue({ journals: [journal(7, { notes: 'hi' })] }); + const redmine = { + listStatuses: vi.fn(async () => [...statuses.values()]), + listIssues: vi.fn(async () => ({ issues: [full], total: 1 })), + getIssue: vi.fn(async () => full), + } as unknown as RedmineClient; + const send = vi.fn(async () => undefined); + const ctx = { + db, + log: pino({ level: 'silent' }), + client: { + channels: { + fetch: async (id: string) => + id === channelId ? { isSendable: () => true, send } : null, + }, + }, + } as unknown as AppContext; + const [poll] = createNotificationJobs(redmine, 'https://r/').jobs; + const info = { id: 1, runAt: new Date(), attempt: 1 }; + + const outcome = await poll?.run({}, info, ctx); + await poll?.run({}, info, ctx); + const ours = send.mock.calls.length; + expect(ours).toBe(2); + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); + const subscriptions = await listSubscriptions(db, 0, 1000); + expect( + subscriptions + .find((s) => s.channelId === channelId) + ?.checkpoint.toISOString(), + ).toBe(full.updated_on.replace('Z', '.000Z')); + }); + + it('keeps going when one subscription fails', async () => { + const db = testDb(); + const redmine = { + listStatuses: vi.fn(async () => []), + listIssues: vi.fn(async () => { + throw new Error('boom'); + }), + } as unknown as RedmineClient; + const ctx = { + db, + log: pino({ level: 'silent' }), + client: { channels: { fetch: vi.fn() } }, + } as unknown as AppContext; + const [poll] = createNotificationJobs(redmine, 'https://r/').jobs; + await expect( + poll?.run({}, { id: 1, runAt: new Date(), attempt: 1 }, ctx), + ).resolves.toBeDefined(); + }); +}); diff --git a/src/features/redmine/schema.ts b/src/features/redmine/schema.ts new file mode 100644 index 0000000..59d4047 --- /dev/null +++ b/src/features/redmine/schema.ts @@ -0,0 +1,55 @@ +import { + integer, + pgTable, + primaryKey, + serial, + text, + timestamp, + unique, +} from 'drizzle-orm/pg-core'; + +/** API keys are stored encrypted with CREDENTIAL_ENCRYPTION_KEY. */ +export const redmineLinks = pgTable('redmine_links', { + userId: text('user_id').primaryKey(), + redmineUserId: integer('redmine_user_id').notNull(), + redmineLogin: text('redmine_login').notNull(), + encryptedApiKey: text('encrypted_api_key').notNull(), + linkedAt: timestamp('linked_at', { withTimezone: true }) + .notNull() + .defaultNow(), +}); + +export const redmineSubscriptions = pgTable( + 'redmine_subscriptions', + { + id: serial('id').primaryKey(), + guildId: text('guild_id').notNull(), + channelId: text('channel_id').notNull(), + projectId: integer('project_id').notNull(), + projectName: text('project_name').notNull(), + createdBy: text('created_by').notNull(), + /** Issues updated at or after this time have not been fully processed. */ + checkpoint: timestamp('checkpoint', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (table) => [ + unique('redmine_subscriptions_unique').on(table.channelId, table.projectId), + ], +); + +/** One row per notification sent, so overlapping polls never repeat one. */ +export const redmineNotifications = pgTable( + 'redmine_notifications', + { + subscriptionId: integer('subscription_id') + .notNull() + .references(() => redmineSubscriptions.id, { onDelete: 'cascade' }), + key: text('key').notNull(), + sentAt: timestamp('sent_at', { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [primaryKey({ columns: [table.subscriptionId, table.key] })], +); + +export type RedmineLink = typeof redmineLinks.$inferSelect; +export type RedmineSubscription = typeof redmineSubscriptions.$inferSelect; diff --git a/src/features/redmine/service.ts b/src/features/redmine/service.ts new file mode 100644 index 0000000..8ec5876 --- /dev/null +++ b/src/features/redmine/service.ts @@ -0,0 +1,179 @@ +import { and, asc, eq, gt } from 'drizzle-orm'; +import type { Db } from '../../db/client.js'; +import type { + RedmineIssue, + RedmineStatus, +} from '../../integrations/redmine/client.js'; +import { + redmineLinks, + redmineNotifications, + redmineSubscriptions, + type RedmineLink, +} from './schema.js'; + +export async function saveLink( + db: Db, + link: Omit, +): Promise { + await db + .insert(redmineLinks) + .values(link) + .onConflictDoUpdate({ + target: redmineLinks.userId, + set: { ...link, linkedAt: new Date() }, + }); +} + +export async function getLink( + db: Db, + userId: string, +): Promise { + const [row] = await db + .select() + .from(redmineLinks) + .where(eq(redmineLinks.userId, userId)); + return row; +} + +export async function deleteLink(db: Db, userId: string): Promise { + const rows = await db + .delete(redmineLinks) + .where(eq(redmineLinks.userId, userId)) + .returning({ userId: redmineLinks.userId }); + return rows.length > 0; +} + +export async function addSubscription( + db: Db, + input: typeof redmineSubscriptions.$inferInsert, +): Promise { + const rows = await db + .insert(redmineSubscriptions) + .values(input) + .onConflictDoNothing() + .returning({ id: redmineSubscriptions.id }); + return rows.length > 0; +} + +export async function removeSubscription( + db: Db, + guildId: string, + channelId: string, + projectId: number, +): Promise { + const rows = await db + .delete(redmineSubscriptions) + .where( + and( + eq(redmineSubscriptions.guildId, guildId), + eq(redmineSubscriptions.channelId, channelId), + eq(redmineSubscriptions.projectId, projectId), + ), + ) + .returning({ id: redmineSubscriptions.id }); + return rows.length > 0; +} + +/** Subscriptions in ID order, paged so each poll run stays bounded. */ +export async function listSubscriptions(db: Db, afterId = 0, limit = 50) { + return db + .select() + .from(redmineSubscriptions) + .where(gt(redmineSubscriptions.id, afterId)) + .orderBy(asc(redmineSubscriptions.id)) + .limit(limit); +} + +export async function setCheckpoint( + db: Db, + id: number, + checkpoint: Date, +): Promise { + await db + .update(redmineSubscriptions) + .set({ checkpoint }) + .where(eq(redmineSubscriptions.id, id)); +} + +/** Records a notification; false means it was already sent. */ +export async function claimNotification( + db: Db, + subscriptionId: number, + key: string, +): Promise { + const rows = await db + .insert(redmineNotifications) + .values({ subscriptionId, key }) + .onConflictDoNothing() + .returning({ key: redmineNotifications.key }); + return rows.length > 0; +} + +export type Notification = { key: string; text: string }; + +/** + * Turns an issue with journals into notifications for changes at or after + * `since`. Private issues and private notes are never included. + */ +export function issueNotifications( + issue: RedmineIssue, + since: Date, + statuses: ReadonlyMap, + issueUrl: string, +): Notification[] { + if (issue.is_private === true) { + return []; + } + const title = `[#${issue.id}](${issueUrl}) ${issue.subject}`; + const notifications: Notification[] = []; + if (new Date(issue.created_on) >= since) { + const assignee = issue.assigned_to + ? `, assigned to ${issue.assigned_to.name}` + : ''; + notifications.push({ + key: `issue:${issue.id}:created`, + text: `🆕 ${issue.tracker.name} ${title} by ${issue.author.name}${assignee}`, + }); + } + for (const journal of issue.journals ?? []) { + if ( + new Date(journal.created_on) < since || + journal.private_notes === true + ) { + continue; + } + const changes = journal.details.flatMap((detail) => { + if (detail.property !== 'attr') { + return []; + } + if (detail.name === 'status_id') { + const name = (id: string | null | undefined) => + statuses.get(Number(id))?.name ?? '?'; + return [`status ${name(detail.old_value)} → ${name(detail.new_value)}`]; + } + if (detail.name === 'assigned_to_id') { + const matches = + issue.assigned_to && + String(issue.assigned_to.id) === detail.new_value; + return [ + matches === true + ? `assigned to ${issue.assigned_to?.name ?? ''}` + : 'assignee changed', + ]; + } + return []; + }); + const notes = journal.notes?.trim() ?? ''; + if (changes.length === 0 && notes === '') { + continue; + } + const who = journal.user?.name ?? 'Someone'; + const comment = + notes === '' ? '' : `\n> ${notes.slice(0, 300).replaceAll('\n', '\n> ')}`; + notifications.push({ + key: `journal:${journal.id}`, + text: `✏️ ${title}: ${[who, ...changes].join(' · ')}${comment}`, + }); + } + return notifications; +} diff --git a/src/integrations/redmine/client.test.ts b/src/integrations/redmine/client.test.ts new file mode 100644 index 0000000..fec72f7 --- /dev/null +++ b/src/integrations/redmine/client.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi } from 'vitest'; +import { RedmineClient, RedmineError } from './client.js'; + +const issue = { + id: 7, + project: { id: 1, name: 'Web' }, + tracker: { id: 1, name: 'Bug' }, + status: { id: 1, name: 'New' }, + priority: { id: 2, name: 'Normal' }, + author: { id: 3, name: 'Mari' }, + subject: 'Fix login', + created_on: '2026-11-01T10:00:00Z', + updated_on: '2026-11-02T10:00:00Z', +}; + +const json = (status: number, body: unknown) => + new Response(body === undefined ? null : JSON.stringify(body), { status }); + +function client(...responses: Array) { + const fetch = vi.fn(); + for (const response of responses) { + if (response instanceof Error) { + fetch.mockRejectedValueOnce(response); + } else { + fetch.mockResolvedValueOnce(response); + } + } + return { + fetch, + redmine: new RedmineClient('https://redmine.example', 'secret', { fetch }), + }; +} + +const kind = async (promise: Promise) => { + try { + await promise; + } catch (error) { + return error instanceof RedmineError ? error.kind : 'other'; + } + return 'none'; +}; + +describe('RedmineClient', () => { + it('sends the API key and builds filtered issue queries', async () => { + const { fetch, redmine } = client( + json(200, { issues: [issue], total_count: 1 }), + ); + const result = await redmine.listIssues({ + projectId: 'web', + assignedToMe: true, + updatedSince: new Date('2026-11-01T10:00:00.123Z'), + }); + expect(result.issues[0]?.subject).toBe('Fix login'); + const [input, init] = fetch.mock.calls[0] ?? []; + const url = input instanceof URL ? input.href : ''; + expect(url).toContain('project_id=web'); + expect(url).toContain('assigned_to_id=me'); + expect(decodeURIComponent(url)).toContain( + 'updated_on=>=2026-11-01T10:00:00Z', + ); + expect(new Headers(init?.headers).get('X-Redmine-API-Key')).toBe('secret'); + }); + + it('rejects responses that do not match the expected shape', async () => { + const { redmine } = client(json(200, { issue: { id: 'seven' } })); + expect(await kind(redmine.getIssue(7))).toBe('invalid_response'); + }); + + it.each([ + [401, 'auth'], + [403, 'forbidden'], + [404, 'not_found'], + ])('maps HTTP %i to %s', async (status, expected) => { + const { redmine } = client(json(status, {})); + expect(await kind(redmine.currentUser())).toBe(expected); + }); + + it('reports validation errors from Redmine', async () => { + const { redmine } = client( + json(422, { errors: ['Subject cannot be blank'] }), + ); + await expect( + redmine.createIssue({ project_id: 1, subject: '' }), + ).rejects.toThrow('Subject cannot be blank'); + }); + + it('retries reads once on timeouts but never retries writes', async () => { + const timeout = new DOMException('timed out', 'TimeoutError'); + const read = client(timeout, json(200, { user: { id: 1, login: 'mari' } })); + expect((await read.redmine.currentUser()).login).toBe('mari'); + expect(read.fetch).toHaveBeenCalledTimes(2); + + const write = client(timeout, json(204, undefined)); + expect(await kind(write.redmine.updateIssue(7, { notes: 'hi' }))).toBe( + 'unavailable', + ); + expect(write.fetch).toHaveBeenCalledOnce(); + }); + + it('treats server errors as unavailable', async () => { + const { redmine } = client(json(502, {}), json(503, {})); + expect(await kind(redmine.listProjects())).toBe('unavailable'); + }); +}); diff --git a/src/integrations/redmine/client.ts b/src/integrations/redmine/client.ts new file mode 100644 index 0000000..e7b58ec --- /dev/null +++ b/src/integrations/redmine/client.ts @@ -0,0 +1,317 @@ +import { z } from 'zod'; + +const named = z.object({ id: z.number(), name: z.string() }); + +const userSchema = z.object({ + id: z.number(), + login: z.string(), + firstname: z.string().optional(), + lastname: z.string().optional(), +}); + +const projectSchema = z.object({ + id: z.number(), + name: z.string(), + identifier: z.string(), + description: z.string().nullish(), +}); + +const journalSchema = z.object({ + id: z.number(), + user: named.optional(), + notes: z.string().nullish(), + private_notes: z.boolean().optional(), + created_on: z.string(), + details: z + .array( + z.object({ + property: z.string(), + name: z.string(), + old_value: z.string().nullish(), + new_value: z.string().nullish(), + }), + ) + .default([]), +}); + +const issueSchema = z.object({ + id: z.number(), + project: named, + tracker: named, + status: named.extend({ is_closed: z.boolean().optional() }), + priority: named, + author: named, + assigned_to: named.optional(), + subject: z.string(), + description: z.string().nullish(), + due_date: z.string().nullish(), + done_ratio: z.number().optional(), + is_private: z.boolean().optional(), + created_on: z.string(), + updated_on: z.string(), + journals: z.array(journalSchema).optional(), +}); + +const statusSchema = z.object({ + id: z.number(), + name: z.string(), + is_closed: z.boolean().optional(), +}); + +const projectsPage = z.object({ + projects: z.array(projectSchema), + total_count: z.number().optional(), +}); +const issuesPage = z.object({ + issues: z.array(issueSchema), + total_count: z.number().optional(), +}); + +export type RedmineUser = z.infer; +export type RedmineProject = z.infer; +export type RedmineIssue = z.infer; +export type RedmineJournal = z.infer; +export type RedmineStatus = z.infer; + +export type RedmineErrorKind = + | 'auth' + | 'forbidden' + | 'not_found' + | 'validation' + | 'unavailable' + | 'invalid_response'; + +/** A normalised Redmine failure. `message` is safe to show to users. */ +export class RedmineError extends Error { + override readonly name = 'RedmineError'; + constructor( + readonly kind: RedmineErrorKind, + message: string, + ) { + super(message); + } +} + +export type IssueQuery = { + projectId?: number | string; + assignedToMe?: boolean; + status?: 'open' | 'closed' | '*'; + updatedSince?: Date; + dueDate?: string; + sort?: string; + offset?: number; + limit?: number; +}; + +export type IssueChanges = { + subject?: string; + description?: string; + status_id?: number; + assigned_to_id?: number; + notes?: string; +}; + +type Request = { + method?: 'GET' | 'POST' | 'PUT'; + body?: unknown; + query?: Record; +}; + +const messages: Record = { + 401: [ + 'auth', + 'Redmine rejected the API key. Link your account again with `/redmine link`.', + ], + 403: ['forbidden', 'Your Redmine account is not allowed to do that.'], + 404: ['not_found', 'Redmine could not find that (or you cannot see it).'], +}; + +/** Redmine timestamps are second precision; this is the format its filters accept. */ +const redmineTime = (date: Date) => `${date.toISOString().slice(0, 19)}Z`; + +export class RedmineClient { + constructor( + private readonly baseUrl: string, + private readonly apiKey: string, + private readonly options: { timeoutMs?: number; fetch?: typeof fetch } = {}, + ) {} + + private async request(path: string, request: Request = {}): Promise { + const url = new URL( + path, + this.baseUrl.endsWith('/') ? this.baseUrl : `${this.baseUrl}/`, + ); + for (const [key, value] of Object.entries(request.query ?? {})) { + url.searchParams.set(key, value); + } + const method = request.method ?? 'GET'; + // Only reads are retried; repeating a write could apply it twice. + const attempts = method === 'GET' ? 2 : 1; + for (let attempt = 1; ; attempt++) { + try { + return await this.send(url, method, request.body); + } catch (error) { + if ( + !(error instanceof RedmineError && error.kind === 'unavailable') || + attempt >= attempts + ) { + throw error; + } + } + } + } + + private async send( + url: URL, + method: string, + body: unknown, + ): Promise { + let response: Response; + try { + response = await (this.options.fetch ?? fetch)(url, { + method, + headers: { + 'X-Redmine-API-Key': this.apiKey, + Accept: 'application/json', + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + signal: AbortSignal.timeout(this.options.timeoutMs ?? 10_000), + }); + } catch { + throw new RedmineError('unavailable', 'Redmine did not respond in time.'); + } + if (response.status === 422) { + const parsed = z + .object({ errors: z.array(z.string()) }) + .safeParse(await response.json().catch(() => null)); + throw new RedmineError( + 'validation', + parsed.success + ? parsed.data.errors.join('; ') + : 'Redmine rejected the request.', + ); + } + const known = messages[response.status]; + if (known) { + throw new RedmineError(...known); + } + if (!response.ok) { + throw new RedmineError( + 'unavailable', + `Redmine is unavailable (HTTP ${response.status}).`, + ); + } + const text = await response.text(); + return text === '' ? null : JSON.parse(text); + } + + private async get( + path: string, + schema: T, + query?: Record, + ): Promise> { + const parsed = schema.safeParse( + await this.request(path, query === undefined ? {} : { query }), + ); + if (!parsed.success) { + throw new RedmineError( + 'invalid_response', + 'Redmine sent a response I do not understand.', + ); + } + return parsed.data; + } + + async currentUser(): Promise { + const data = await this.get( + 'users/current.json', + z.object({ user: userSchema }), + ); + return data.user; + } + + async listProjects( + offset = 0, + limit = 25, + ): Promise<{ projects: RedmineProject[]; total: number }> { + const data = await this.get('projects.json', projectsPage, { + offset: String(offset), + limit: String(Math.min(limit, 100)), + }); + return { + projects: data.projects, + total: data.total_count ?? data.projects.length, + }; + } + + async listIssues( + query: IssueQuery = {}, + ): Promise<{ issues: RedmineIssue[]; total: number }> { + const params: Record = { + status_id: query.status ?? 'open', + sort: query.sort ?? 'updated_on:desc', + offset: String(query.offset ?? 0), + limit: String(Math.min(query.limit ?? 25, 100)), + }; + if (query.projectId !== undefined) { + params.project_id = String(query.projectId); + } + if (query.assignedToMe === true) { + params.assigned_to_id = 'me'; + } + if (query.updatedSince) { + params.updated_on = `>=${redmineTime(query.updatedSince)}`; + } + if (query.dueDate !== undefined) { + params.due_date = query.dueDate; + } + const data = await this.get('issues.json', issuesPage, params); + return { + issues: data.issues, + total: data.total_count ?? data.issues.length, + }; + } + + async getIssue(id: number, withJournals = false): Promise { + const query = withJournals ? { include: 'journals' } : undefined; + const data = await this.get( + `issues/${id}.json`, + z.object({ issue: issueSchema }), + query, + ); + return data.issue; + } + + async listStatuses(): Promise { + const data = await this.get( + 'issue_statuses.json', + z.object({ issue_statuses: z.array(statusSchema) }), + ); + return data.issue_statuses; + } + + async createIssue( + fields: IssueChanges & { project_id: number | string; subject: string }, + ): Promise { + const data = await this.request('issues.json', { + method: 'POST', + body: { issue: fields }, + }); + const parsed = z.object({ issue: issueSchema }).safeParse(data); + if (!parsed.success) { + throw new RedmineError( + 'invalid_response', + 'Redmine created the issue but sent an unexpected response.', + ); + } + return parsed.data.issue; + } + + async updateIssue(id: number, changes: IssueChanges): Promise { + await this.request(`issues/${id}.json`, { + method: 'PUT', + body: { issue: changes }, + }); + } +} diff --git a/src/shared/crypto.test.ts b/src/shared/crypto.test.ts new file mode 100644 index 0000000..c3b2b72 --- /dev/null +++ b/src/shared/crypto.test.ts @@ -0,0 +1,28 @@ +import { randomBytes } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { createSecretBox } from './crypto.js'; + +describe('createSecretBox', () => { + const box = createSecretBox(randomBytes(32).toString('base64')); + + it('round-trips without leaking the plaintext', () => { + const sealed = box.encrypt('api-key-123'); + expect(sealed).not.toContain('api-key-123'); + expect(box.encrypt('api-key-123')).not.toBe(sealed); + expect(box.decrypt(sealed)).toBe('api-key-123'); + }); + + it('refuses tampered values and other keys', () => { + const sealed = box.encrypt('api-key-123'); + const parts = sealed.split(':'); + const tampered = [ + ...parts.slice(0, 3), + Buffer.from('x').toString('base64'), + ].join(':'); + expect(() => box.decrypt(tampered)).toThrow(); + expect(() => + createSecretBox(randomBytes(32).toString('base64')).decrypt(sealed), + ).toThrow(); + expect(() => createSecretBox('short')).toThrow('32 bytes'); + }); +}); diff --git a/src/shared/crypto.ts b/src/shared/crypto.ts new file mode 100644 index 0000000..9759666 --- /dev/null +++ b/src/shared/crypto.ts @@ -0,0 +1,52 @@ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; + +const version = 'v1'; + +/** + * AES-256-GCM with a key held outside the database. The output carries its + * own IV and auth tag, so tampered or wrongly keyed values fail to decrypt. + */ +export function createSecretBox(base64Key: string) { + const key = Buffer.from(base64Key, 'base64'); + if (key.length !== 32) { + throw new Error('Encryption key must be 32 bytes'); + } + return { + encrypt: (plaintext: string): string => { + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', key, iv); + const data = Buffer.concat([ + cipher.update(plaintext, 'utf8'), + cipher.final(), + ]); + return [version, iv, cipher.getAuthTag(), data] + .map((part) => + typeof part === 'string' ? part : part.toString('base64'), + ) + .join(':'); + }, + decrypt: (sealed: string): string => { + const [prefix, iv, tag, data] = sealed.split(':'); + if ( + prefix !== version || + iv === undefined || + tag === undefined || + data === undefined + ) { + throw new Error('Unrecognised secret format'); + } + const decipher = createDecipheriv( + 'aes-256-gcm', + key, + Buffer.from(iv, 'base64'), + ); + decipher.setAuthTag(Buffer.from(tag, 'base64')); + return Buffer.concat([ + decipher.update(Buffer.from(data, 'base64')), + decipher.final(), + ]).toString('utf8'); + }, + }; +} + +export type SecretBox = ReturnType; From 24af986e647a64b99825f23b6f679b963df93f02 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 013/199] feat: wire features into the app and add command registration --- drizzle.config.ts | 11 + drizzle/0000_init.sql | 241 +++++ drizzle/meta/0000_snapshot.json | 1647 +++++++++++++++++++++++++++++++ drizzle/meta/_journal.json | 13 + scripts/register-commands.ts | 18 + src/app.ts | 130 +++ src/index.ts | 40 + tests/app.test.ts | 73 ++ 8 files changed, 2173 insertions(+) create mode 100644 drizzle.config.ts create mode 100644 drizzle/0000_init.sql create mode 100644 drizzle/meta/0000_snapshot.json create mode 100644 drizzle/meta/_journal.json create mode 100644 scripts/register-commands.ts create mode 100644 src/app.ts create mode 100644 src/index.ts create mode 100644 tests/app.test.ts diff --git a/drizzle.config.ts b/drizzle.config.ts new file mode 100644 index 0000000..c122bfb --- /dev/null +++ b/drizzle.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'drizzle-kit'; + +export default defineConfig({ + dialect: 'postgresql', + schema: [ + './src/core/**/schema.ts', + './src/core/guild-settings.ts', + './src/features/*/schema.ts', + ], + out: './drizzle', +}); diff --git a/drizzle/0000_init.sql b/drizzle/0000_init.sql new file mode 100644 index 0000000..338625f --- /dev/null +++ b/drizzle/0000_init.sql @@ -0,0 +1,241 @@ +CREATE TYPE "public"."job_status" AS ENUM('pending', 'running', 'done', 'failed', 'cancelled');--> statement-breakpoint +CREATE TYPE "public"."announcement_status" AS ENUM('draft', 'scheduled', 'publishing', 'published', 'cancelled', 'failed');--> statement-breakpoint +CREATE TYPE "public"."birthday_visibility" AS ENUM('public', 'announce', 'private');--> statement-breakpoint +CREATE TYPE "public"."event_status" AS ENUM('scheduled', 'cancelled');--> statement-breakpoint +CREATE TYPE "public"."rsvp_status" AS ENUM('going', 'maybe', 'not_going');--> statement-breakpoint +CREATE TYPE "public"."poll_result_visibility" AS ENUM('live', 'closed');--> statement-breakpoint +CREATE TYPE "public"."poll_status" AS ENUM('open', 'closed', 'cancelled');--> statement-breakpoint +CREATE TYPE "public"."reminder_recurrence" AS ENUM('daily', 'weekly', 'monthly');--> statement-breakpoint +CREATE TYPE "public"."reminder_status" AS ENUM('active', 'done', 'cancelled', 'failed');--> statement-breakpoint +CREATE TYPE "public"."role_panel_kind" AS ENUM('reaction', 'select');--> statement-breakpoint +CREATE TABLE "role_permissions" ( + "guild_id" text NOT NULL, + "role_id" text NOT NULL, + "permission" text NOT NULL, + "granted_by" text NOT NULL, + "granted_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "role_permissions_guild_id_role_id_permission_pk" PRIMARY KEY("guild_id","role_id","permission") +); +--> statement-breakpoint +CREATE TABLE "scheduled_jobs" ( + "id" bigserial PRIMARY KEY NOT NULL, + "type" text NOT NULL, + "payload" jsonb NOT NULL, + "run_at" timestamp with time zone NOT NULL, + "status" "job_status" DEFAULT 'pending' NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "max_attempts" integer DEFAULT 5 NOT NULL, + "locked_until" timestamp with time zone, + "last_error" text, + "key" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "finished_at" timestamp with time zone, + CONSTRAINT "scheduled_jobs_key_unique" UNIQUE("key") +); +--> statement-breakpoint +CREATE TABLE "guild_settings" ( + "guild_id" text PRIMARY KEY NOT NULL, + "timezone" text, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "announcements" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "author_id" text NOT NULL, + "channel_id" text NOT NULL, + "title" text, + "content" text NOT NULL, + "embed" boolean DEFAULT true NOT NULL, + "mention_role_id" text, + "status" "announcement_status" DEFAULT 'draft' NOT NULL, + "scheduled_at" timestamp with time zone, + "published_at" timestamp with time zone, + "message_id" text, + "failure" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "birthday_settings" ( + "guild_id" text PRIMARY KEY NOT NULL, + "channel_id" text NOT NULL, + "role_id" text, + "hour" smallint DEFAULT 9 NOT NULL +); +--> statement-breakpoint +CREATE TABLE "birthdays" ( + "guild_id" text NOT NULL, + "user_id" text NOT NULL, + "month" smallint NOT NULL, + "day" smallint NOT NULL, + "visibility" "birthday_visibility" DEFAULT 'public' NOT NULL, + "last_announced_year" integer, + CONSTRAINT "birthdays_guild_id_user_id_pk" PRIMARY KEY("guild_id","user_id") +); +--> statement-breakpoint +CREATE TABLE "event_rsvps" ( + "event_id" integer NOT NULL, + "user_id" text NOT NULL, + "status" "rsvp_status" NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "event_rsvps_event_id_user_id_pk" PRIMARY KEY("event_id","user_id") +); +--> statement-breakpoint +CREATE TABLE "events" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "title" text NOT NULL, + "description" text, + "starts_at" timestamp with time zone NOT NULL, + "ends_at" timestamp with time zone, + "timezone" text NOT NULL, + "location" text, + "organizer_id" text NOT NULL, + "channel_id" text NOT NULL, + "message_id" text, + "capacity" integer, + "mention_role_id" text, + "reminder_minutes" integer[] DEFAULT '{}' NOT NULL, + "discord_event_id" text, + "status" "event_status" DEFAULT 'scheduled' NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "movie_screenings" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "suggestion_id" integer NOT NULL, + "event_id" integer, + "poll_id" integer, + "scheduled_for" timestamp with time zone, + "watched_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "movie_suggestions" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "title" text NOT NULL, + "normalized_title" text NOT NULL, + "year" smallint, + "note" text, + "suggested_by" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "removed_at" timestamp with time zone +); +--> statement-breakpoint +CREATE TABLE "poll_options" ( + "id" serial PRIMARY KEY NOT NULL, + "poll_id" integer NOT NULL, + "position" integer NOT NULL, + "label" text NOT NULL, + "ref" text, + CONSTRAINT "poll_options_position_unique" UNIQUE("poll_id","position") +); +--> statement-breakpoint +CREATE TABLE "poll_votes" ( + "poll_id" integer NOT NULL, + "option_id" integer NOT NULL, + "user_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "poll_votes_poll_id_user_id_option_id_pk" PRIMARY KEY("poll_id","user_id","option_id") +); +--> statement-breakpoint +CREATE TABLE "polls" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "channel_id" text NOT NULL, + "message_id" text, + "creator_id" text NOT NULL, + "question" text NOT NULL, + "multiple" boolean DEFAULT false NOT NULL, + "anonymous" boolean DEFAULT false NOT NULL, + "show_results" "poll_result_visibility" DEFAULT 'live' NOT NULL, + "closes_at" timestamp with time zone, + "status" "poll_status" DEFAULT 'open' NOT NULL, + "source" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "redmine_links" ( + "user_id" text PRIMARY KEY NOT NULL, + "redmine_user_id" integer NOT NULL, + "redmine_login" text NOT NULL, + "encrypted_api_key" text NOT NULL, + "linked_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "redmine_notifications" ( + "subscription_id" integer NOT NULL, + "key" text NOT NULL, + "sent_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "redmine_notifications_subscription_id_key_pk" PRIMARY KEY("subscription_id","key") +); +--> statement-breakpoint +CREATE TABLE "redmine_subscriptions" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "channel_id" text NOT NULL, + "project_id" integer NOT NULL, + "project_name" text NOT NULL, + "created_by" text NOT NULL, + "checkpoint" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "redmine_subscriptions_unique" UNIQUE("channel_id","project_id") +); +--> statement-breakpoint +CREATE TABLE "reminders" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "user_id" text NOT NULL, + "channel_id" text, + "message" text NOT NULL, + "run_at" timestamp with time zone NOT NULL, + "recurrence" "reminder_recurrence", + "timezone" text NOT NULL, + "status" "reminder_status" DEFAULT 'active' NOT NULL, + "failure" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "role_panel_roles" ( + "panel_id" integer NOT NULL, + "role_id" text NOT NULL, + "label" text NOT NULL, + "emoji" text, + "position" integer NOT NULL, + CONSTRAINT "role_panel_roles_panel_id_role_id_pk" PRIMARY KEY("panel_id","role_id") +); +--> statement-breakpoint +CREATE TABLE "role_panels" ( + "id" serial PRIMARY KEY NOT NULL, + "guild_id" text NOT NULL, + "channel_id" text NOT NULL, + "message_id" text, + "kind" "role_panel_kind" NOT NULL, + "title" text NOT NULL, + "created_by" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "role_panels_message_id_unique" UNIQUE("message_id") +); +--> statement-breakpoint +ALTER TABLE "event_rsvps" ADD CONSTRAINT "event_rsvps_event_id_events_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."events"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "movie_screenings" ADD CONSTRAINT "movie_screenings_suggestion_id_movie_suggestions_id_fk" FOREIGN KEY ("suggestion_id") REFERENCES "public"."movie_suggestions"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "poll_options" ADD CONSTRAINT "poll_options_poll_id_polls_id_fk" FOREIGN KEY ("poll_id") REFERENCES "public"."polls"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "poll_votes" ADD CONSTRAINT "poll_votes_poll_id_polls_id_fk" FOREIGN KEY ("poll_id") REFERENCES "public"."polls"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "poll_votes" ADD CONSTRAINT "poll_votes_option_id_poll_options_id_fk" FOREIGN KEY ("option_id") REFERENCES "public"."poll_options"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "redmine_notifications" ADD CONSTRAINT "redmine_notifications_subscription_id_redmine_subscriptions_id_fk" FOREIGN KEY ("subscription_id") REFERENCES "public"."redmine_subscriptions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "role_panel_roles" ADD CONSTRAINT "role_panel_roles_panel_id_role_panels_id_fk" FOREIGN KEY ("panel_id") REFERENCES "public"."role_panels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "scheduled_jobs_due_idx" ON "scheduled_jobs" USING btree ("run_at") WHERE "scheduled_jobs"."status" = 'pending';--> statement-breakpoint +CREATE INDEX "scheduled_jobs_lease_idx" ON "scheduled_jobs" USING btree ("locked_until") WHERE "scheduled_jobs"."status" = 'running';--> statement-breakpoint +CREATE INDEX "announcements_guild_idx" ON "announcements" USING btree ("guild_id","status");--> statement-breakpoint +CREATE INDEX "birthdays_date_idx" ON "birthdays" USING btree ("guild_id","month","day");--> statement-breakpoint +CREATE INDEX "event_rsvps_status_idx" ON "event_rsvps" USING btree ("event_id","status");--> statement-breakpoint +CREATE INDEX "events_guild_start_idx" ON "events" USING btree ("guild_id","starts_at");--> statement-breakpoint +CREATE INDEX "movie_screenings_guild_idx" ON "movie_screenings" USING btree ("guild_id","watched_at");--> statement-breakpoint +CREATE UNIQUE INDEX "movie_suggestions_unique_idx" ON "movie_suggestions" USING btree ("guild_id","normalized_title") WHERE "movie_suggestions"."removed_at" IS NULL;--> statement-breakpoint +CREATE INDEX "poll_votes_option_idx" ON "poll_votes" USING btree ("option_id");--> statement-breakpoint +CREATE INDEX "polls_guild_status_idx" ON "polls" USING btree ("guild_id","status");--> statement-breakpoint +CREATE INDEX "polls_source_idx" ON "polls" USING btree ("guild_id","source","created_at");--> statement-breakpoint +CREATE INDEX "reminders_user_idx" ON "reminders" USING btree ("guild_id","user_id","status");--> statement-breakpoint +CREATE INDEX "role_panels_guild_idx" ON "role_panels" USING btree ("guild_id");--> statement-breakpoint +CREATE UNIQUE INDEX "role_panels_reaction_channel_idx" ON "role_panels" USING btree ("guild_id","channel_id") WHERE "role_panels"."kind" = 'reaction'; \ No newline at end of file diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json new file mode 100644 index 0000000..7fae61a --- /dev/null +++ b/drizzle/meta/0000_snapshot.json @@ -0,0 +1,1647 @@ +{ + "id": "80864efc-f688-4b13-b99f-0388ac6e9a92", + "prevId": "00000000-0000-0000-0000-000000000000", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": ["guild_id", "role_id", "permission"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_jobs": { + "name": "scheduled_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "job_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "scheduled_jobs_due_idx": { + "name": "scheduled_jobs_due_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_jobs_lease_idx": { + "name": "scheduled_jobs_lease_idx", + "columns": [ + { + "expression": "locked_until", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "scheduled_jobs_key_unique": { + "name": "scheduled_jobs_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guild_settings": { + "name": "guild_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embed": { + "name": "embed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": ["guild_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": ["event_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": ["event_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": ["suggestion_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": ["poll_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": ["poll_id", "position"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": ["poll_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": ["option_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": ["poll_id", "user_id", "option_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_links": { + "name": "redmine_links", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "redmine_user_id": { + "name": "redmine_user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redmine_login": { + "name": "redmine_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "linked_at": { + "name": "linked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": ["subscription_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": ["subscription_id", "key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": ["channel_id", "project_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": ["panel_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": ["panel_id", "role_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": ["message_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.job_status": { + "name": "job_status", + "schema": "public", + "values": ["pending", "running", "done", "failed", "cancelled"] + }, + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "publishing", + "published", + "cancelled", + "failed" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": ["public", "announce", "private"] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": ["scheduled", "cancelled"] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": ["going", "maybe", "not_going"] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": ["live", "closed"] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": ["open", "closed", "cancelled"] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": ["daily", "weekly", "monthly"] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": ["active", "done", "cancelled", "failed"] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": ["reaction", "select"] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json new file mode 100644 index 0000000..62af31b --- /dev/null +++ b/drizzle/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "postgresql", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1794742755691, + "tag": "0000_init", + "breakpoints": true + } + ] +} diff --git a/scripts/register-commands.ts b/scripts/register-commands.ts new file mode 100644 index 0000000..cb7c0f9 --- /dev/null +++ b/scripts/register-commands.ts @@ -0,0 +1,18 @@ +import { createRegistry } from '../src/app.js'; +import { loadConfig } from '../src/core/config.js'; +import { registerCommands } from '../src/core/discord/registration.js'; + +const config = loadConfig(); +if (config.DISCORD_APPLICATION_ID === undefined) { + throw new Error('DISCORD_APPLICATION_ID is required to register commands'); +} +const count = await registerCommands(createRegistry(config), { + token: config.DISCORD_TOKEN, + applicationId: config.DISCORD_APPLICATION_ID, + guildId: config.DISCORD_GUILD_ID, +}); +const scope = + config.DISCORD_GUILD_ID === undefined + ? 'globally' + : `in guild ${config.DISCORD_GUILD_ID}`; +console.log(`Registered ${count} commands ${scope}.`); diff --git a/src/app.ts b/src/app.ts new file mode 100644 index 0000000..cf78038 --- /dev/null +++ b/src/app.ts @@ -0,0 +1,130 @@ +import { Events, type Client } from 'discord.js'; +import type { Config } from './core/config.js'; +import { createClient } from './core/discord/client.js'; +import { createInteractionHandler } from './core/discord/router.js'; +import type { AppContext, Feature } from './core/feature.js'; +import type { Logger } from './core/logger.js'; +import { createAuthorizer } from './core/permissions/authorizer.js'; +import { buildRegistry, type Registry } from './core/registry.js'; +import { createScheduler } from './core/scheduler/scheduler.js'; +import { connectDatabase, runMigrations } from './db/client.js'; +import { announcementsFeature } from './features/announcements/index.js'; +import { birthdaysFeature } from './features/birthdays/index.js'; +import { eventsFeature } from './features/events/index.js'; +import { moviesFeature } from './features/movies/index.js'; +import { createPermissionsFeature } from './features/permissions/index.js'; +import { pollsFeature } from './features/polls/index.js'; +import { createRedmineFeature } from './features/redmine/index.js'; +import { remindersFeature } from './features/reminders/index.js'; +import { rolesFeature } from './features/roles/index.js'; +import { settingsFeature } from './features/settings/index.js'; + +/** + * The composition root: every feature the bot runs is listed here. Removing + * a line disables that feature; its pending jobs stay in the database. + */ +export function createRegistry(config: Config): Registry { + const features: Feature[] = [ + rolesFeature, + createPermissionsFeature(() => registry.permissions), + settingsFeature, + remindersFeature, + announcementsFeature, + eventsFeature, + birthdaysFeature, + pollsFeature, + moviesFeature, + ]; + const redmine = createRedmineFeature(config); + if (redmine) { + features.push(redmine); + } + const registry = buildRegistry(features); + return registry; +} + +function waitForReady(client: Client, token: string): Promise> { + return new Promise((resolve, reject) => { + client.once(Events.ClientReady, resolve); + client.login(token).catch(reject); + }); +} + +/** Starts the bot and returns a function that shuts it down gracefully. */ +export async function startApp( + config: Config, + log: Logger, +): Promise<() => Promise> { + const registry = createRegistry(config); + const database = connectDatabase(config.DATABASE_URL); + const client = createClient(); + + try { + await runMigrations(database.db); + const scheduler = createScheduler( + database.db, + registry.jobs, + log.child({ component: 'scheduler' }), + ); + const ready = await waitForReady(client, config.DISCORD_TOKEN); + const ctx: AppContext = { + client: ready, + db: database.db, + log, + config, + authz: createAuthorizer(database.db), + scheduler, + }; + + for (const feature of registry.features) { + for (const listener of feature.events ?? []) { + listener.attach(client, { + ...ctx, + log: log.child({ feature: feature.name }), + }); + } + } + const handleInteraction = createInteractionHandler(registry, ctx); + client.on(Events.InteractionCreate, (interaction) => { + handleInteraction(interaction).catch((error: unknown) => { + log.error({ err: error }, 'Interaction handler crashed'); + }); + }); + client.on(Events.Error, (error) => { + log.error({ err: error }, 'Discord client error'); + }); + + // A feature that fails to start is logged, not fatal to the others. + await Promise.all( + registry.features.map(async (feature) => { + try { + await feature.start?.({ + ...ctx, + log: log.child({ feature: feature.name }), + }); + } catch (error) { + log.error( + { err: error, feature: feature.name }, + 'Feature failed to start', + ); + } + }), + ); + scheduler.start(ctx); + log.info( + { user: ready.user.tag, features: registry.features.map((f) => f.name) }, + 'Ready', + ); + + return async () => { + client.removeAllListeners(Events.InteractionCreate); + await scheduler.stop(); + await client.destroy(); + await database.close(); + }; + } catch (error) { + await client.destroy(); + await database.close(); + throw error; + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..a9b2121 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,40 @@ +import { startApp } from './app.js'; +import { loadConfig } from './core/config.js'; +import { createLogger } from './core/logger.js'; + +let config: ReturnType; +try { + config = loadConfig(); +} catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exit(1); +} +const log = createLogger(config.LOG_LEVEL); + +process.on('unhandledRejection', (reason) => { + log.error({ err: reason }, 'Unhandled promise rejection'); +}); + +try { + const stop = await startApp(config, log); + let stopping = false; + const shutdown = (signal: NodeJS.Signals) => { + if (stopping) { + return; + } + stopping = true; + log.info({ signal }, 'Shutting down'); + stop().then( + () => process.exit(0), + (error: unknown) => { + log.error({ err: error }, 'Shutdown failed'); + process.exit(1); + }, + ); + }; + process.once('SIGINT', shutdown); + process.once('SIGTERM', shutdown); +} catch (error) { + log.fatal({ err: error }, 'Startup failed'); + process.exitCode = 1; +} diff --git a/tests/app.test.ts b/tests/app.test.ts new file mode 100644 index 0000000..bd5f3da --- /dev/null +++ b/tests/app.test.ts @@ -0,0 +1,73 @@ +import type { + APIApplicationCommandOption, + RESTPostAPIChatInputApplicationCommandsJSONBody, +} from 'discord.js'; +import { describe, expect, it } from 'vitest'; +import { createRegistry } from '../src/app.js'; +import type { Config } from '../src/core/config.js'; + +const config = { DEFAULT_TIMEZONE: 'Europe/Tallinn' } as Config; + +/** Rules Discord enforces when commands are registered. */ +function problems( + path: string, + options: readonly APIApplicationCommandOption[] = [], +): string[] { + const found: string[] = []; + if (options.length > 25) { + found.push(`${path}: more than 25 options`); + } + let optionalSeen = false; + for (const option of options) { + const name = `${path} ${option.name}`; + if (!/^[\p{Ll}\p{N}_-]{1,32}$/u.test(option.name)) { + found.push(`${name}: invalid name`); + } + if (option.description.length === 0 || option.description.length > 100) { + found.push(`${name}: description must be 1-100 characters`); + } + if ('options' in option) { + found.push(...problems(name, option.options)); + continue; + } + const required = 'required' in option && option.required; + if (required && optionalSeen) { + found.push(`${name}: required option after an optional one`); + } + optionalSeen ||= !required; + } + return found; +} + +describe('composition root', () => { + const registry = createRegistry(config); + + it('builds without duplicate handlers', () => { + expect(registry.features.map((f) => f.name)).toContain('roles'); + expect(registry.commands.size).toBeGreaterThan(5); + }); + + it('declares commands Discord will accept', () => { + const commands = [...registry.commands.values()].map( + (c): RESTPostAPIChatInputApplicationCommandsJSONBody => c.data, + ); + expect(commands.flatMap((c) => problems(`/${c.name}`, c.options))).toEqual( + [], + ); + }); + + it('only requires permissions that some feature declares', () => { + const declared = new Set(registry.permissions.keys()); + const used = [...registry.commands.values()].flatMap((c) => + Object.values(c.permissions ?? {}), + ); + const usedByComponents = [...registry.components.values()].flatMap( + (c) => c.permission ?? [], + ); + expect( + [...used, ...usedByComponents].filter( + (p) => p !== undefined && !declared.has(p), + ), + ).toEqual([]); + }); +}); From c4a634c178f8dae73d906efde058c27351c46d13 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 014/199] chore: Docker, Compose and CI --- .dockerignore | 6 ++++++ .env.example | 29 +++++++++++++++++++++++++++++ .github/workflows/ci.yml | 36 ++++++++++++++++++++++++++++++++++++ Dockerfile | 24 ++++++++++++++++++++++++ compose.dev.yaml | 6 ++++++ compose.yaml | 30 ++++++++++++++++++++++++++++++ 6 files changed, 131 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 Dockerfile create mode 100644 compose.dev.yaml create mode 100644 compose.yaml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..94101b0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +node_modules +dist +coverage +.env +.git +PLAN.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..aece95f --- /dev/null +++ b/.env.example @@ -0,0 +1,29 @@ +# Required +DISCORD_TOKEN= +DATABASE_URL=postgres://lapbot:lapbot@localhost:5432/lapbot + +# Needed by `pnpm commands:register`. With DISCORD_GUILD_ID set, commands are +# registered to that server only and update instantly. +DISCORD_APPLICATION_ID= +DISCORD_GUILD_ID= + +LOG_LEVEL=info +# Fallback when a server has not run /settings timezone. +DEFAULT_TIMEZONE=Europe/Tallinn + +# Legacy reaction role panel. Leave ROLE_SELECTION_CHANNEL_ID empty to disable. +ROLE_SELECTION_CHANNEL_ID= +TARKVARA_ROLE_ID= +HELPDESK_ROLE_ID= +KULTUUR_ROLE_ID= + +# Redmine (optional). Setting REDMINE_BASE_URL enables the feature and then +# requires CREDENTIAL_ENCRYPTION_KEY. REDMINE_API_KEY is a restricted service +# account used only for channel notifications. +# Generate a key with: openssl rand -base64 32 +REDMINE_BASE_URL= +REDMINE_API_KEY= +CREDENTIAL_ENCRYPTION_KEY= + +# Used by compose.yaml for the bundled PostgreSQL. +POSTGRES_PASSWORD= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3d91ee5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17-alpine + env: + POSTGRES_USER: lapbot + POSTGRES_PASSWORD: lapbot + POSTGRES_DB: lapbot_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U lapbot" --health-interval 5s --health-timeout 3s --health-retries 10 + env: + TEST_DATABASE_URL: postgres://lapbot:lapbot@localhost:5432/lapbot_test + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm typecheck + - run: pnpm lint + - run: pnpm format:check + - run: pnpm test + - run: pnpm build diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6a7c0f2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM node:24-alpine AS base +WORKDIR /app +RUN corepack enable +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ + +FROM base AS build +RUN pnpm install --frozen-lockfile +COPY tsconfig.json tsconfig.build.json ./ +COPY src ./src +RUN pnpm build + +FROM base AS deps +RUN pnpm install --frozen-lockfile --prod + +FROM node:24-alpine +ENV NODE_ENV=production +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY --from=build /app/dist ./dist +COPY drizzle ./drizzle +COPY package.json ./ +USER node +# Migrations run on startup; SIGTERM triggers a graceful shutdown. +CMD ["node", "--enable-source-maps", "dist/index.js"] diff --git a/compose.dev.yaml b/compose.dev.yaml new file mode 100644 index 0000000..0a6f057 --- /dev/null +++ b/compose.dev.yaml @@ -0,0 +1,6 @@ +# Local development: exposes PostgreSQL on localhost only. +# docker compose -f compose.yaml -f compose.dev.yaml up -d postgres +services: + postgres: + ports: + - '127.0.0.1:5432:5432' diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..1fa3686 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,30 @@ +services: + bot: + build: . + restart: unless-stopped + env_file: .env + environment: + DATABASE_URL: postgres://lapbot:${POSTGRES_PASSWORD:-lapbot}@postgres:5432/lapbot + depends_on: + postgres: + condition: service_healthy + stop_grace_period: 30s + + postgres: + image: postgres:17-alpine + restart: unless-stopped + environment: + POSTGRES_USER: lapbot + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-lapbot} + POSTGRES_DB: lapbot + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U lapbot -d lapbot'] + interval: 5s + timeout: 3s + retries: 10 + # No published port: only the bot reaches the database. + +volumes: + pgdata: From 4255d3856ab08ee04c71424544f83c433fc47803 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:01:10 +0200 Subject: [PATCH 015/199] docs: setup, permissions and architecture --- README.md | 240 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 231 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 9d1b284..9797d78 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,235 @@ # LAPbot -### SETUP -Install node_modules using `npm install`
-Create a `.env` file
-Put there `BOT TOKEN`, `CHANNELS IDs` and `ROLES IDs` +The Lapikud Discord bot: role selection, events with RSVPs, reminders, +birthdays, announcements, polls, movie nights and Redmine. -`DISCORD_TOKEN=`
-`ROLE_SELECTION_CHANNEL_ID=` - Separate channel where bots role message goes. NB! MAKE SURE THAT NOBODY CAN SEND MESSAGES HERE (except for admins (bot has admin privileges))
-`TARKVARA_ROLE_ID=`
-`HELPDESK_ROLE_ID=`
-`KULTUUR_ROLE_ID=`
+TypeScript (strict, ESM) on Node.js 24, discord.js 14, PostgreSQL with +Drizzle ORM, one process with a persistent job scheduler. +## Setup + +Requirements: Node.js 24+, pnpm (`corepack enable`), Docker (for PostgreSQL). + +```sh +pnpm install +cp .env.example .env # fill in DISCORD_TOKEN and the role IDs +docker compose -f compose.yaml -f compose.dev.yaml up -d postgres +pnpm commands:register # once, and after changing commands +pnpm dev +``` + +Migrations run automatically when the bot starts. `pnpm db:migrate` runs +them without starting the bot. + +### Discord application + +1. Create an application at , + add a bot, and copy its token into `DISCORD_TOKEN` and the application ID + into `DISCORD_APPLICATION_ID`. +2. **Gateway intents:** none of the privileged intents are needed. The bot + uses only `Guilds` and `GuildMessageReactions`. +3. **Invite** with scopes `bot` and `applications.commands` and these + permissions: View Channels, Send Messages, Embed Links, Read Message + History, Add Reactions, Manage Roles, Manage Events (only for native + Discord events), and Mention Everyone (only if announcements should ping + roles that are not mentionable). +4. Drag the bot's role **above** every role it should hand out. Discord does + not let it manage roles at or above its own. +5. Make the role selection channel read-only for members (they still need Add + Reactions on the legacy panel). + +### Configuration + +All settings come from environment variables (see `.env.example`), validated +at startup. Only `DISCORD_TOKEN` and `DATABASE_URL` are required; each optional +feature asks only for what it needs. + +Precedence: settings changed at runtime with bot commands (server timezone, +birthday channel) live in the database and win over environment defaults +(`DEFAULT_TIMEZONE`). Everything else is environment-only. + +## Commands + +| Command | Who | +| -------------------------------------------------------------------------- | -------------------------------------------------------------- | +| `/role list`, role panels (button + select menu) | everyone | +| `/role create`, `delete`, `assign`, `remove`, `panel create/update/remove` | `role:create`, `role:manage`, `role:assign` | +| `/remindme`, `/reminders list/edit/cancel` | everyone; `channel:` needs `reminder:channel` | +| `/announce create/preview/publish/schedule/edit/cancel` | `announcement:create`, `:publish`, `:schedule` | +| `/event create/edit/cancel/list/view/attendees`, RSVP buttons | create needs `event:create`; organizer or `event:manage` edits | +| `/birthday set/remove/view/upcoming`, `/birthday settings` | everyone; settings need `birthday:manage` | +| `/poll create/list/results/close/cancel` | create needs `poll:create`; creator or `poll:manage` manages | +| `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | +| `/redmine …` | see [Redmine](#redmine) | +| `/permissions grant/revoke/list/check` | `permissions:manage` | +| `/settings timezone` | viewing is open; changing needs `settings:manage` | + +## Permissions + +The bot has its own action-based permissions (`event:create`, `poll:manage`, +…) granted to Discord roles per server and stored in PostgreSQL. + +- Everything restricted is denied unless one of the member's roles has a grant. + Grants from all roles combine. +- Members with Discord's **Administrator** permission hold every bot + permission. That is how the first grants are made: + `/permissions grant role:@Juhatus permission:event:create`. +- Granting to `@everyone` opens an action to all members. +- To prevent escalation, a non-administrator with `permissions:manage` can + grant only permissions they hold themselves, only to roles below their + own highest role, and never `permissions:manage`. +- Permissions are checked again on every button and menu press, not just when + the message was created. Discord role hierarchy and Redmine's own + permissions always apply on top. +- Every grant and revoke is logged. + +## Role panels and migrating from reactions + +The original reaction message (`Valige endale rolli: …` with 1️⃣ 2️⃣ 3️⃣) still +works when `ROLE_SELECTION_CHANNEL_ID` and the role IDs are set. On first start +the bot finds the message it posted before, or posts it once, and stores its +ID. It no longer reposts or searches on later starts, and reactions on any +other message are ignored. + +Select-menu panels are the replacement. Members press **Choose roles** and get +a private menu showing the roles they already have. To migrate: + +1. `/role panel create channel:#rollid title:Vali endale roll` +2. `/role panel update panel: add:@Tarkvara`, then do the same for each role. +3. Announce the new panel. Members who reacted keep their roles. +4. When ready, an administrator runs `/role panel remove` on the legacy + panel and clears `ROLE_SELECTION_CHANNEL_ID`. The bot never deletes the + legacy message on its own. + +Roles that grant moderator permissions, are managed by integrations, or sit +above the bot cannot be put on a panel. + +## Redmine + +Set `REDMINE_BASE_URL` and `CREDENTIAL_ENCRYPTION_KEY` +(`openssl rand -base64 32`) to enable it. + +- Each member runs `/redmine link` and pastes their own Redmine API key + (_My account → API access key_; the REST API must be enabled by a Redmine + admin). The key is checked against Redmine, then stored encrypted + (AES-256-GCM) with a key that never enters the database. `/redmine unlink` + deletes it. +- Every user action (`projects`, `issues`, `issue view/create/update/assign/comment`) + uses that member's own key, so Redmine decides what they can see and change. + The bot permissions `redmine:issue:create`, `redmine:issue:update` and + `redmine:issue:assign` are an additional gate, never a bypass. +- `/redmine issue remind` sets a personal DM reminder before an issue's due date. +- **Notifications:** with `REDMINE_API_KEY` (a dedicated, restricted service + account) set, `/redmine subscribe project:` posts new issues, + status changes, assignments and comments to a channel, plus a daily "due + tomorrow" digest. The bot polls every two minutes and asks only for issues + updated since each subscription's stored checkpoint. Private issues and + private notes are never posted. Anyone who can read the channel sees the + updates, so subscribe only channels whose audience may see the project. + Standard Redmine has no webhooks, so polling is the mechanism. + +## Development + +| Script | Purpose | +| -------------------------------------------------- | ----------------------------------------------------------- | +| `pnpm dev` | Run with reload (reads `.env`) | +| `pnpm build` / `pnpm start` | Compile to `dist/` and run it | +| `pnpm typecheck`, `pnpm lint`, `pnpm format:check` | Static checks | +| `pnpm test` | Vitest; set `TEST_DATABASE_URL` to run the PostgreSQL tests | +| `pnpm db:generate` | Create a migration after editing a `schema.ts` | +| `pnpm db:migrate` | Apply migrations | +| `pnpm commands:register` | Register slash commands with Discord | + +Database tests run against a real PostgreSQL and **reset its schema**, so +point `TEST_DATABASE_URL` at a throwaway database, for example: + +```sh +docker run -d --name lapbot-test-pg -e POSTGRES_USER=lapbot -e POSTGRES_PASSWORD=lapbot \ + -e POSTGRES_DB=lapbot_test -p 127.0.0.1:55432:5432 postgres:17-alpine +TEST_DATABASE_URL=postgres://lapbot:lapbot@127.0.0.1:55432/lapbot_test pnpm test +``` + +Linting uses the shared baseline (typescript-eslint strict and stylistic, type +checked; sonarjs; unicorn) plus `eslint-plugin-import-x` for cycles and module +boundaries. `eslint-plugin-n` was left out because TypeScript and the +`import-x` rules already cover module resolution. `eslint-plugin-security` +was left out because its rules are mostly false positives on this kind of +code. + +## Production + +```sh +cp .env.example .env # set DISCORD_TOKEN, POSTGRES_PASSWORD, … +docker compose up -d --build +docker compose logs -f bot +``` + +The image runs as a non-root user, applies migrations on start, logs JSON to +stdout, and shuts down gracefully on `SIGTERM`: it stops taking interactions, +finishes running jobs, then closes Discord and the database. PostgreSQL is not +published outside the Compose network. Back up the `pgdata` volume. + +## Architecture + +``` +src/ + index.ts entry point: config, logging, signals + app.ts composition root: the list of features + core/ no feature-specific logic + feature.ts the Feature contract and shared types + registry.ts collects features, rejects duplicates + discord/ client, interaction router, error boundary + permissions/ RBAC storage and the Authorizer + scheduler/ persistent job scheduler + features// index.ts is the public API; service.ts and schema.ts + hold persistence and logic and may not import discord.js + integrations/redmine typed HTTP client, no Discord code + shared/ time parsing, encryption, error types +drizzle/ SQL migrations +``` + +- **Features** declare commands, components (custom ID prefix + `feature:action`), event listeners, jobs and permissions. The router + dispatches by name and prefix, so it never changes when features are added. +- **Cross-feature use** goes through public `index.ts` exports only (enforced + by ESLint): movies use `createPoll` and `createEvent`, Redmine uses + `createReminder`. +- **Scheduler:** jobs live in `scheduled_jobs`. Workers claim due jobs with + `FOR UPDATE SKIP LOCKED` and a lease, so a crash mid-job leads to a retry + after the lease expires. Delivery is at-least-once, and handlers re-check + current state. Where a duplicate Discord message would be worse than a + missed one (announcements, birthdays, Redmine notifications), the handler + records the send in the database before posting. Each handler decides what + lateness means: late reminders are still delivered, overdue polls close, and + announcements more than an hour late are skipped and marked failed. + Transient failures retry with backoff; permanent Discord errors (closed + DMs, deleted channels) do not. + +### Adding a feature + +1. Create `src/features//`, with `schema.ts` for tables, `service.ts` + for database logic, and `index.ts` exporting a `Feature`. +2. Add it to the list in `src/app.ts`. +3. `pnpm db:generate` if you added tables, then `pnpm commands:register`. + +Declare permissions in the feature and attach them per subcommand with +`permissions: { create: 'thing:create' }`. Prefix custom IDs with the feature +name and keep any state the component needs in the database, so buttons keep +working after restarts. + +## Known limitations + +- Anonymous polls hide voters in Discord, but the database stores who voted + (needed to change votes), so database administrators can see votes. +- If the process dies between posting a reminder or event reminder and + recording it, that message can be sent twice (at-least-once). Announcements, + birthday wishes and Redmine notifications go the other way and can be lost + instead. +- Redmine polling handles 25 changed issues per project per run. More than 25 + issues changed within the same second could keep the checkpoint from moving. +- Birthday announcements are not sent for days the bot was entirely offline. +- User-facing text is English (the legacy panel and birthday wishes are + Estonian). Strings sit in the Discord layer of each feature, ready for + localisation. +- Native Discord polls are not used, because bot polls must persist and work + with movie nights. From 7c4fb95a0c629c282dd5cabc25c8b34722cad5f0 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:10:16 +0200 Subject: [PATCH 016/199] build: bundle with tsdown, resolve ~/ paths without .js extensions --- Dockerfile | 5 +- package.json | 10 +- pnpm-lock.yaml | 486 ++++++++++++++++++++++++++++++++++++++++++-- tsconfig.build.json | 11 - tsconfig.json | 11 +- tsdown.config.ts | 10 + vitest.config.ts | 4 +- 7 files changed, 496 insertions(+), 41 deletions(-) delete mode 100644 tsconfig.build.json create mode 100644 tsdown.config.ts diff --git a/Dockerfile b/Dockerfile index 6a7c0f2..7bd290f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ FROM base AS build RUN pnpm install --frozen-lockfile -COPY tsconfig.json tsconfig.build.json ./ +COPY tsconfig.json tsdown.config.ts ./ COPY src ./src RUN pnpm build @@ -20,5 +20,4 @@ COPY --from=build /app/dist ./dist COPY drizzle ./drizzle COPY package.json ./ USER node -# Migrations run on startup; SIGTERM triggers a graceful shutdown. -CMD ["node", "--enable-source-maps", "dist/index.js"] +CMD ["node", "--enable-source-maps", "dist/index.mjs"] diff --git a/package.json b/package.json index 59b85df..62cfaa1 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "packageManager": "pnpm@11.22.0", "scripts": { "dev": "tsx watch --env-file-if-exists=.env src/index.ts", - "build": "tsc -p tsconfig.build.json", - "start": "node --env-file-if-exists=.env --enable-source-maps dist/index.js", + "build": "tsdown", + "start": "node --env-file-if-exists=.env --enable-source-maps dist/index.mjs", "typecheck": "tsc --noEmit", "lint": "eslint .", "lint:fix": "eslint . --fix", @@ -24,17 +24,18 @@ "commands:register": "tsx --env-file-if-exists=.env scripts/register-commands.ts" }, "dependencies": { + "@date-fns/tz": "^1.5.0", + "date-fns": "^4.4.0", "discord.js": "^14.28.1", "drizzle-orm": "^0.45.4", - "luxon": "^3.7.2", "pino": "^10.4.0", "postgres": "^3.4.9", "zod": "^4.6.7" }, "devDependencies": { "@eslint/js": "^10.0.1", + "@stylistic/eslint-plugin": "^6.0.0", "@total-typescript/ts-reset": "^0.6.1", - "@types/luxon": "^3.7.6", "@types/node": "^24.19.2", "drizzle-kit": "^0.31.11", "eslint": "^10.15.0", @@ -47,6 +48,7 @@ "jiti": "^2.7.0", "pino-pretty": "^13.2.0", "prettier": "^3.10.1", + "tsdown": "^0.23.7", "tsx": "^4.23.15", "typescript": "~6.0.3", "typescript-eslint": "^8.72.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ffcaeb5..97c54d9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,15 +8,18 @@ importers: .: dependencies: + '@date-fns/tz': + specifier: ^1.5.0 + version: 1.5.0 + date-fns: + specifier: ^4.4.0 + version: 4.4.0 discord.js: specifier: ^14.28.1 version: 14.28.1 drizzle-orm: specifier: ^0.45.4 version: 0.45.4(postgres@3.4.9) - luxon: - specifier: ^3.7.2 - version: 3.7.2 pino: specifier: ^10.4.0 version: 10.4.0 @@ -30,12 +33,12 @@ importers: '@eslint/js': specifier: ^10.0.1 version: 10.0.1(eslint@10.15.0(jiti@2.7.0)) + '@stylistic/eslint-plugin': + specifier: ^6.0.0 + version: 6.0.0(eslint@10.15.0(jiti@2.7.0)) '@total-typescript/ts-reset': specifier: ^0.6.1 version: 0.6.1 - '@types/luxon': - specifier: ^3.7.6 - version: 3.7.6 '@types/node': specifier: ^24.19.2 version: 24.19.2 @@ -72,6 +75,9 @@ importers: prettier: specifier: ^3.10.1 version: 3.10.1 + tsdown: + specifier: ^0.23.7 + version: 0.23.7(tsx@4.23.15)(typescript@6.0.3) tsx: specifier: ^4.23.15 version: 4.23.15 @@ -93,6 +99,9 @@ packages: '@cacheable/utils@2.5.0': resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + '@date-fns/tz@1.5.0': + resolution: {integrity: sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==} + '@discordjs/builders@1.15.0': resolution: {integrity: sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==} engines: {node: '>=16.11.0'} @@ -680,45 +689,87 @@ packages: '@oxc-project/types@0.156.0': resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + '@oxc-project/types@0.158.0': + resolution: {integrity: sha512-xZ66qA4WmLbTLlxH3mqMd8f9UKbaOzOT0ATwFf4DH/14pMgpUrtqtjyYzOQmgfl2a0iRAAMbQ9G1th/67jRzGw==} + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + '@quansync/fs@1.1.0': + resolution: {integrity: sha512-qAPG/t3HqML1TlN7sY/pTbEjzFVAKsMjNNMGheyDosro+kT4iw2KCUoHcVdmliwWjorm4elZbgNQyU2eD97eDg==} + '@rolldown/binding-android-arm-eabi@1.2.19': resolution: {integrity: sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] + '@rolldown/binding-android-arm-eabi@1.3.2': + resolution: {integrity: sha512-kqR2xcygEx3WwDY69LsKeyf7SVmx4yzMtKZRknyaHieVJdRvvnAM97L0Gq6tUFc9T2YXcW/Ghij2+Um6He0LTw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + '@rolldown/binding-android-arm64@1.2.19': resolution: {integrity: sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] + '@rolldown/binding-android-arm64@1.3.2': + resolution: {integrity: sha512-gXM4GAAvvIZA7qUuSCQS+Zz91H2fagKa5MNppUdjzysJ8LXMWm9D/gQj4nfOKo6okquDQ5pkjsuo2SUMXNW0Rw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + '@rolldown/binding-darwin-arm64@1.2.19': resolution: {integrity: sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] + '@rolldown/binding-darwin-arm64@1.3.2': + resolution: {integrity: sha512-OBs5hp3W+LwMEUmDMMMnu08ncG0t6DDgnFU+6TAucKtAfNgerYLZSr2jtREKb/JuPQ1J7bJnWIgKKkxvjuAw1g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + '@rolldown/binding-darwin-x64@1.2.19': resolution: {integrity: sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] + '@rolldown/binding-darwin-x64@1.3.2': + resolution: {integrity: sha512-X0VGYd4v/gdjfa/IP6uHuMhofPoUDYvK/byk3bC0jQ1pKKgt6RZ4B4puMqP0AHkjmIHAsxA471mM6AxZ39IaTA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + '@rolldown/binding-freebsd-x64@1.2.19': resolution: {integrity: sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] + '@rolldown/binding-freebsd-x64@1.3.2': + resolution: {integrity: sha512-mr04K4cp9J/fj9fknrX8e4QvI/V48Sp+4v64PoLwhoirIH8b8L8EBrF/0bTjV1It2IL91hoNG13GblnWLglkxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': resolution: {integrity: sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] + '@rolldown/binding-linux-arm-gnueabihf@1.3.2': + resolution: {integrity: sha512-VgWy02HU9Tiy6tU8U+kF3Fd4TQwTNdIBvs2MlgViP1ksMtAnQQTIPAj0ZsJzIQXKIOugqQSpqxQgELJ3fkuL5w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + '@rolldown/binding-linux-arm64-gnu@1.2.19': resolution: {integrity: sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -726,6 +777,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-arm64-gnu@1.3.2': + resolution: {integrity: sha512-0wloJFYqV844gv6boiERbHpErxbxHbmlgnMX5VxP1Ux+DLBqGrUOn0cIpBmCZEcTITes3QUelxya4u8c9ziQvQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-arm64-musl@1.2.19': resolution: {integrity: sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -733,6 +791,13 @@ packages: os: [linux] libc: [musl] + '@rolldown/binding-linux-arm64-musl@1.3.2': + resolution: {integrity: sha512-Kys8wgFQy8H8vua0MNpC0akMBFoNO8455RHk2yycBM0iayMIAtVAL6xmV9TWAkehFgrrlImTL2fZdX5LXfYtAA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + '@rolldown/binding-linux-ppc64-gnu@1.2.19': resolution: {integrity: sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==} engines: {node: ^20.19.0 || >=22.12.0} @@ -740,6 +805,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-ppc64-gnu@1.3.2': + resolution: {integrity: sha512-L8eej7+/StRxUHHOPsOVl7Fzx/3tumuGB4hGQZKT73xRI16KZhaSJr0gi3C3WBjNRxeJRKKps2UD4lQukP+oBw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-s390x-gnu@1.2.19': resolution: {integrity: sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -747,6 +819,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-s390x-gnu@1.3.2': + resolution: {integrity: sha512-MV5CEb/nV8neQOj7l6945q1vy62HXtWO8zPDvfySPusoUzdBoLoJ/DfXXwaYThGTXZCniF+5bCf253WTPPK7Yw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-x64-gnu@1.2.19': resolution: {integrity: sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==} engines: {node: ^20.19.0 || >=22.12.0} @@ -754,6 +833,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-x64-gnu@1.3.2': + resolution: {integrity: sha512-3qssvvVvkwQookZ1/1avlKWc5orAR85vgKdzDd5noZS8nnHiI/ejOAEt0xfNYvtBBF7/DZmP8dANWkRBJVOBCA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-x64-musl@1.2.19': resolution: {integrity: sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -761,29 +847,59 @@ packages: os: [linux] libc: [musl] + '@rolldown/binding-linux-x64-musl@1.3.2': + resolution: {integrity: sha512-rJqoFTm/bCZFKKgaT4NzWn/TuJkFDToZ/rzYFnYVBL28jH1nIfg6snx2mDri30nal9H+wcYfKpoPR9jrMQgQQg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + '@rolldown/binding-openharmony-arm64@1.2.19': resolution: {integrity: sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] + '@rolldown/binding-openharmony-arm64@1.3.2': + resolution: {integrity: sha512-ozdbCjHfh0N//wJNExjJlSlcDaeIKo8k1ktzkLUyESr2Gu/Qw7nBYxKe3jgtoaxda570vg10WdYosre82263hQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + '@rolldown/binding-wasm32-wasi@1.2.19': resolution: {integrity: sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==} engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} cpu: [wasm32] + '@rolldown/binding-wasm32-wasi@1.3.2': + resolution: {integrity: sha512-p5VA6Vk/2cXZPVWf+dDbuE0dkhrcoAo6pISTJmzUnsSdQqNJdusyR8lZgHku095+r27zrYISNLZnJoqrcePW0A==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + cpu: [wasm32] + '@rolldown/binding-win32-arm64-msvc@1.2.19': resolution: {integrity: sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] + '@rolldown/binding-win32-arm64-msvc@1.3.2': + resolution: {integrity: sha512-XDb2U14Orf4r76SwzvJ7avePL00w4gHBmi1Ig4B/itYFEUTmYMNDHVU0dcYuBa0LgNBqyREoJOrQKxQlyYJA7A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + '@rolldown/binding-win32-x64-msvc@1.2.19': resolution: {integrity: sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] + '@rolldown/binding-win32-x64-msvc@1.3.2': + resolution: {integrity: sha512-lEsKzKJqIUDZVCBhS4lkZuyQUhV1oRg5UHkI72qlOAqJn7qEXcoVdTridFS7PHNWdZknBl95EAF/4P1Xv0K1eQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@rolldown/pluginutils@1.1.1': resolution: {integrity: sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==} @@ -802,6 +918,18 @@ packages: '@sonarsource/analyzer-commons-configurations@2.31.0-5284': resolution: {integrity: sha512-ruk3blMs9BE9RNSp9LPpWZAIjxJmq4Cp00E3cELIHz7Kym3WxdWGRlKOMYLRQ5tJg/de7jN5AtEElY3bGIfTcw==} + '@stylistic/eslint-plugin@6.0.0': + resolution: {integrity: sha512-phICSey4OqR8nkSwmoeXsl9EBzv30Zqbge4jrK3CU02GhjTgZ+y5qhTTg92EDK5j7JhX2xzp4VvH+YYUknQ8/Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^9.0.0 || ^10.0.0 + oxlint: ^1.55.0 + peerDependenciesMeta: + eslint: + optional: true + oxlint: + optional: true + '@total-typescript/ts-reset@0.6.1': resolution: {integrity: sha512-cka47fVSo6lfQDIATYqb/vO1nvFfbPw7uWLayIXIhGETj0wcOOlrlkobOMDNQOFr9QOafegUPq13V2+6vtD7yg==} @@ -826,9 +954,6 @@ packages: '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - '@types/luxon@3.7.6': - resolution: {integrity: sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ==} - '@types/ms@2.1.0': resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} @@ -1033,6 +1158,36 @@ packages: resolution: {integrity: sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==} engines: {node: '>=v14.0.0', npm: '>=7.0.0'} + '@yuku-toolchain/darwin-arm64@0.28.0': + resolution: {integrity: sha512-ub1u+JMRrLcuDMN2VofXS1GMau5Irl/HKj8raDUN6hYihe/Ed7IVpT9ycqs7vWxQx1j4BPyXr+UOV3gVXVFooA==} + cpu: [arm64] + os: [darwin] + + '@yuku-toolchain/darwin-x64@0.28.0': + resolution: {integrity: sha512-S3XmN4T7nXBUdBAvIM/7/O1LpNXFg0E/9iaZO4S2fZrlxeYuvOKcgI9y6i0/2ddsWMJvMZ51cuxFTeesvRC41A==} + cpu: [x64] + os: [darwin] + + '@yuku-toolchain/linux-arm64@0.28.0': + resolution: {integrity: sha512-kIK5JcpiGGBFZlLKuvjVmzqOmnCYSFXa1P8Vl+gZN6B+3G/1rTusBJqyMjKMNuXyMb+AYac6roGRpbcGH/LFUw==} + cpu: [arm64] + os: [linux] + + '@yuku-toolchain/linux-x64@0.28.0': + resolution: {integrity: sha512-yCz0KECLdtk8G7VCwzYlC0xi70W29oB65oRUW7MA+lvaNEHkhK+ZLZzCveVkl3BVpLpkyBrznODX8UdbVBmpCg==} + cpu: [x64] + os: [linux] + + '@yuku-toolchain/win32-arm64@0.28.0': + resolution: {integrity: sha512-d6M/3YJ/vJNQP32Yw/58KaVtp1D9nmP4C3C8HSTdhjiVTSmVQ4UX0+QT/iftH4G7VLGVZeI8wo5QhLF4rC2jgw==} + cpu: [arm64] + os: [win32] + + '@yuku-toolchain/win32-x64@0.28.0': + resolution: {integrity: sha512-aJ4h8oy9jYtfjh5hXXuIBrDvnkXfPUlKhxFumAArkK9TrnDAXo3Ixk3/S6xmjnPkkqobS7NyDLcSC/HZb2gjOg==} + cpu: [x64] + os: [win32] + acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -1087,6 +1242,10 @@ packages: resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} engines: {node: '>= 0.8'} + cac@7.1.0: + resolution: {integrity: sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==} + engines: {node: '>=20.19.0'} + cacheable@2.5.0: resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} @@ -1125,6 +1284,9 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + date-fns@4.4.0: + resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==} + dateformat@4.6.3: resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==} @@ -1143,6 +1305,9 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -1264,9 +1429,22 @@ packages: sqlite3: optional: true + dts-resolver@3.0.0: + resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==} + engines: {node: ^22.18.0 || >=24.0.0} + peerDependencies: + oxc-resolver: '>=11.0.0' + peerDependenciesMeta: + oxc-resolver: + optional: true + electron-to-chromium@1.5.485: resolution: {integrity: sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw==} + empathic@2.1.0: + resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} + engines: {node: '>=14'} + end-of-stream@1.4.5: resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} @@ -1464,6 +1642,10 @@ packages: get-tsconfig@4.14.3: resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==} + get-tsconfig@5.0.0-beta.6: + resolution: {integrity: sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw==} + engines: {node: '>=20.20.0'} + glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -1479,6 +1661,9 @@ packages: help-me@5.0.0: resolution: {integrity: sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==} + hookable@6.1.2: + resolution: {integrity: sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg==} + hookified@1.15.1: resolution: {integrity: sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==} @@ -1497,6 +1682,10 @@ packages: resolution: {integrity: sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==} engines: {node: '>= 4'} + import-without-cache@0.4.1: + resolution: {integrity: sha512-vXoV9PjKHEednCUu01e98TkImxy67e3BJXbTIOmIq4Hyzw3IAwYRcuPkfeTzJzwyyts4kjuA73x+pWJLc4f86A==} + engines: {node: ^22.18.0 || >=24.0.0} + imurmurhash@0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} @@ -1640,10 +1829,6 @@ packages: lodash@4.18.1: resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} - luxon@3.7.2: - resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} - engines: {node: '>=12'} - magic-bytes.js@1.13.1: resolution: {integrity: sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==} @@ -1837,6 +2022,9 @@ packages: resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} engines: {node: '>=20'} + quansync@1.0.0: + resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==} + quick-format-unescaped@4.0.4: resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} @@ -1866,11 +2054,38 @@ packages: resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + rolldown-plugin-dts@0.30.2: + resolution: {integrity: sha512-Q3wRlwawifZeN1llb1BaeZfimmJMF/WHzm7z5ieZ8g2CWHQM0gvVWLYPbgBglsXJqcd405gc+3LS2NzSevbYNQ==} + engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} + peerDependencies: + '@volar/typescript': ~2.4.0 + '@vue/language-core': ~3.2.0 || ~3.3.0 + rolldown: ^1.2.0 + tsrs: '*' + typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 || ~7.1.0-0 + vue-tsc: ~3.2.0 || ~3.3.0 + peerDependenciesMeta: + '@volar/typescript': + optional: true + '@vue/language-core': + optional: true + tsrs: + optional: true + typescript: + optional: true + vue-tsc: + optional: true + rolldown@1.2.19: resolution: {integrity: sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + rolldown@1.3.2: + resolution: {integrity: sha512-EFHqbVkXiYZA6akmYm2bvJhNbEGdUwAResRhYwl/BO8QhB5KxsG+t3RVHJSIOy5jBEb0XCACvrIGnnl6Z8sMGA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + safe-stable-stringify@2.5.0: resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} engines: {node: '>=10'} @@ -1947,6 +2162,9 @@ packages: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinyps@0.5.2: + resolution: {integrity: sha512-sYhvdbpuo2rGE7u/jPUMiZz4H2LCaOodUtRD9ot4DLNFQbr884g9zozoJnxLI+1r4hXqWkmdHUl8Yig2Rllxxw==} + ts-api-utils@2.5.0: resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} engines: {node: '>=18.12'} @@ -1956,6 +2174,40 @@ packages: ts-mixer@6.0.4: resolution: {integrity: sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==} + tsdown@0.23.7: + resolution: {integrity: sha512-w9nmWyEimfqQ7/HpVeKTldAeBvWGXiaWyNP7xaxSrr0GhKxsngEyTWqk1nOruRqvqRSkdpMMkpV2BcoWfLB4Uw==} + engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@arethetypeswrong/core': ^0.18.1 + '@tsdown/css': 0.23.7 + '@tsdown/exe': 0.23.7 + '@vitejs/devtools': '*' + publint: ^0.3.8 + tsx: '*' + typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 + unplugin-unused: '>=0.5.0' + unrun: '*' + peerDependenciesMeta: + '@arethetypeswrong/core': + optional: true + '@tsdown/css': + optional: true + '@tsdown/exe': + optional: true + '@vitejs/devtools': + optional: true + publint: + optional: true + tsx: + optional: true + typescript: + optional: true + unplugin-unused: + optional: true + unrun: + optional: true + tslib@2.9.1: resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} @@ -1980,6 +2232,9 @@ packages: engines: {node: '>=14.17'} hasBin: true + unconfig-core@7.5.0: + resolution: {integrity: sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==} + undici-types@7.24.6: resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} @@ -2002,6 +2257,10 @@ packages: uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + verkit@0.5.0: + resolution: {integrity: sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==} + engines: {node: '>=18.12.0'} + vite@8.3.8: resolution: {integrity: sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2124,6 +2383,15 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} + yuku@0.28.0: + resolution: {integrity: sha512-vzuml0lBwq8gYUujhLZn9AZwgPG1yPF1081ceOkTnEIM9bwgRnFUGAW5x2hTLC+qGI/iqu9PLs5Jko6rUn7YDA==} + engines: {node: '>=16.4.0'} + peerDependencies: + '@yuku-toolchain/wasm': 0.28.0 + peerDependenciesMeta: + '@yuku-toolchain/wasm': + optional: true + zod@4.6.7: resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} @@ -2141,6 +2409,8 @@ snapshots: hashery: 1.5.1 keyv: 5.6.0 + '@date-fns/tz@1.5.0': {} + '@discordjs/builders@1.15.0': dependencies: '@discordjs/formatters': 0.6.2 @@ -2523,47 +2793,92 @@ snapshots: '@oxc-project/types@0.156.0': {} + '@oxc-project/types@0.158.0': {} + '@pinojs/redact@0.4.0': {} + '@quansync/fs@1.1.0': + dependencies: + quansync: 1.0.0 + '@rolldown/binding-android-arm-eabi@1.2.19': optional: true + '@rolldown/binding-android-arm-eabi@1.3.2': + optional: true + '@rolldown/binding-android-arm64@1.2.19': optional: true + '@rolldown/binding-android-arm64@1.3.2': + optional: true + '@rolldown/binding-darwin-arm64@1.2.19': optional: true + '@rolldown/binding-darwin-arm64@1.3.2': + optional: true + '@rolldown/binding-darwin-x64@1.2.19': optional: true + '@rolldown/binding-darwin-x64@1.3.2': + optional: true + '@rolldown/binding-freebsd-x64@1.2.19': optional: true + '@rolldown/binding-freebsd-x64@1.3.2': + optional: true + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': optional: true + '@rolldown/binding-linux-arm-gnueabihf@1.3.2': + optional: true + '@rolldown/binding-linux-arm64-gnu@1.2.19': optional: true + '@rolldown/binding-linux-arm64-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-arm64-musl@1.2.19': optional: true + '@rolldown/binding-linux-arm64-musl@1.3.2': + optional: true + '@rolldown/binding-linux-ppc64-gnu@1.2.19': optional: true + '@rolldown/binding-linux-ppc64-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-s390x-gnu@1.2.19': optional: true + '@rolldown/binding-linux-s390x-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-x64-gnu@1.2.19': optional: true + '@rolldown/binding-linux-x64-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-x64-musl@1.2.19': optional: true + '@rolldown/binding-linux-x64-musl@1.3.2': + optional: true + '@rolldown/binding-openharmony-arm64@1.2.19': optional: true + '@rolldown/binding-openharmony-arm64@1.3.2': + optional: true + '@rolldown/binding-wasm32-wasi@1.2.19': dependencies: '@emnapi/core': 2.0.0-beta.2 @@ -2571,12 +2886,25 @@ snapshots: '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2) optional: true + '@rolldown/binding-wasm32-wasi@1.3.2': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2) + optional: true + '@rolldown/binding-win32-arm64-msvc@1.2.19': optional: true + '@rolldown/binding-win32-arm64-msvc@1.3.2': + optional: true + '@rolldown/binding-win32-x64-msvc@1.2.19': optional: true + '@rolldown/binding-win32-x64-msvc@1.3.2': + optional: true + '@rolldown/pluginutils@1.1.1': {} '@sapphire/async-queue@1.5.5': {} @@ -2590,6 +2918,16 @@ snapshots: '@sonarsource/analyzer-commons-configurations@2.31.0-5284': {} + '@stylistic/eslint-plugin@6.0.0(eslint@10.15.0(jiti@2.7.0))': + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0(jiti@2.7.0)) + '@typescript-eslint/types': 8.72.2 + '@typescript-eslint/visitor-keys': 8.72.2 + espree: 11.2.0 + picomatch: 4.0.7 + optionalDependencies: + eslint: 10.15.0(jiti@2.7.0) + '@total-typescript/ts-reset@0.6.1': {} '@tybys/wasm-util@0.10.4': @@ -2614,8 +2952,6 @@ snapshots: '@types/json-schema@7.0.15': {} - '@types/luxon@3.7.6': {} - '@types/ms@2.1.0': {} '@types/node@24.19.2': @@ -2797,6 +3133,24 @@ snapshots: '@vladfrangu/async_event_emitter@2.4.7': {} + '@yuku-toolchain/darwin-arm64@0.28.0': + optional: true + + '@yuku-toolchain/darwin-x64@0.28.0': + optional: true + + '@yuku-toolchain/linux-arm64@0.28.0': + optional: true + + '@yuku-toolchain/linux-x64@0.28.0': + optional: true + + '@yuku-toolchain/win32-arm64@0.28.0': + optional: true + + '@yuku-toolchain/win32-x64@0.28.0': + optional: true + acorn-jsx@5.3.2(acorn@8.19.0): dependencies: acorn: 8.19.0 @@ -2838,6 +3192,8 @@ snapshots: bytes@3.1.2: {} + cac@7.1.0: {} + cacheable@2.5.0: dependencies: '@cacheable/memory': 2.2.0 @@ -2872,6 +3228,8 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 + date-fns@4.4.0: {} + dateformat@4.6.3: {} debug@4.4.3: @@ -2884,6 +3242,8 @@ snapshots: deep-is@0.1.4: {} + defu@6.1.7: {} + dequal@2.0.3: {} detect-indent@7.0.2: {} @@ -2926,8 +3286,12 @@ snapshots: optionalDependencies: postgres: 3.4.9 + dts-resolver@3.0.0: {} + electron-to-chromium@1.5.485: {} + empathic@2.1.0: {} + end-of-stream@1.4.5: dependencies: once: 1.4.0 @@ -3234,6 +3598,10 @@ snapshots: dependencies: resolve-pkg-maps: 1.0.0 + get-tsconfig@5.0.0-beta.6: + dependencies: + resolve-pkg-maps: 1.0.0 + glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -3246,6 +3614,8 @@ snapshots: help-me@5.0.0: {} + hookable@6.1.2: {} + hookified@1.15.1: {} hookified@2.2.0: {} @@ -3258,6 +3628,8 @@ snapshots: ignore@7.0.14: {} + import-without-cache@0.4.1: {} + imurmurhash@0.1.4: {} indent-string@5.0.0: {} @@ -3358,8 +3730,6 @@ snapshots: lodash@4.18.1: {} - luxon@3.7.2: {} - magic-bytes.js@1.13.1: {} magic-string@1.4.5: @@ -3621,6 +3991,8 @@ snapshots: dependencies: hookified: 2.2.0 + quansync@1.0.0: {} + quick-format-unescaped@4.0.4: {} quote-js-string@0.1.0: {} @@ -3644,6 +4016,19 @@ snapshots: resolve-pkg-maps@1.0.0: {} + rolldown-plugin-dts@0.30.2(rolldown@1.3.2)(typescript@6.0.3): + dependencies: + dts-resolver: 3.0.0 + get-tsconfig: 5.0.0-beta.6 + obug: 3.0.0 + rolldown: 1.3.2 + yuku: 0.28.0 + optionalDependencies: + typescript: 6.0.3 + transitivePeerDependencies: + - '@yuku-toolchain/wasm' + - oxc-resolver + rolldown@1.2.19: dependencies: '@oxc-project/types': 0.156.0 @@ -3666,6 +4051,28 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.19 '@rolldown/binding-win32-x64-msvc': 1.2.19 + rolldown@1.3.2: + dependencies: + '@oxc-project/types': 0.158.0 + '@rolldown/pluginutils': 1.1.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.3.2 + '@rolldown/binding-android-arm64': 1.3.2 + '@rolldown/binding-darwin-arm64': 1.3.2 + '@rolldown/binding-darwin-x64': 1.3.2 + '@rolldown/binding-freebsd-x64': 1.3.2 + '@rolldown/binding-linux-arm-gnueabihf': 1.3.2 + '@rolldown/binding-linux-arm64-gnu': 1.3.2 + '@rolldown/binding-linux-arm64-musl': 1.3.2 + '@rolldown/binding-linux-ppc64-gnu': 1.3.2 + '@rolldown/binding-linux-s390x-gnu': 1.3.2 + '@rolldown/binding-linux-x64-gnu': 1.3.2 + '@rolldown/binding-linux-x64-musl': 1.3.2 + '@rolldown/binding-openharmony-arm64': 1.3.2 + '@rolldown/binding-wasm32-wasi': 1.3.2 + '@rolldown/binding-win32-arm64-msvc': 1.3.2 + '@rolldown/binding-win32-x64-msvc': 1.3.2 + safe-stable-stringify@2.5.0: {} scslre@0.3.0: @@ -3724,12 +4131,41 @@ snapshots: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 + tinyps@0.5.2: {} + ts-api-utils@2.5.0(typescript@6.0.3): dependencies: typescript: 6.0.3 ts-mixer@6.0.4: {} + tsdown@0.23.7(tsx@4.23.15)(typescript@6.0.3): + dependencies: + cac: 7.1.0 + defu: 6.1.7 + empathic: 2.1.0 + hookable: 6.1.2 + import-without-cache: 0.4.1 + obug: 3.0.0 + picomatch: 4.0.7 + rolldown: 1.3.2 + rolldown-plugin-dts: 0.30.2(rolldown@1.3.2)(typescript@6.0.3) + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tinyps: 0.5.2 + unconfig-core: 7.5.0 + verkit: 0.5.0 + optionalDependencies: + tsx: 4.23.15 + typescript: 6.0.3 + transitivePeerDependencies: + - '@volar/typescript' + - '@vue/language-core' + - '@yuku-toolchain/wasm' + - oxc-resolver + - tsrs + - vue-tsc + tslib@2.9.1: {} tsx@4.23.15: @@ -3755,6 +4191,11 @@ snapshots: typescript@6.0.3: {} + unconfig-core@7.5.0: + dependencies: + '@quansync/fs': 1.1.0 + quansync: 1.0.0 + undici-types@7.24.6: {} undici-types@8.9.0: {} @@ -3797,6 +4238,8 @@ snapshots: dependencies: punycode: 2.3.1 + verkit@0.5.0: {} + vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 @@ -3849,4 +4292,13 @@ snapshots: yocto-queue@0.1.0: {} + yuku@0.28.0: + optionalDependencies: + '@yuku-toolchain/darwin-arm64': 0.28.0 + '@yuku-toolchain/darwin-x64': 0.28.0 + '@yuku-toolchain/linux-arm64': 0.28.0 + '@yuku-toolchain/linux-x64': 0.28.0 + '@yuku-toolchain/win32-arm64': 0.28.0 + '@yuku-toolchain/win32-x64': 0.28.0 + zod@4.6.7: {} diff --git a/tsconfig.build.json b/tsconfig.build.json deleted file mode 100644 index af7cb03..0000000 --- a/tsconfig.build.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "noEmit": false, - "rootDir": "src", - "outDir": "dist", - "sourceMap": true - }, - "include": ["src"], - "exclude": ["src/**/*.test.ts"] -} diff --git a/tsconfig.json b/tsconfig.json index 1f899a2..f0a6744 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,9 +1,9 @@ { "compilerOptions": { "target": "ES2022", - "lib": ["ES2023"], - "module": "NodeNext", - "moduleResolution": "NodeNext", + "lib": ["ES2024"], + "module": "ESNext", + "moduleResolution": "bundler", "types": ["node"], "strict": true, "noUncheckedIndexedAccess": true, @@ -18,7 +18,10 @@ "noEmitOnError": true, "skipLibCheck": true, "resolveJsonModule": true, - "noEmit": true + "noEmit": true, + "paths": { + "~/*": ["./src/*"] + } }, "include": ["src", "tests", "scripts", "*.config.ts"] } diff --git a/tsdown.config.ts b/tsdown.config.ts new file mode 100644 index 0000000..10969c9 --- /dev/null +++ b/tsdown.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/index.ts'], + platform: 'node', + target: 'node24', + format: 'esm', + sourcemap: true, + dts: false, +}); diff --git a/vitest.config.ts b/vitest.config.ts index 1b6a808..f3b30a7 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,10 +1,10 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ + resolve: { tsconfigPaths: true }, test: { - include: ['src/**/*.test.ts', 'tests/**/*.test.ts'], + include: ['tests/**/*.test.ts'], globalSetup: ['tests/global-setup.ts'], - // Database tests share one database, so files run one at a time. fileParallelism: false, }, }); From 55acd7ef4011943a770865c153c9cf43d10cbce6 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:10:16 +0200 Subject: [PATCH 017/199] style: adopt style-guide lint rules for padding, loops and imports --- eslint.config.ts | 40 ++++++++++++++++++++++++++++++++++------ src/shared/async.ts | 8 ++++++++ src/shared/errors.ts | 10 +--------- 3 files changed, 43 insertions(+), 15 deletions(-) create mode 100644 src/shared/async.ts diff --git a/eslint.config.ts b/eslint.config.ts index 208becd..5a89a37 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -2,7 +2,7 @@ import js from '@eslint/js'; import type { Linter } from 'eslint'; import { defineConfig, globalIgnores } from 'eslint/config'; import tseslint from 'typescript-eslint'; -import sonarjs from 'eslint-plugin-sonarjs'; +import { configs as sonarConfigs } from 'eslint-plugin-sonarjs'; import unicorn from 'eslint-plugin-unicorn'; import prettier from 'eslint-config-prettier'; import globals from 'globals'; @@ -64,7 +64,8 @@ const qualityRules: Linter.RulesRecord = { complexity: ['error', { max: 15 }], 'max-depth': ['error', { max: 4 }], - 'max-params': ['error', { max: 5 }], + 'max-params': ['error', { max: 4 }], + 'no-await-in-loop': 'error', 'max-nested-callbacks': ['error', { max: 4 }], 'sonarjs/cognitive-complexity': ['error', 15], @@ -74,9 +75,9 @@ const qualityRules: Linter.RulesRecord = { 'sonarjs/prefer-regexp-exec': 'error', 'sonarjs/no-empty-collection': 'error', 'sonarjs/reduce-initial-value': 'error', + 'sonarjs/no-redundant-optional': 'error', }; -// Files that hold business logic or persistence must stay transport-agnostic. const transportFreeFiles = [ 'src/db/**/*.ts', 'src/integrations/**/*.ts', @@ -95,7 +96,6 @@ const noDiscordImport = { 'Keep Discord transport code out of services, stores and integrations.', }; -// A feature may only reach into another feature through its index.ts. const featurePrivatePattern = { group: ['../*/*', '!../*/index.js', '!../../**'], message: "Import other features only through their public 'index.js'.", @@ -129,6 +129,7 @@ const unicornRules: Linter.RulesRecord = { 'unicorn/no-for-loop': 'error', 'unicorn/no-array-reduce': 'off', + 'unicorn/no-array-callback-reference': 'error', }; export default defineConfig( @@ -152,7 +153,7 @@ export default defineConfig( { files: sourceFiles, - extends: [js.configs.recommended, sonarjs.configs.recommended], + extends: [js.configs.recommended, sonarConfigs.recommended], languageOptions: { ecmaVersion: 'latest', globals: globals.builtin, @@ -382,10 +383,37 @@ export default defineConfig( '@typescript-eslint/require-await': 'off', 'unicorn/no-useless-undefined': 'off', 'unicorn/no-await-expression-member': 'off', - // Tests may build fixtures with another feature's internals. 'no-restricted-imports': 'off', + 'no-await-in-loop': 'off', }, }, + { + files: ['src/shared/async.ts', 'src/core/scheduler/scheduler.ts'], + rules: { 'no-await-in-loop': 'off' }, + }, + prettier, + + { + files: typescriptFiles, + rules: { + curly: ['error', 'all'], + 'no-restricted-syntax': [ + 'error', + { + selector: + 'ImportDeclaration[source.value=/^\\.{1,2}\\/.*\\.js$/], ImportExpression[source.value=/^\\.{1,2}\\/.*\\.js$/]', + message: 'Import local modules without the .js extension.', + }, + ], + 'padding-line-between-statements': [ + 'error', + { blankLine: 'always', prev: '*', next: 'return' }, + { blankLine: 'always', prev: ['const', 'let'], next: '*' }, + { blankLine: 'any', prev: ['const', 'let'], next: ['const', 'let'] }, + { blankLine: 'always', prev: 'block-like', next: '*' }, + ], + }, + }, ); diff --git a/src/shared/async.ts b/src/shared/async.ts new file mode 100644 index 0000000..1fe61cf --- /dev/null +++ b/src/shared/async.ts @@ -0,0 +1,8 @@ +export async function sequential( + items: Iterable, + run: (item: T) => Promise, +): Promise { + for (const item of items) { + await run(item); + } +} diff --git a/src/shared/errors.ts b/src/shared/errors.ts index f274219..e84923e 100644 --- a/src/shared/errors.ts +++ b/src/shared/errors.ts @@ -1,17 +1,9 @@ -/** - * An expected failure caused by user input or current state. Its message is - * safe to show to the user and it is not logged as an error. - */ export class UserError extends Error { override readonly name = 'UserError'; } -/** A job failure that retrying cannot fix. */ export class PermanentError extends Error { override readonly name = 'PermanentError'; } -/** For best-effort calls whose failure needs no handling, e.g. a late reply. */ -export function ignore(): void { - // Intentionally empty. -} +export const ignore = () => null; From 2b292ca06d5ab8baf3932037fe5d4ca1cabc996f Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:10:25 +0200 Subject: [PATCH 018/199] test: move tests into tests/ mirroring src/ --- tests/app.test.ts | 17 +++++-- {src => tests}/core/discord/router.test.ts | 19 ++++++-- .../core/permissions/authorizer.test.ts | 17 +++++-- {src => tests}/core/registry.test.ts | 5 +- .../core/scheduler/scheduler.test.ts | 33 +++++++++---- tests/db.ts | 7 +-- .../announcements/announcements.test.ts | 22 ++++++--- .../features/birthdays/birthdays.test.ts | 46 +++++++++++-------- {src => tests}/features/events/events.test.ts | 18 +++++--- {src => tests}/features/movies/movies.test.ts | 15 ++++-- .../features/permissions/permissions.test.ts | 4 +- {src => tests}/features/polls/polls.test.ts | 26 ++++++++--- .../features/redmine/redmine.test.ts | 22 ++++++--- .../features/reminders/reminders.test.ts | 25 +++++++--- {src => tests}/features/roles/roles.test.ts | 18 ++++++-- tests/global-setup.ts | 8 +++- .../integrations/redmine/client.test.ts | 13 +++++- {src => tests}/shared/crypto.test.ts | 4 +- {src => tests}/shared/time.test.ts | 11 +++-- 19 files changed, 234 insertions(+), 96 deletions(-) rename {src => tests}/core/discord/router.test.ts (95%) rename {src => tests}/core/permissions/authorizer.test.ts (90%) rename {src => tests}/core/registry.test.ts (95%) rename {src => tests}/core/scheduler/scheduler.test.ts (93%) rename {src => tests}/features/announcements/announcements.test.ts (87%) rename {src => tests}/features/birthdays/birthdays.test.ts (84%) rename {src => tests}/features/events/events.test.ts (92%) rename {src => tests}/features/movies/movies.test.ts (92%) rename {src => tests}/features/permissions/permissions.test.ts (93%) rename {src => tests}/features/polls/polls.test.ts (93%) rename {src => tests}/features/redmine/redmine.test.ts (93%) rename {src => tests}/features/reminders/reminders.test.ts (89%) rename {src => tests}/features/roles/roles.test.ts (94%) rename {src => tests}/integrations/redmine/client.test.ts (97%) rename {src => tests}/shared/crypto.test.ts (94%) rename {src => tests}/shared/time.test.ts (89%) diff --git a/tests/app.test.ts b/tests/app.test.ts index bd5f3da..2c300ac 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -3,39 +3,48 @@ import type { RESTPostAPIChatInputApplicationCommandsJSONBody, } from 'discord.js'; import { describe, expect, it } from 'vitest'; -import { createRegistry } from '../src/app.js'; -import type { Config } from '../src/core/config.js'; +import { createRegistry } from '~/app'; +import type { Config } from '~/core/config'; const config = { DEFAULT_TIMEZONE: 'Europe/Tallinn' } as Config; -/** Rules Discord enforces when commands are registered. */ function problems( path: string, options: readonly APIApplicationCommandOption[] = [], ): string[] { const found: string[] = []; + if (options.length > 25) { found.push(`${path}: more than 25 options`); } + let optionalSeen = false; + for (const option of options) { const name = `${path} ${option.name}`; + if (!/^[\p{Ll}\p{N}_-]{1,32}$/u.test(option.name)) { found.push(`${name}: invalid name`); } + if (option.description.length === 0 || option.description.length > 100) { found.push(`${name}: description must be 1-100 characters`); } + if ('options' in option) { found.push(...problems(name, option.options)); continue; } + const required = 'required' in option && option.required; + if (required && optionalSeen) { found.push(`${name}: required option after an optional one`); } + optionalSeen ||= !required; } + return found; } @@ -51,6 +60,7 @@ describe('composition root', () => { const commands = [...registry.commands.values()].map( (c): RESTPostAPIChatInputApplicationCommandsJSONBody => c.data, ); + expect(commands.flatMap((c) => problems(`/${c.name}`, c.options))).toEqual( [], ); @@ -64,6 +74,7 @@ describe('composition root', () => { const usedByComponents = [...registry.components.values()].flatMap( (c) => c.permission ?? [], ); + expect( [...used, ...usedByComponents].filter( (p) => p !== undefined && !declared.has(p), diff --git a/src/core/discord/router.test.ts b/tests/core/discord/router.test.ts similarity index 95% rename from src/core/discord/router.test.ts rename to tests/core/discord/router.test.ts index c077bcd..c7b8fd6 100644 --- a/src/core/discord/router.test.ts +++ b/tests/core/discord/router.test.ts @@ -1,9 +1,9 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { UserError } from '../../shared/errors.js'; -import type { AppContext, Feature } from '../feature.js'; -import { buildRegistry } from '../registry.js'; -import { createInteractionHandler } from './router.js'; +import { UserError } from '~/shared/errors'; +import type { AppContext, Feature } from '~/core/feature'; +import { buildRegistry } from '~/core/registry'; +import { createInteractionHandler } from '~/core/discord/router'; function context(allowed: boolean) { const require = vi.fn(async () => { @@ -15,6 +15,7 @@ function context(allowed: boolean) { log: pino({ level: 'silent' }), authz: { require, can: vi.fn() }, } as unknown as AppContext; + return { ctx, require }; } @@ -75,6 +76,7 @@ describe('interaction router', () => { it('routes public subcommands without a permission check', async () => { const { ctx, require } = context(false); + execute.mockClear(); await createInteractionHandler( registry, @@ -86,8 +88,10 @@ describe('interaction router', () => { it('enforces declared permissions before executing', async () => { const { ctx, require } = context(false); + execute.mockClear(); const interaction = commandInteraction('demo', 'manage'); + await createInteractionHandler(registry, ctx)(interaction as never); expect(require).toHaveBeenCalledWith(interaction.member, 'demo:manage'); expect(execute).not.toHaveBeenCalled(); @@ -98,8 +102,10 @@ describe('interaction router', () => { it('rechecks permissions on persistent components and passes arguments', async () => { const allowed = context(true); + execute.mockClear(); const interaction = componentInteraction('demo:press:42:x'); + await createInteractionHandler(registry, allowed.ctx)(interaction as never); expect(allowed.require).toHaveBeenCalledWith( interaction.member, @@ -111,6 +117,7 @@ describe('interaction router', () => { it('answers unknown components instead of failing silently', async () => { const { ctx } = context(true); const interaction = componentInteraction('gone:button:1'); + await createInteractionHandler(registry, ctx)(interaction as never); expect(interaction.reply).toHaveBeenCalledWith( expect.objectContaining({ content: 'This control is no longer active.' }), @@ -120,10 +127,12 @@ describe('interaction router', () => { it('hides unexpected errors behind a reference', async () => { const { ctx } = context(true); const interaction = commandInteraction('boom', null); + await createInteractionHandler(registry, ctx)(interaction as never); const [[reply]] = interaction.reply.mock.calls as unknown as [ [{ content: string }], ]; + expect(reply.content).toMatch( /^Something went wrong\. Reference: `\w{8}`$/, ); @@ -137,11 +146,13 @@ describe('interaction router', () => { deferred: true, editReply: vi.fn(async () => undefined), }; + await handle(pending as never); expect(pending.editReply).toHaveBeenCalledOnce(); expect(pending.reply).not.toHaveBeenCalled(); const answered = { ...commandInteraction('boom', null), replied: true }; + await handle(answered as never); expect(answered.followUp).toHaveBeenCalledOnce(); }); diff --git a/src/core/permissions/authorizer.test.ts b/tests/core/permissions/authorizer.test.ts similarity index 90% rename from src/core/permissions/authorizer.test.ts rename to tests/core/permissions/authorizer.test.ts index 138b2de..156eff9 100644 --- a/src/core/permissions/authorizer.test.ts +++ b/tests/core/permissions/authorizer.test.ts @@ -1,9 +1,9 @@ import type { GuildMember } from 'discord.js'; import { beforeAll, describe, expect, it } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import { UserError } from '../../shared/errors.js'; -import { createAuthorizer } from './authorizer.js'; -import { grant, listGrants, revoke } from './store.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { UserError } from '~/shared/errors'; +import { createAuthorizer } from '~/core/permissions/authorizer'; +import { grant, listGrants, revoke } from '~/core/permissions/store'; function member( guildId: string, @@ -25,6 +25,7 @@ describe.skipIf(noDatabase)('authorizer', () => { beforeAll(async () => { const db = testDb(); + await grant(db, { guildId, roleId: organizers, @@ -41,6 +42,7 @@ describe.skipIf(noDatabase)('authorizer', () => { it('denies by default and allows granted roles', async () => { const authz = createAuthorizer(testDb()); + expect(await authz.can(member(guildId, []), 'event:create')).toBe(false); expect(await authz.can(member(guildId, [organizers]), 'event:create')).toBe( true, @@ -50,15 +52,17 @@ describe.skipIf(noDatabase)('authorizer', () => { ); }); - it('combines grants from all of a member’s roles', async () => { + it('combines grants from all roles of a member', async () => { const authz = createAuthorizer(testDb()); const both = member(guildId, [organizers, helpers]); + expect(await authz.can(both, 'event:create')).toBe(true); expect(await authz.can(both, 'poll:create')).toBe(true); }); it('isolates grants per guild', async () => { const authz = createAuthorizer(testDb()); + expect( await authz.can(member(otherGuild, [organizers]), 'event:create'), ).toBe(false); @@ -66,6 +70,7 @@ describe.skipIf(noDatabase)('authorizer', () => { it('lets Discord administrators do everything', async () => { const authz = createAuthorizer(testDb()); + expect( await authz.can(member(guildId, [], true), 'permissions:manage'), ).toBe(true); @@ -75,6 +80,7 @@ describe.skipIf(noDatabase)('authorizer', () => { const db = testDb(); const authz = createAuthorizer(db); const role = snowflake(); + expect( await grant(db, { guildId, @@ -104,6 +110,7 @@ describe.skipIf(noDatabase)('authorizer', () => { it('require throws a user-facing error', async () => { const authz = createAuthorizer(testDb()); + await expect( authz.require(member(guildId, []), 'event:create'), ).rejects.toBeInstanceOf(UserError); diff --git a/src/core/registry.test.ts b/tests/core/registry.test.ts similarity index 95% rename from src/core/registry.test.ts rename to tests/core/registry.test.ts index fb96c76..67616e3 100644 --- a/src/core/registry.test.ts +++ b/tests/core/registry.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import type { Feature } from './feature.js'; -import { buildRegistry, customId, parseCustomId } from './registry.js'; +import type { Feature } from '~/core/feature'; +import { buildRegistry, customId, parseCustomId } from '~/core/registry'; const noop = async () => undefined; const noopJob = async () => null; @@ -19,6 +19,7 @@ describe('buildRegistry', () => { }, { name: 'b', permissions: [{ id: 'b:do', description: '' }] }, ]); + expect([...registry.commands.keys()]).toEqual(['alpha']); expect([...registry.components.keys()]).toEqual(['a:click']); expect([...registry.permissions.keys()]).toEqual(['b:do']); diff --git a/src/core/scheduler/scheduler.test.ts b/tests/core/scheduler/scheduler.test.ts similarity index 93% rename from src/core/scheduler/scheduler.test.ts rename to tests/core/scheduler/scheduler.test.ts index 660cf5e..9989b4b 100644 --- a/src/core/scheduler/scheduler.test.ts +++ b/tests/core/scheduler/scheduler.test.ts @@ -2,13 +2,13 @@ import { eq, sql } from 'drizzle-orm'; import { pino } from 'pino'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod'; -import { noDatabase, testDb } from '../../../tests/db.js'; -import { PermanentError } from '../../shared/errors.js'; -import { defineJob } from '../define.js'; -import type { AppContext } from '../feature.js'; -import { createScheduler, retryDelayMs } from './scheduler.js'; -import { scheduledJobs } from './schema.js'; -import { claimDueJobs } from './store.js'; +import { noDatabase, testDb } from '../../db'; +import { PermanentError } from '~/shared/errors'; +import { defineJob } from '~/core/define'; +import type { AppContext } from '~/core/feature'; +import { createScheduler, retryDelayMs } from '~/core/scheduler/scheduler'; +import { scheduledJobs } from '~/core/scheduler/schema'; +import { claimDueJobs } from '~/core/scheduler/store'; const log = pino({ level: 'silent' }); @@ -27,10 +27,13 @@ describe.skipIf(noDatabase)('scheduler', () => { if (!db) { throw new Error('unreachable'); } + const scheduler = createScheduler(db, new Map([[job.type, job]]), log); const ctx = { db, log } as unknown as AppContext; + return { db, scheduler, ctx }; }; + const past = () => new Date(Date.now() - 1000); const row = async (key: string) => { const { db: database } = setup(); @@ -38,6 +41,7 @@ describe.skipIf(noDatabase)('scheduler', () => { .select() .from(scheduledJobs) .where(eq(scheduledJobs.key, key)); + return found; }; @@ -48,6 +52,7 @@ describe.skipIf(noDatabase)('scheduler', () => { it('runs due jobs once and marks them done', async () => { const { scheduler, ctx } = setup(); + handle.mockResolvedValue(null); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'a' }); await scheduler.schedule( @@ -65,6 +70,7 @@ describe.skipIf(noDatabase)('scheduler', () => { it('replaces a pending job scheduled with the same key', async () => { const { scheduler, ctx } = setup(); + handle.mockResolvedValue(null); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'same' }); await scheduler.schedule(job, { n: 2 }, { runAt: past(), key: 'same' }); @@ -74,6 +80,7 @@ describe.skipIf(noDatabase)('scheduler', () => { it('does not run cancelled jobs', async () => { const { scheduler, ctx } = setup(); + await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'c' }); await scheduler.cancel('c'); expect(await scheduler.tick(ctx)).toBe(0); @@ -82,12 +89,14 @@ describe.skipIf(noDatabase)('scheduler', () => { it('retries transient failures with backoff, then fails', async () => { const { db: database, scheduler, ctx } = setup(); + handle.mockRejectedValue(new Error('discord down')); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'r' }); for (let attempt = 1; attempt <= 3; attempt++) { await scheduler.tick(ctx); const current = await row('r'); + expect(current?.attempts).toBe(attempt); if (attempt < 3) { expect(current?.status).toBe('pending'); @@ -98,6 +107,7 @@ describe.skipIf(noDatabase)('scheduler', () => { .where(eq(scheduledJobs.key, 'r')); } } + expect((await row('r'))?.status).toBe('failed'); expect((await row('r'))?.lastError).toBe('discord down'); expect(retryDelayMs(1)).toBe(30_000); @@ -106,6 +116,7 @@ describe.skipIf(noDatabase)('scheduler', () => { it('does not retry permanent failures or invalid payloads', async () => { const { db: database, scheduler, ctx } = setup(); + handle.mockRejectedValue(new PermanentError('user blocked DMs')); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'p' }); await database.insert(scheduledJobs).values({ @@ -123,10 +134,12 @@ describe.skipIf(noDatabase)('scheduler', () => { it('reschedules recurring jobs', async () => { const { scheduler, ctx } = setup(); const next = new Date(Date.now() + 86_400_000); + handle.mockResolvedValue({ rescheduleAt: next }); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'rec' }); await scheduler.tick(ctx); const current = await row('rec'); + expect(current?.status).toBe('pending'); expect(current?.runAt.getTime()).toBe(next.getTime()); expect(current?.attempts).toBe(0); @@ -134,9 +147,9 @@ describe.skipIf(noDatabase)('scheduler', () => { it('recovers jobs whose lease expired after a crash', async () => { const { db: database, scheduler, ctx } = setup(); + handle.mockResolvedValue(null); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'crash' }); - // Simulate a worker that claimed the job and died. await claimDueJobs(database, { types: [job.type], limit: 10, @@ -153,9 +166,11 @@ describe.skipIf(noDatabase)('scheduler', () => { it('never hands the same job to concurrent claimers', async () => { const { db: database, scheduler } = setup(); + for (let n = 0; n < 20; n++) { await scheduler.schedule(job, { n }, { runAt: past(), key: `k${n}` }); } + const claims = await Promise.all( Array.from({ length: 5 }, () => claimDueJobs(database, { @@ -166,12 +181,14 @@ describe.skipIf(noDatabase)('scheduler', () => { ), ); const ids = claims.flat().map((claimed) => claimed.id); + expect(new Set(ids).size).toBe(ids.length); expect(ids).toHaveLength(20); }); it('leaves jobs of unregistered types untouched', async () => { const { db: database, scheduler, ctx } = setup(); + await database.insert(scheduledJobs).values({ type: 'disabled:feature', payload: {}, diff --git a/tests/db.ts b/tests/db.ts index 28de6c2..33e0df0 100644 --- a/tests/db.ts +++ b/tests/db.ts @@ -1,9 +1,8 @@ import { afterAll } from 'vitest'; -import { connectDatabase, type Db } from '../src/db/client.js'; +import { connectDatabase, type Db } from '~/db/client'; const url = process.env.TEST_DATABASE_URL; -/** True when database tests cannot run; use with `describe.skipIf`. */ export const noDatabase = url === undefined; let database: ReturnType | undefined; @@ -12,7 +11,9 @@ export function testDb(): Db { if (url === undefined) { throw new Error('TEST_DATABASE_URL is not set'); } + database ??= connectDatabase(url); + return database.db; } @@ -23,8 +24,8 @@ afterAll(async () => { let counter = 0; -/** A unique snowflake-shaped ID so tests never collide on shared tables. */ export function snowflake(): string { counter += 1; + return `${Date.now()}${String(counter).padStart(5, '0')}`; } diff --git a/src/features/announcements/announcements.test.ts b/tests/features/announcements/announcements.test.ts similarity index 87% rename from src/features/announcements/announcements.test.ts rename to tests/features/announcements/announcements.test.ts index b8520f3..8e18096 100644 --- a/src/features/announcements/announcements.test.ts +++ b/tests/features/announcements/announcements.test.ts @@ -1,10 +1,14 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { render } from './index.js'; -import type { Announcement } from './schema.js'; -import { getAnnouncement, insertAnnouncement, transition } from './service.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { render } from '~/features/announcements'; +import type { Announcement } from '~/features/announcements/schema'; +import { + getAnnouncement, + insertAnnouncement, + transition, +} from '~/features/announcements/service'; const draft = (overrides: Partial = {}): Announcement => ({ id: 1, @@ -67,12 +71,13 @@ describe.skipIf(noDatabase)('announcement publishing', () => { transition(db, row.id, ['draft'], { status: 'publishing' }), ), ); + expect(claims.filter(Boolean)).toHaveLength(1); }); it('skips scheduled announcements that are long overdue', async () => { const db = testDb(); - const { announcementsFeature } = await import('./index.js'); + const { announcementsFeature } = await import('~/features/announcements'); const job = announcementsFeature.jobs?.[0]; const send = vi.fn(); const ctx = { @@ -83,6 +88,7 @@ describe.skipIf(noDatabase)('announcement publishing', () => { }, } as unknown as AppContext; const row = await insertAnnouncement(db, input()); + await transition(db, row.id, ['draft'], { status: 'scheduled', scheduledAt: new Date(Date.now() - 2 * 3_600_000), @@ -98,7 +104,7 @@ describe.skipIf(noDatabase)('announcement publishing', () => { it('publishes due scheduled announcements once', async () => { const db = testDb(); - const { announcementsFeature } = await import('./index.js'); + const { announcementsFeature } = await import('~/features/announcements'); const job = announcementsFeature.jobs?.[0]; const send = vi.fn(async () => ({ id: 'm1' })); const ctx = { @@ -109,11 +115,13 @@ describe.skipIf(noDatabase)('announcement publishing', () => { }, } as unknown as AppContext; const row = await insertAnnouncement(db, input()); + await transition(db, row.id, ['draft'], { status: 'scheduled', scheduledAt: new Date(), }); const info = { id: 1, runAt: new Date(), attempt: 1 }; + await job?.run({ announcementId: row.id }, info, ctx); await job?.run({ announcementId: row.id }, info, ctx); expect(send).toHaveBeenCalledOnce(); diff --git a/src/features/birthdays/birthdays.test.ts b/tests/features/birthdays/birthdays.test.ts similarity index 84% rename from src/features/birthdays/birthdays.test.ts rename to tests/features/birthdays/birthdays.test.ts index df63bb6..bb53e4f 100644 --- a/src/features/birthdays/birthdays.test.ts +++ b/tests/features/birthdays/birthdays.test.ts @@ -1,10 +1,9 @@ -import { DateTime } from 'luxon'; import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { nextDailyRun } from '../../shared/time.js'; -import { dailyJob } from './index.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { calendarDay, nextDailyRun } from '~/shared/time'; +import { dailyJob } from '~/features/birthdays'; import { celebratedOn, claimTodaysBirthdays, @@ -13,7 +12,7 @@ import { setBirthday, upcomingBirthdays, validateDate, -} from './service.js'; +} from '~/features/birthdays/service'; describe('birthday dates', () => { it('accepts 29 February and rejects impossible dates', () => { @@ -23,20 +22,21 @@ describe('birthday dates', () => { }); it('celebrates leap-day birthdays on 28 February in non-leap years', () => { - expect(celebratedOn(DateTime.local(2027, 2, 28))).toEqual([ + expect(celebratedOn({ year: 2027, month: 2, day: 28 })).toEqual([ { month: 2, day: 28 }, { month: 2, day: 29 }, ]); - expect(celebratedOn(DateTime.local(2028, 2, 28))).toEqual([ + expect(celebratedOn({ year: 2028, month: 2, day: 28 })).toEqual([ { month: 2, day: 28 }, ]); - expect(celebratedOn(DateTime.local(2028, 2, 29))).toEqual([ + expect(celebratedOn({ year: 2028, month: 2, day: 29 })).toEqual([ { month: 2, day: 29 }, ]); }); it('computes the next announcement hour in the guild timezone', () => { - const now = DateTime.fromISO('2026-06-01T10:00:00Z') as DateTime; + const now = new Date('2026-06-01T10:00:00Z'); + expect(nextDailyRun('Europe/Tallinn', 9, now).toISOString()).toBe( '2026-06-02T06:00:00.000Z', ); @@ -47,7 +47,7 @@ describe('birthday dates', () => { }); describe.skipIf(noDatabase)('birthday announcements', () => { - const today = DateTime.local(2027, 2, 28); + const today = { year: 2027, month: 2, day: 28 }; it('announces each birthday once per year and respects privacy', async () => { const db = testDb(); @@ -59,6 +59,7 @@ describe.skipIf(noDatabase)('birthday announcements', () => { snowflake(), snowflake(), ]; + await setBirthday(db, { guildId, userId: pub, @@ -96,11 +97,15 @@ describe.skipIf(noDatabase)('birthday announcements', () => { }); const claimed = await claimTodaysBirthdays(db, guildId, today); + expect(claimed).toHaveLength(3); expect(claimed).toEqual(expect.arrayContaining([pub, announce, leap])); expect(await claimTodaysBirthdays(db, guildId, today)).toEqual([]); expect( - await claimTodaysBirthdays(db, guildId, today.plus({ years: 1 })), + await claimTodaysBirthdays(db, guildId, { + ...today, + year: today.year + 1, + }), ).toHaveLength(2); }); @@ -108,6 +113,7 @@ describe.skipIf(noDatabase)('birthday announcements', () => { const db = testDb(); const guildId = snowflake(); const user = snowflake(); + await setBirthday(db, { guildId, userId: user, @@ -129,6 +135,7 @@ describe.skipIf(noDatabase)('birthday announcements', () => { snowflake(), snowflake(), ]; + await setBirthday(db, { guildId, userId: jan, @@ -157,11 +164,12 @@ describe.skipIf(noDatabase)('birthday announcements', () => { day: 6, visibility: 'announce', }); - const list = await upcomingBirthdays( - db, - guildId, - DateTime.local(2026, 6, 1), - ); + const list = await upcomingBirthdays(db, guildId, { + year: 2026, + month: 6, + day: 1, + }); + expect(list.map((b) => b.userId)).toEqual([jun, dec, jan]); }); @@ -169,7 +177,8 @@ describe.skipIf(noDatabase)('birthday announcements', () => { const db = testDb(); const guildId = snowflake(); const user = snowflake(); - const now = DateTime.now().setZone('Europe/Tallinn'); + const now = calendarDay(new Date(), 'Europe/Tallinn'); + await setBirthday(db, { guildId, userId: user, @@ -194,6 +203,7 @@ describe.skipIf(noDatabase)('birthday announcements', () => { } as unknown as AppContext; const info = { id: 1, runAt: new Date(), attempt: 1 }; const outcome = await dailyJob.run({ guildId }, info, ctx); + await dailyJob.run({ guildId }, info, ctx); expect(send).toHaveBeenCalledOnce(); expect(send).toHaveBeenCalledWith( diff --git a/src/features/events/events.test.ts b/tests/features/events/events.test.ts similarity index 92% rename from src/features/events/events.test.ts rename to tests/features/events/events.test.ts index 18e67b9..9f8c342 100644 --- a/src/features/events/events.test.ts +++ b/tests/features/events/events.test.ts @@ -1,16 +1,16 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { UserError } from '../../shared/errors.js'; -import { createEvent, remindJob } from './index.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { UserError } from '~/shared/errors'; +import { createEvent, remindJob } from '~/features/events'; import { insertEvent, listAttendees, rsvpCounts, setRsvp, updateEvent, -} from './service.js'; +} from '~/features/events/service'; const base = () => ({ guildId: snowflake(), @@ -27,12 +27,14 @@ describe.skipIf(noDatabase)('event RSVPs', () => { if (!db) { throw new Error('unreachable'); } + return db; }; it('records RSVPs and lets members change them without duplicates', async () => { const event = await insertEvent(database(), base()); const user = snowflake(); + await setRsvp(database(), event.id, user, 'going'); await setRsvp(database(), event.id, user, 'maybe'); await setRsvp(database(), event.id, user, 'maybe'); @@ -49,6 +51,7 @@ describe.skipIf(noDatabase)('event RSVPs', () => { it('enforces capacity but lets attendees keep their spot', async () => { const event = await insertEvent(database(), { ...base(), capacity: 1 }); const [first, second] = [snowflake(), snowflake()]; + await setRsvp(database(), event.id, first, 'going'); await setRsvp(database(), event.id, first, 'going'); await expect( @@ -67,12 +70,14 @@ describe.skipIf(noDatabase)('event RSVPs', () => { setRsvp(database(), event.id, snowflake(), 'going'), ), ); + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(3); expect((await rsvpCounts(database(), event.id)).going).toBe(3); }); it('closes RSVPs once cancelled', async () => { const event = await insertEvent(database(), base()); + await updateEvent(database(), event.id, { status: 'cancelled' }); await expect( setRsvp(database(), event.id, snowflake(), 'going'), @@ -81,6 +86,7 @@ describe.skipIf(noDatabase)('event RSVPs', () => { it('validates times and capacity', async () => { const start = new Date(Date.now() + 3_600_000); + await expect( insertEvent(database(), { ...base(), startsAt: start, endsAt: start }), ).rejects.toThrow('end'); @@ -104,8 +110,8 @@ describe.skipIf(noDatabase)('event RSVPs', () => { ...base(), reminderMinutes: [60, 600], }); + expect(event.messageId).not.toBeNull(); - // 600 minutes before a start 3h away is already past, so only one job. expect(schedule).toHaveBeenCalledOnce(); expect(schedule).toHaveBeenCalledWith( remindJob, diff --git a/src/features/movies/movies.test.ts b/tests/features/movies/movies.test.ts similarity index 92% rename from src/features/movies/movies.test.ts rename to tests/features/movies/movies.test.ts index 8d5e91d..f33a014 100644 --- a/src/features/movies/movies.test.ts +++ b/tests/features/movies/movies.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { castVote, finishPoll, insertPoll } from '../polls/service.js'; -import { pickMovie } from './index.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { castVote, finishPoll, insertPoll } from '~/features/polls/service'; +import { pickMovie } from '~/features/movies'; import { listUnwatched, markWatched, @@ -10,7 +10,7 @@ import { recordScreening, suggestMovie, watchHistory, -} from './service.js'; +} from '~/features/movies/service'; describe('normalizeTitle', () => { it('ignores case, punctuation and spacing', () => { @@ -35,6 +35,7 @@ describe.skipIf(noDatabase)('movies', () => { it('rejects duplicate suggestions and points out watched ones', async () => { const guildId = snowflake(); const movie = await suggest(guildId, 'Paprika'); + await expect(suggest(guildId, 'paprika!')).rejects.toThrow( 'already suggested', ); @@ -64,9 +65,11 @@ describe.skipIf(noDatabase)('movies', () => { source: 'movies', options: [a, b].map((m) => ({ label: m.title, ref: String(m.id) })), }); + await expect(pickMovie(ctx(), guildId, null)).rejects.toThrow('close'); const [optionA, optionB] = poll.options.map((o) => o.id); + await castVote(testDb(), poll.id, snowflake(), [optionA ?? 0]); await castVote(testDb(), poll.id, snowflake(), [optionB ?? 0]); await finishPoll(testDb(), poll.id, 'closed'); @@ -81,6 +84,7 @@ describe.skipIf(noDatabase)('movies', () => { source: 'movies', options: [a, b].map((m) => ({ label: m.title, ref: String(m.id) })), }); + await castVote(testDb(), second.id, snowflake(), [ second.options[0]?.id ?? 0, ]); @@ -94,6 +98,7 @@ describe.skipIf(noDatabase)('movies', () => { it('tracks screenings and history', async () => { const guildId = snowflake(); const movie = await suggest(guildId, 'Heat'); + await recordScreening(testDb(), { guildId, suggestionId: movie.id, diff --git a/src/features/permissions/permissions.test.ts b/tests/features/permissions/permissions.test.ts similarity index 93% rename from src/features/permissions/permissions.test.ts rename to tests/features/permissions/permissions.test.ts index 7ffa408..71b4f6e 100644 --- a/src/features/permissions/permissions.test.ts +++ b/tests/features/permissions/permissions.test.ts @@ -1,7 +1,7 @@ import type { GuildMember, Role } from 'discord.js'; import { describe, expect, it } from 'vitest'; -import type { Authorizer } from '../../core/feature.js'; -import { checkDelegation } from './index.js'; +import type { Authorizer } from '~/core/feature'; +import { checkDelegation } from '~/features/permissions'; const role = {} as Role; const actor = (options: { admin?: boolean; above?: boolean }) => diff --git a/src/features/polls/polls.test.ts b/tests/features/polls/polls.test.ts similarity index 93% rename from src/features/polls/polls.test.ts rename to tests/features/polls/polls.test.ts index 14e862c..4983d47 100644 --- a/src/features/polls/polls.test.ts +++ b/tests/features/polls/polls.test.ts @@ -1,9 +1,9 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { UserError } from '../../shared/errors.js'; -import { closeJob, renderPoll } from './index.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { UserError } from '~/shared/errors'; +import { closeJob, renderPoll } from '~/features/polls'; import { castVote, finishPoll, @@ -12,7 +12,7 @@ import { getVoterChoices, insertPoll, type NewPoll, -} from './service.js'; +} from '~/features/polls/service'; const base = (overrides: Partial = {}): NewPoll => ({ guildId: snowflake(), @@ -39,6 +39,7 @@ describe.skipIf(noDatabase)('polls', () => { const poll = await insertPoll(db(), base()); const [pizza, sushi] = poll.options; const user = snowflake(); + await castVote(db(), poll.id, user, [pizza?.id ?? 0]); await castVote(db(), poll.id, user, [sushi?.id ?? 0]); expect(await getVoterChoices(db(), poll.id, user)).toEqual([sushi?.id]); @@ -51,6 +52,7 @@ describe.skipIf(noDatabase)('polls', () => { const poll = await insertPoll(db(), base({ multiple: true })); const ids = poll.options.map((o) => o.id); const user = snowflake(); + await castVote(db(), poll.id, user, ids); expect((await getResults(db(), poll)).voters).toBe(1); expect((await getResults(db(), poll)).options.map((o) => o.votes)).toEqual([ @@ -63,6 +65,7 @@ describe.skipIf(noDatabase)('polls', () => { it('rejects options from another poll', async () => { const poll = await insertPoll(db(), base()); const other = await insertPoll(db(), base()); + await expect( castVote(db(), poll.id, snowflake(), [other.options[0]?.id ?? 0]), ).rejects.toThrow('not part'); @@ -71,19 +74,23 @@ describe.skipIf(noDatabase)('polls', () => { it('reports ties and winners', async () => { const poll = await insertPoll(db(), base()); const [pizza, sushi] = poll.options.map((o) => o.id); + await castVote(db(), poll.id, snowflake(), [pizza ?? 0]); await castVote(db(), poll.id, snowflake(), [sushi ?? 0]); const tied = await getResults(db(), poll); + expect(tied.tie).toBe(true); expect(tied.winners.map((w) => w.label)).toEqual(['Pizza', 'Sushi']); await castVote(db(), poll.id, snowflake(), [sushi ?? 0]); const won = await getResults(db(), poll); + expect(won.tie).toBe(false); expect(won.winners.map((w) => w.label)).toEqual(['Sushi']); }); it('refuses votes after closing or the deadline', async () => { const poll = await insertPoll(db(), base()); + expect(await finishPoll(db(), poll.id, 'closed')).toBeDefined(); expect(await finishPoll(db(), poll.id, 'closed')).toBeUndefined(); await expect( @@ -94,6 +101,7 @@ describe.skipIf(noDatabase)('polls', () => { db(), base({ closesAt: new Date(Date.now() - 1000) }), ); + await expect( castVote(db(), expired.id, snowflake(), [expired.options[0]?.id ?? 0]), ).rejects.toThrow('closed'); @@ -104,24 +112,27 @@ describe.skipIf(noDatabase)('polls', () => { const [pizza, sushi] = poll.options.map((o) => o.id); const user = snowflake(); const voters = Array.from({ length: 20 }, () => snowflake()); + await Promise.all([ ...voters.map((voter) => castVote(db(), poll.id, voter, [pizza ?? 0])), - // The same member switching rapidly must end with exactly one vote. ...Array.from({ length: 10 }, (_, n) => castVote(db(), poll.id, user, [(n % 2 === 0 ? pizza : sushi) ?? 0]), ), ]); const results = await getResults(db(), poll); + expect(results.voters).toBe(21); expect(await getVoterChoices(db(), poll.id, user)).toHaveLength(1); }); it('closes on schedule and hides live counts when requested', async () => { const poll = await insertPoll(db(), base({ showResults: 'closed' })); + await castVote(db(), poll.id, snowflake(), [poll.options[0]?.id ?? 0]); const hidden = JSON.stringify( renderPoll(poll, await getResults(db(), poll)).embeds, ); + expect(hidden).not.toContain('█'); const ctx = { @@ -129,15 +140,18 @@ describe.skipIf(noDatabase)('polls', () => { log: pino({ level: 'silent' }), client: { channels: { fetch: vi.fn() } }, } as unknown as AppContext; + await closeJob.run( { pollId: poll.id }, { id: 1, runAt: new Date(), attempt: 1 }, ctx, ); const closed = await getPoll(db(), poll.id); + expect(closed?.status).toBe('closed'); if (closed) { const rendered = renderPoll(closed, await getResults(db(), closed)); + expect(JSON.stringify(rendered.embeds)).toContain('Winner'); expect(rendered.components).toEqual([]); } diff --git a/src/features/redmine/redmine.test.ts b/tests/features/redmine/redmine.test.ts similarity index 93% rename from src/features/redmine/redmine.test.ts rename to tests/features/redmine/redmine.test.ts index dde73b4..8680769 100644 --- a/src/features/redmine/redmine.test.ts +++ b/tests/features/redmine/redmine.test.ts @@ -1,20 +1,20 @@ import { randomBytes } from 'node:crypto'; import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { Config } from '../../core/config.js'; -import type { AppContext } from '../../core/feature.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { Config } from '~/core/config'; +import type { AppContext } from '~/core/feature'; import type { RedmineClient, RedmineIssue, -} from '../../integrations/redmine/client.js'; -import { createRedmineFeature } from './index.js'; -import { createNotificationJobs } from './notifications.js'; +} from '~/integrations/redmine/client'; +import { createRedmineFeature } from '~/features/redmine'; +import { createNotificationJobs } from '~/features/redmine/notifications'; import { addSubscription, issueNotifications, listSubscriptions, -} from './service.js'; +} from '~/features/redmine/service'; const since = new Date('2026-11-10T00:00:00Z'); const statuses = new Map([ @@ -76,6 +76,7 @@ describe('issueNotifications', () => { statuses, 'https://r/issues/42', ); + expect(notifications.map((n) => n.key)).toEqual([ 'issue:42:created', 'journal:1', @@ -100,6 +101,7 @@ describe('issueNotifications', () => { statuses, 'u', ); + expect(notes).toEqual([]); }); }); @@ -114,6 +116,7 @@ describe('createRedmineFeature', () => { REDMINE_BASE_URL: 'https://r', CREDENTIAL_ENCRYPTION_KEY: randomBytes(32).toString('base64'), } as Config); + expect(feature?.jobs).toEqual([]); }); }); @@ -122,6 +125,7 @@ describe.skipIf(noDatabase)('redmine polling', () => { it('notifies once per change and advances the checkpoint', async () => { const db = testDb(); const channelId = snowflake(); + await addSubscription(db, { guildId: snowflake(), channelId, @@ -151,11 +155,14 @@ describe.skipIf(noDatabase)('redmine polling', () => { const info = { id: 1, runAt: new Date(), attempt: 1 }; const outcome = await poll?.run({}, info, ctx); + await poll?.run({}, info, ctx); const ours = send.mock.calls.length; + expect(ours).toBe(2); expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); const subscriptions = await listSubscriptions(db, 0, 1000); + expect( subscriptions .find((s) => s.channelId === channelId) @@ -177,6 +184,7 @@ describe.skipIf(noDatabase)('redmine polling', () => { client: { channels: { fetch: vi.fn() } }, } as unknown as AppContext; const [poll] = createNotificationJobs(redmine, 'https://r/').jobs; + await expect( poll?.run({}, { id: 1, runAt: new Date(), attempt: 1 }, ctx), ).resolves.toBeDefined(); diff --git a/src/features/reminders/reminders.test.ts b/tests/features/reminders/reminders.test.ts similarity index 89% rename from src/features/reminders/reminders.test.ts rename to tests/features/reminders/reminders.test.ts index 361b35d..10aaa34 100644 --- a/src/features/reminders/reminders.test.ts +++ b/tests/features/reminders/reminders.test.ts @@ -1,11 +1,15 @@ import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { PermanentError, UserError } from '../../shared/errors.js'; -import { createReminder, deliverJob } from './index.js'; -import { getReminder, insertReminder, maxActivePerUser } from './service.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { PermanentError, UserError } from '~/shared/errors'; +import { createReminder, deliverJob } from '~/features/reminders'; +import { + getReminder, + insertReminder, + maxActivePerUser, +} from '~/features/reminders/service'; const cannotDm = new DiscordAPIError( { @@ -28,6 +32,7 @@ function context() { client: { users: { fetch: async () => ({ send }) } }, scheduler: { schedule, cancel: vi.fn() }, } as unknown as AppContext; + return { ctx, send, schedule }; } @@ -46,6 +51,7 @@ describe.skipIf(noDatabase)('reminders', () => { it('schedules a job keyed to the reminder', async () => { const { ctx, schedule } = context(); const reminder = await createReminder(ctx, base()); + expect(schedule).toHaveBeenCalledWith( deliverJob, { reminderId: reminder.id }, @@ -59,6 +65,7 @@ describe.skipIf(noDatabase)('reminders', () => { it('delivers one-off reminders by DM and completes them', async () => { const { ctx, send } = context(); const reminder = await insertReminder(ctx.db, base()); + expect( await deliverJob.run({ reminderId: reminder.id }, info, ctx), ).toBeNull(); @@ -78,6 +85,7 @@ describe.skipIf(noDatabase)('reminders', () => { info, ctx, ); + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); expect(outcome?.rescheduleAt.getTime()).toBeLessThanOrEqual( Date.now() + 86_400_000, @@ -87,8 +95,10 @@ describe.skipIf(noDatabase)('reminders', () => { it('fails permanently when DMs are closed', async () => { const { ctx, send } = context(); + send.mockRejectedValue(cannotDm); const reminder = await insertReminder(ctx.db, base()); + await expect( deliverJob.run({ reminderId: reminder.id }, info, ctx), ).rejects.toBeInstanceOf(PermanentError); @@ -98,7 +108,8 @@ describe.skipIf(noDatabase)('reminders', () => { it('skips cancelled reminders', async () => { const { ctx, send } = context(); const reminder = await insertReminder(ctx.db, base()); - const { updateReminder } = await import('./service.js'); + const { updateReminder } = await import('~/features/reminders/service'); + await updateReminder(ctx.db, reminder.id, { status: 'cancelled' }); await deliverJob.run({ reminderId: reminder.id }, info, ctx); expect(send).not.toHaveBeenCalled(); @@ -107,9 +118,11 @@ describe.skipIf(noDatabase)('reminders', () => { it('limits active reminders per user and message length', async () => { const { ctx } = context(); const input = base(); + for (let n = 0; n < maxActivePerUser; n++) { await insertReminder(ctx.db, input); } + await expect(insertReminder(ctx.db, input)).rejects.toBeInstanceOf( UserError, ); diff --git a/src/features/roles/roles.test.ts b/tests/features/roles/roles.test.ts similarity index 94% rename from src/features/roles/roles.test.ts rename to tests/features/roles/roles.test.ts index 985801a..1ce6fbd 100644 --- a/src/features/roles/roles.test.ts +++ b/tests/features/roles/roles.test.ts @@ -5,16 +5,20 @@ import { } from 'discord.js'; import { pino } from 'pino'; import { beforeAll, describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../../tests/db.js'; -import type { AppContext } from '../../core/feature.js'; -import { requireAbove, selfAssignProblem } from './guards.js'; -import { handleReaction, legacyMessage, legacyRoles } from './legacy.js'; +import { noDatabase, snowflake, testDb } from '../../db'; +import type { AppContext } from '~/core/feature'; +import { requireAbove, selfAssignProblem } from '~/features/roles/guards'; +import { + handleReaction, + legacyMessage, + legacyRoles, +} from '~/features/roles/legacy'; import { addPanelRole, createPanel, replacePanelRoles, setPanelMessage, -} from './service.js'; +} from '~/features/roles/service'; function role( overrides: Partial<{ @@ -44,6 +48,7 @@ describe('legacy role mapping', () => { HELPDESK_ROLE_ID: 'h', KULTUUR_ROLE_ID: 'k', }; + expect(legacyRoles({ config } as never)).toEqual([ { emoji: '1️⃣', roleId: 't', label: 'Tarkvara' }, { emoji: '2️⃣', roleId: 'h', label: 'Helpdesk' }, @@ -81,6 +86,7 @@ describe('role guards', () => { guild: { ownerId: 'owner' }, roles: { highest: { comparePositionTo: () => position } }, }) as never; + expect(() => requireAbove(actor(1), role())).not.toThrow(); expect(() => requireAbove(actor(0), role())).toThrow( 'not below your highest role', @@ -128,6 +134,7 @@ describe.skipIf(noDatabase)('reaction role handling', () => { title: 'Legacy', createdBy: 'bot', }); + await setPanelMessage(ctx.db, panelId, messageId); await replacePanelRoles(ctx.db, panelId, [ { roleId, label: 'Tarkvara', emoji: '1️⃣' }, @@ -159,6 +166,7 @@ describe.skipIf(noDatabase)('reaction role handling', () => { title: 'x', createdBy: 'u', }); + await addPanelRole(ctx.db, panelId, { roleId: 'gone', label: 'Gone', diff --git a/tests/global-setup.ts b/tests/global-setup.ts index fe2655b..56e57b8 100644 --- a/tests/global-setup.ts +++ b/tests/global-setup.ts @@ -1,19 +1,23 @@ import postgres from 'postgres'; -import { connectDatabase, runMigrations } from '../src/db/client.js'; +import { connectDatabase, runMigrations } from '~/db/client'; -/** Recreates the test database schema from migrations before the run. */ export default async function setup(): Promise { const url = process.env.TEST_DATABASE_URL; + if (url === undefined) { console.warn('TEST_DATABASE_URL is not set; database tests are skipped.'); + return; } + const sql = postgres(url, { onnotice: () => null }); + await sql`DROP SCHEMA IF EXISTS public CASCADE`; await sql`DROP SCHEMA IF EXISTS drizzle CASCADE`; await sql`CREATE SCHEMA public`; await sql.end(); const database = connectDatabase(url); + await runMigrations(database.db); await database.close(); } diff --git a/src/integrations/redmine/client.test.ts b/tests/integrations/redmine/client.test.ts similarity index 97% rename from src/integrations/redmine/client.test.ts rename to tests/integrations/redmine/client.test.ts index fec72f7..03a3a71 100644 --- a/src/integrations/redmine/client.test.ts +++ b/tests/integrations/redmine/client.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest'; -import { RedmineClient, RedmineError } from './client.js'; +import { RedmineClient, RedmineError } from '~/integrations/redmine/client'; const issue = { id: 7, @@ -18,6 +18,7 @@ const json = (status: number, body: unknown) => function client(...responses: Array) { const fetch = vi.fn(); + for (const response of responses) { if (response instanceof Error) { fetch.mockRejectedValueOnce(response); @@ -25,6 +26,7 @@ function client(...responses: Array) { fetch.mockResolvedValueOnce(response); } } + return { fetch, redmine: new RedmineClient('https://redmine.example', 'secret', { fetch }), @@ -37,6 +39,7 @@ const kind = async (promise: Promise) => { } catch (error) { return error instanceof RedmineError ? error.kind : 'other'; } + return 'none'; }; @@ -50,9 +53,11 @@ describe('RedmineClient', () => { assignedToMe: true, updatedSince: new Date('2026-11-01T10:00:00.123Z'), }); + expect(result.issues[0]?.subject).toBe('Fix login'); const [input, init] = fetch.mock.calls[0] ?? []; const url = input instanceof URL ? input.href : ''; + expect(url).toContain('project_id=web'); expect(url).toContain('assigned_to_id=me'); expect(decodeURIComponent(url)).toContain( @@ -63,6 +68,7 @@ describe('RedmineClient', () => { it('rejects responses that do not match the expected shape', async () => { const { redmine } = client(json(200, { issue: { id: 'seven' } })); + expect(await kind(redmine.getIssue(7))).toBe('invalid_response'); }); @@ -72,6 +78,7 @@ describe('RedmineClient', () => { [404, 'not_found'], ])('maps HTTP %i to %s', async (status, expected) => { const { redmine } = client(json(status, {})); + expect(await kind(redmine.currentUser())).toBe(expected); }); @@ -79,6 +86,7 @@ describe('RedmineClient', () => { const { redmine } = client( json(422, { errors: ['Subject cannot be blank'] }), ); + await expect( redmine.createIssue({ project_id: 1, subject: '' }), ).rejects.toThrow('Subject cannot be blank'); @@ -87,10 +95,12 @@ describe('RedmineClient', () => { it('retries reads once on timeouts but never retries writes', async () => { const timeout = new DOMException('timed out', 'TimeoutError'); const read = client(timeout, json(200, { user: { id: 1, login: 'mari' } })); + expect((await read.redmine.currentUser()).login).toBe('mari'); expect(read.fetch).toHaveBeenCalledTimes(2); const write = client(timeout, json(204, undefined)); + expect(await kind(write.redmine.updateIssue(7, { notes: 'hi' }))).toBe( 'unavailable', ); @@ -99,6 +109,7 @@ describe('RedmineClient', () => { it('treats server errors as unavailable', async () => { const { redmine } = client(json(502, {}), json(503, {})); + expect(await kind(redmine.listProjects())).toBe('unavailable'); }); }); diff --git a/src/shared/crypto.test.ts b/tests/shared/crypto.test.ts similarity index 94% rename from src/shared/crypto.test.ts rename to tests/shared/crypto.test.ts index c3b2b72..0300d62 100644 --- a/src/shared/crypto.test.ts +++ b/tests/shared/crypto.test.ts @@ -1,12 +1,13 @@ import { randomBytes } from 'node:crypto'; import { describe, expect, it } from 'vitest'; -import { createSecretBox } from './crypto.js'; +import { createSecretBox } from '~/shared/crypto'; describe('createSecretBox', () => { const box = createSecretBox(randomBytes(32).toString('base64')); it('round-trips without leaking the plaintext', () => { const sealed = box.encrypt('api-key-123'); + expect(sealed).not.toContain('api-key-123'); expect(box.encrypt('api-key-123')).not.toBe(sealed); expect(box.decrypt(sealed)).toBe('api-key-123'); @@ -19,6 +20,7 @@ describe('createSecretBox', () => { ...parts.slice(0, 3), Buffer.from('x').toString('base64'), ].join(':'); + expect(() => box.decrypt(tampered)).toThrow(); expect(() => createSecretBox(randomBytes(32).toString('base64')).decrypt(sealed), diff --git a/src/shared/time.test.ts b/tests/shared/time.test.ts similarity index 89% rename from src/shared/time.test.ts rename to tests/shared/time.test.ts index ba25b39..6db9270 100644 --- a/src/shared/time.test.ts +++ b/tests/shared/time.test.ts @@ -1,14 +1,14 @@ import { describe, expect, it } from 'vitest'; -import { UserError } from './errors.js'; +import { UserError } from '~/shared/errors'; import { nextFutureOccurrence, nextOccurrence, parseFutureWhen, parseWhen, -} from './time.js'; +} from '~/shared/time'; const zone = 'Europe/Tallinn'; -const now = new Date('2026-03-10T10:00:00Z'); // 12:00 in Tallinn +const now = new Date('2026-03-10T10:00:00Z'); describe('parseWhen', () => { it.each([ @@ -54,8 +54,8 @@ describe('parseWhen', () => { describe('recurrence', () => { it('keeps the wall-clock time across a DST change', () => { - // Tallinn moves to summer time on 2026-03-29. - const before = new Date('2026-03-28T07:00:00Z'); // 09:00 EET + const before = new Date('2026-03-28T07:00:00Z'); + expect(nextOccurrence(before, 'daily', zone).toISOString()).toBe( '2026-03-29T06:00:00.000Z', ); @@ -63,6 +63,7 @@ describe('recurrence', () => { it('skips occurrences missed while offline', () => { const old = new Date('2026-03-01T10:00:00Z'); + expect(nextFutureOccurrence(old, 'weekly', 'UTC', now).toISOString()).toBe( '2026-03-15T10:00:00.000Z', ); From 7ab47d080d9ec61221e0733d75a2f80401087251 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:10:25 +0200 Subject: [PATCH 019/199] refactor: replace luxon with date-fns, drop comments, use ~/ imports --- scripts/migrate.ts | 4 +- scripts/register-commands.ts | 9 +- src/app.ts | 49 ++++--- src/core/config.ts | 7 +- src/core/define.ts | 15 +- src/core/discord/client.ts | 5 - src/core/discord/errors.ts | 4 +- src/core/discord/registration.ts | 5 +- src/core/discord/router.ts | 28 ++-- src/core/feature.ts | 21 +-- src/core/guild-settings.ts | 4 +- src/core/logger.ts | 1 + src/core/permissions/authorizer.ts | 18 +-- src/core/permissions/store.ts | 10 +- src/core/registry.ts | 13 +- src/core/scheduler/scheduler.ts | 29 ++-- src/core/scheduler/store.ts | 17 +-- src/db/client.ts | 7 +- src/features/announcements/index.ts | 75 +++++++--- src/features/announcements/schema.ts | 1 - src/features/announcements/service.ts | 17 +-- src/features/birthdays/index.ts | 87 +++++++----- src/features/birthdays/schema.ts | 4 - src/features/birthdays/service.ts | 45 +++--- src/features/events/index.ts | 111 +++++++++++---- src/features/events/schema.ts | 4 - src/features/events/service.ts | 25 +++- src/features/movies/index.ts | 49 ++++--- src/features/movies/schema.ts | 4 - src/features/movies/service.ts | 21 ++- src/features/permissions/index.ts | 28 ++-- src/features/polls/index.ts | 69 ++++++++-- src/features/polls/schema.ts | 2 - src/features/polls/service.ts | 38 ++++-- src/features/redmine/index.ts | 82 +++++++---- src/features/redmine/notifications.ts | 142 +++++++++++-------- src/features/redmine/schema.ts | 3 - src/features/redmine/service.ts | 31 +++-- src/features/reminders/index.ts | 55 +++++--- src/features/reminders/schema.ts | 1 - src/features/reminders/service.ts | 18 ++- src/features/roles/guards.ts | 10 +- src/features/roles/index.ts | 48 ++++--- src/features/roles/legacy.ts | 58 +++++--- src/features/roles/panels.ts | 33 ++++- src/features/roles/schema.ts | 1 - src/features/roles/service.ts | 22 ++- src/features/settings/index.ts | 14 +- src/index.ts | 10 +- src/integrations/redmine/client.ts | 51 +++++-- src/shared/crypto.ts | 11 +- src/shared/time.ts | 188 ++++++++++++++++++-------- 52 files changed, 1039 insertions(+), 565 deletions(-) diff --git a/scripts/migrate.ts b/scripts/migrate.ts index c98abb7..1c898d9 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -1,9 +1,9 @@ import { z } from 'zod'; -import { connectDatabase, runMigrations } from '../src/db/client.js'; +import { connectDatabase, runMigrations } from '~/db/client'; -// The bot also migrates on startup; this runs migrations without starting it. const url = z.url().parse(process.env.DATABASE_URL); const database = connectDatabase(url); + try { await runMigrations(database.db); console.log('Migrations applied.'); diff --git a/scripts/register-commands.ts b/scripts/register-commands.ts index cb7c0f9..d9d3480 100644 --- a/scripts/register-commands.ts +++ b/scripts/register-commands.ts @@ -1,11 +1,13 @@ -import { createRegistry } from '../src/app.js'; -import { loadConfig } from '../src/core/config.js'; -import { registerCommands } from '../src/core/discord/registration.js'; +import { createRegistry } from '~/app'; +import { loadConfig } from '~/core/config'; +import { registerCommands } from '~/core/discord/registration'; const config = loadConfig(); + if (config.DISCORD_APPLICATION_ID === undefined) { throw new Error('DISCORD_APPLICATION_ID is required to register commands'); } + const count = await registerCommands(createRegistry(config), { token: config.DISCORD_TOKEN, applicationId: config.DISCORD_APPLICATION_ID, @@ -15,4 +17,5 @@ const scope = config.DISCORD_GUILD_ID === undefined ? 'globally' : `in guild ${config.DISCORD_GUILD_ID}`; + console.log(`Registered ${count} commands ${scope}.`); diff --git a/src/app.ts b/src/app.ts index cf78038..deec30b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,28 +1,24 @@ import { Events, type Client } from 'discord.js'; -import type { Config } from './core/config.js'; -import { createClient } from './core/discord/client.js'; -import { createInteractionHandler } from './core/discord/router.js'; -import type { AppContext, Feature } from './core/feature.js'; -import type { Logger } from './core/logger.js'; -import { createAuthorizer } from './core/permissions/authorizer.js'; -import { buildRegistry, type Registry } from './core/registry.js'; -import { createScheduler } from './core/scheduler/scheduler.js'; -import { connectDatabase, runMigrations } from './db/client.js'; -import { announcementsFeature } from './features/announcements/index.js'; -import { birthdaysFeature } from './features/birthdays/index.js'; -import { eventsFeature } from './features/events/index.js'; -import { moviesFeature } from './features/movies/index.js'; -import { createPermissionsFeature } from './features/permissions/index.js'; -import { pollsFeature } from './features/polls/index.js'; -import { createRedmineFeature } from './features/redmine/index.js'; -import { remindersFeature } from './features/reminders/index.js'; -import { rolesFeature } from './features/roles/index.js'; -import { settingsFeature } from './features/settings/index.js'; +import type { Config } from '~/core/config'; +import { createClient } from '~/core/discord/client'; +import { createInteractionHandler } from '~/core/discord/router'; +import type { AppContext, Feature } from '~/core/feature'; +import type { Logger } from '~/core/logger'; +import { createAuthorizer } from '~/core/permissions/authorizer'; +import { buildRegistry, type Registry } from '~/core/registry'; +import { createScheduler } from '~/core/scheduler/scheduler'; +import { connectDatabase, runMigrations } from '~/db/client'; +import { announcementsFeature } from '~/features/announcements'; +import { birthdaysFeature } from '~/features/birthdays'; +import { eventsFeature } from '~/features/events'; +import { moviesFeature } from '~/features/movies'; +import { createPermissionsFeature } from '~/features/permissions'; +import { pollsFeature } from '~/features/polls'; +import { createRedmineFeature } from '~/features/redmine'; +import { remindersFeature } from '~/features/reminders'; +import { rolesFeature } from '~/features/roles'; +import { settingsFeature } from '~/features/settings'; -/** - * The composition root: every feature the bot runs is listed here. Removing - * a line disables that feature; its pending jobs stay in the database. - */ export function createRegistry(config: Config): Registry { const features: Feature[] = [ rolesFeature, @@ -36,10 +32,13 @@ export function createRegistry(config: Config): Registry { moviesFeature, ]; const redmine = createRedmineFeature(config); + if (redmine) { features.push(redmine); } + const registry = buildRegistry(features); + return registry; } @@ -50,7 +49,6 @@ function waitForReady(client: Client, token: string): Promise> { }); } -/** Starts the bot and returns a function that shuts it down gracefully. */ export async function startApp( config: Config, log: Logger, @@ -84,7 +82,9 @@ export async function startApp( }); } } + const handleInteraction = createInteractionHandler(registry, ctx); + client.on(Events.InteractionCreate, (interaction) => { handleInteraction(interaction).catch((error: unknown) => { log.error({ err: error }, 'Interaction handler crashed'); @@ -94,7 +94,6 @@ export async function startApp( log.error({ err: error }, 'Discord client error'); }); - // A feature that fails to start is logged, not fatal to the others. await Promise.all( registry.features.map(async (feature) => { try { diff --git a/src/core/config.ts b/src/core/config.ts index a40ea17..7546b06 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -1,7 +1,6 @@ -import { IANAZone } from 'luxon'; +import { isZone } from '~/shared/time'; import { z } from 'zod'; -// Blank values in .env files arrive as '' and mean "not set". const optional = (schema: T) => z.preprocess( (value) => (value === '' ? undefined : value), @@ -23,7 +22,7 @@ const envSchema = z.object({ DEFAULT_TIMEZONE: z .string() .default('Europe/Tallinn') - .refine((zone) => IANAZone.isValidZone(zone), 'must be an IANA timezone'), + .refine((zone) => isZone(zone), 'must be an IANA timezone'), ROLE_SELECTION_CHANNEL_ID: optional(snowflake), TARKVARA_ROLE_ID: optional(snowflake), @@ -46,8 +45,10 @@ export type Config = z.infer; export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const result = envSchema.safeParse(env); + if (!result.success) { throw new Error(`Invalid configuration:\n${z.prettifyError(result.error)}`); } + return result.data; } diff --git a/src/core/define.ts b/src/core/define.ts index c7268b6..34eff27 100644 --- a/src/core/define.ts +++ b/src/core/define.ts @@ -1,7 +1,7 @@ import { MessageFlags, type ClientEvents } from 'discord.js'; import type { z } from 'zod'; -import { PermanentError } from '../shared/errors.js'; -import { subcommandPath } from './discord/router.js'; +import { PermanentError } from '~/shared/errors'; +import { subcommandPath } from '~/core/discord/router'; import type { AppContext, CommandInteraction, @@ -10,7 +10,7 @@ import type { JobInfo, JobOutcome, SlashCommand, -} from './feature.js'; +} from './feature'; export function defineJob(definition: { type: string; @@ -27,9 +27,11 @@ export function defineJob(definition: { maxAttempts: definition.maxAttempts ?? 5, run: async (raw, info, ctx) => { const parsed = definition.payload.safeParse(raw); + if (!parsed.success) { throw new PermanentError(`Invalid payload: ${parsed.error.message}`); } + return (await definition.handle(parsed.data, info, ctx)) ?? null; }, }; @@ -56,24 +58,21 @@ type SubcommandHandler = ( ctx: AppContext, ) => Promise; -/** Dispatches a command to the handler for its subcommand path. */ export function bySubcommand( handlers: Record, ): SlashCommand['execute'] { return async (interaction, ctx) => { const path = subcommandPath(interaction); const handler = handlers[path]; + if (!handler) { throw new Error(`No handler for /${interaction.commandName} ${path}`); } + await handler(interaction, ctx); }; } -/** - * Acknowledges privately before running a handler that may take longer than - * Discord's three-second deadline. Reply with `respond()` afterwards. - */ export function deferred(handler: SubcommandHandler): SubcommandHandler { return async (interaction, ctx) => { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); diff --git a/src/core/discord/client.ts b/src/core/discord/client.ts index acd049e..484d51a 100644 --- a/src/core/discord/client.ts +++ b/src/core/discord/client.ts @@ -1,10 +1,5 @@ import { Client, GatewayIntentBits, Partials } from 'discord.js'; -/** - * Only non-privileged intents are requested. Members are fetched over REST - * when needed, so the GuildMembers and MessageContent intents are not used. - * Partials let reaction events arrive for messages sent before a restart. - */ export function createClient(): Client { return new Client({ intents: [ diff --git a/src/core/discord/errors.ts b/src/core/discord/errors.ts index 68e2652..9a6f502 100644 --- a/src/core/discord/errors.ts +++ b/src/core/discord/errors.ts @@ -1,5 +1,5 @@ import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; -import { PermanentError } from '../../shared/errors.js'; +import { PermanentError } from '~/shared/errors'; const permanentCodes = new Set([ RESTJSONErrorCodes.UnknownChannel, @@ -13,12 +13,10 @@ const permanentCodes = new Set([ RESTJSONErrorCodes.CannotSendMessagesToThisUser, ]); -/** Deleted or inaccessible Discord objects; retrying will not help. */ export function isPermanentDiscordError(error: unknown): boolean { return error instanceof DiscordAPIError && permanentCodes.has(error.code); } -/** Rethrows permanent Discord failures as PermanentError for the scheduler. */ export function asJobError(error: unknown): unknown { return isPermanentDiscordError(error) && error instanceof Error ? new PermanentError(error.message) diff --git a/src/core/discord/registration.ts b/src/core/discord/registration.ts index a683e4d..adfe38a 100644 --- a/src/core/discord/registration.ts +++ b/src/core/discord/registration.ts @@ -1,7 +1,6 @@ import { REST, Routes } from 'discord.js'; -import type { Registry } from '../registry.js'; +import type { Registry } from '~/core/registry'; -/** Registers to one guild when given (instant), otherwise globally. */ export async function registerCommands( registry: Registry, options: { @@ -16,6 +15,8 @@ export async function registerCommands( options.guildId === undefined ? Routes.applicationCommands(options.applicationId) : Routes.applicationGuildCommands(options.applicationId, options.guildId); + await rest.put(route, { body }); + return body.length; } diff --git a/src/core/discord/router.ts b/src/core/discord/router.ts index d52fa31..22df55d 100644 --- a/src/core/discord/router.ts +++ b/src/core/discord/router.ts @@ -5,20 +5,16 @@ import { type BaseMessageOptions, type Interaction, } from 'discord.js'; -import { ignore, UserError } from '../../shared/errors.js'; +import { ignore, UserError } from '~/shared/errors'; import type { AppContext, CommandInteraction, ComponentInteraction, -} from '../feature.js'; -import { parseCustomId, type Registry } from '../registry.js'; +} from '~/core/feature'; +import { parseCustomId, type Registry } from '~/core/registry'; type Repliable = CommandInteraction | ComponentInteraction; -/** - * Answers privately, whatever state the interaction is in: a fresh reply, - * the completion of a deferred reply, or a follow-up after an answer. - */ export async function respond( interaction: Repliable, content: string | Pick, @@ -27,6 +23,7 @@ export async function respond( ...(typeof content === 'string' ? { content } : content), allowedMentions: { parse: [] }, }; + if (interaction.replied) { await interaction.followUp({ ...message, flags: MessageFlags.Ephemeral }); } else if (interaction.deferred) { @@ -51,14 +48,18 @@ async function runCommand( ctx: AppContext, ): Promise { const command = registry.commands.get(interaction.commandName); + if (!command) { throw new UserError('This command is no longer available.'); } + const permissions = command.permissions ?? {}; const required = permissions['*'] ?? permissions[subcommandPath(interaction)]; + if (required !== undefined) { await ctx.authz.require(interaction.member, required); } + await command.execute(interaction, ctx); } @@ -69,12 +70,15 @@ async function runComponent( ): Promise { const parsed = parseCustomId(interaction.customId); const handler = parsed && registry.components.get(parsed.prefix); + if (!parsed || !handler) { throw new UserError('This control is no longer active.'); } + if (handler.permission !== undefined) { await ctx.authz.require(interaction.member, handler.permission); } + await handler.execute(interaction, parsed.args, ctx); } @@ -84,6 +88,7 @@ async function runAutocomplete( ctx: AppContext, ): Promise { const command = registry.commands.get(interaction.commandName); + try { await command?.autocomplete?.(interaction, ctx); } catch (error) { @@ -92,6 +97,7 @@ async function runAutocomplete( 'Autocomplete failed', ); } + if (!interaction.responded) { await interaction.respond([]).catch(ignore); } @@ -110,7 +116,6 @@ function describe(interaction: Repliable): Record { }; } -/** The single error boundary for every interaction the bot receives. */ export function createInteractionHandler( registry: Registry, ctx: AppContext, @@ -125,12 +130,16 @@ export function createInteractionHandler( }) .catch(ignore); } + return; } + if (interaction.isAutocomplete()) { await runAutocomplete(registry, interaction, ctx); + return; } + if ( !interaction.isChatInputCommand() && !interaction.isMessageComponent() && @@ -145,6 +154,7 @@ export function createInteractionHandler( : runComponent(registry, interaction, ctx)); } catch (error) { let message: string; + if (error instanceof UserError) { message = error.message; ctx.log.debug( @@ -153,12 +163,14 @@ export function createInteractionHandler( ); } else { const ref = randomUUID().slice(0, 8); + ctx.log.error( { err: error, ref, ...describe(interaction) }, 'Interaction failed', ); message = `Something went wrong. Reference: \`${ref}\``; } + await respond(interaction, message).catch((replyError: unknown) => { ctx.log.warn({ err: replyError }, 'Could not report interaction error'); }); diff --git a/src/core/feature.ts b/src/core/feature.ts index ec700cd..c5e41d9 100644 --- a/src/core/feature.ts +++ b/src/core/feature.ts @@ -9,11 +9,10 @@ import type { ModalSubmitInteraction, RESTPostAPIChatInputApplicationCommandsJSONBody, } from 'discord.js'; -import type { Db } from '../db/client.js'; -import type { Config } from './config.js'; -import type { Logger } from './logger.js'; +import type { Db } from '~/db/client'; +import type { Config } from './config'; +import type { Logger } from './logger'; -/** Action identifiers such as `event:create`; features declare their own. */ export type Permission = `${string}:${string}`; export type PermissionDefinition = { @@ -23,13 +22,11 @@ export type PermissionDefinition = { export type Authorizer = { can: (member: GuildMember, permission: Permission) => Promise; - /** Throws a UserError when the member lacks the permission. */ require: (member: GuildMember, permission: Permission) => Promise; }; export type ScheduleOptions = { runAt: Date; - /** Scheduling again with the same key replaces the pending job. */ key?: string; maxAttempts?: number; }; @@ -56,10 +53,6 @@ export type CommandInteraction = ChatInputCommandInteraction<'cached'>; export type SlashCommand = { data: RESTPostAPIChatInputApplicationCommandsJSONBody; - /** - * Permission required per subcommand path ("create", "panel create"), or - * `'*'` for the whole command. Unlisted subcommands are open to members. - */ permissions?: Partial>; execute: (interaction: CommandInteraction, ctx: AppContext) => Promise; autocomplete?: ( @@ -73,10 +66,6 @@ export type ComponentInteraction = | AnySelectMenuInteraction<'cached'> | ModalSubmitInteraction<'cached'>; -/** - * Handles buttons, select menus and modals whose custom ID starts with - * `prefix` followed by `:`. Remaining `:`-separated segments become `args`. - */ export type ComponentHandler = { prefix: string; permission?: Permission; @@ -94,19 +83,16 @@ export type EventListener = { export type JobInfo = { id: number; - /** When the job was due; handlers decide what lateness means for them. */ runAt: Date; attempt: number; }; -/** Returning a date makes the job recur at that time. */ export type JobOutcome = null | { rescheduleAt: Date }; export type Job

= { type: string; maxAttempts: number; run: (raw: unknown, info: JobInfo, ctx: AppContext) => Promise; - /** Carries the payload type for `Scheduler.schedule`; never set. */ payloadType?: P; }; @@ -117,6 +103,5 @@ export type Feature = { components?: readonly ComponentHandler[]; events?: readonly EventListener[]; jobs?: ReadonlyArray>; - /** Runs once after the client is ready and migrations have applied. */ start?: (ctx: AppContext) => Promise; }; diff --git a/src/core/guild-settings.ts b/src/core/guild-settings.ts index 002e76a..423f72f 100644 --- a/src/core/guild-settings.ts +++ b/src/core/guild-settings.ts @@ -1,6 +1,6 @@ import { eq } from 'drizzle-orm'; import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -import type { Db } from '../db/client.js'; +import type { Db } from '~/db/client'; export const guildSettings = pgTable('guild_settings', { guildId: text('guild_id').primaryKey(), @@ -10,7 +10,6 @@ export const guildSettings = pgTable('guild_settings', { .defaultNow(), }); -/** Guild setting stored in the database wins over DEFAULT_TIMEZONE. */ export async function getGuildTimezone( db: Db, guildId: string, @@ -20,6 +19,7 @@ export async function getGuildTimezone( .select({ timezone: guildSettings.timezone }) .from(guildSettings) .where(eq(guildSettings.guildId, guildId)); + return row?.timezone ?? fallback; } diff --git a/src/core/logger.ts b/src/core/logger.ts index 2656aa1..4c31eb2 100644 --- a/src/core/logger.ts +++ b/src/core/logger.ts @@ -4,6 +4,7 @@ export type { Logger } from 'pino'; export function createLogger(level: string): Logger { const pretty = process.stdout.isTTY && process.env.NODE_ENV !== 'production'; + return pino({ level, redact: { diff --git a/src/core/permissions/authorizer.ts b/src/core/permissions/authorizer.ts index a1c5e90..667b8eb 100644 --- a/src/core/permissions/authorizer.ts +++ b/src/core/permissions/authorizer.ts @@ -1,14 +1,9 @@ import { PermissionFlagsBits, type GuildMember } from 'discord.js'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; -import type { Authorizer, Permission } from '../feature.js'; -import { hasGrant } from './store.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; +import type { Authorizer, Permission } from '~/core/feature'; +import { hasGrant } from './store'; -/** - * Members with Discord's Administrator permission (which includes the guild - * owner) hold every bot permission. Everyone else needs a grant on one of - * their roles; granting to @everyone makes an action open to all members. - */ export function isAdministrator(member: GuildMember): boolean { return member.permissions.has(PermissionFlagsBits.Administrator); } @@ -30,15 +25,12 @@ export function createAuthorizer(db: Db): Authorizer { }; } -/** - * Bot permissions never extend a member's reach: they may only direct the - * bot to post where they could post themselves. - */ export function requireCanPost(member: GuildMember, channelId: string): void { const channel = member.guild.channels.cache.get(channelId); const allowed = channel ?.permissionsFor(member) .has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages]); + if (allowed !== true) { throw new UserError(`You cannot post in <#${channelId}> yourself.`); } diff --git a/src/core/permissions/store.ts b/src/core/permissions/store.ts index c5c6aae..2887361 100644 --- a/src/core/permissions/store.ts +++ b/src/core/permissions/store.ts @@ -1,6 +1,6 @@ import { and, eq, inArray } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { rolePermissions } from './schema.js'; +import type { Db } from '~/db/client'; +import { rolePermissions } from './schema'; export async function hasGrant( db: Db, @@ -11,6 +11,7 @@ export async function hasGrant( if (roleIds.length === 0) { return false; } + const rows = await db .select({ roleId: rolePermissions.roleId }) .from(rolePermissions) @@ -22,10 +23,10 @@ export async function hasGrant( ), ) .limit(1); + return rows.length > 0; } -/** Returns false when the grant already existed. */ export async function grant( db: Db, input: { @@ -40,10 +41,10 @@ export async function grant( .values(input) .onConflictDoNothing() .returning({ roleId: rolePermissions.roleId }); + return rows.length > 0; } -/** Returns false when there was nothing to revoke. */ export async function revoke( db: Db, input: { guildId: string; roleId: string; permission: string }, @@ -58,6 +59,7 @@ export async function revoke( ), ) .returning({ roleId: rolePermissions.roleId }); + return rows.length > 0; } diff --git a/src/core/registry.ts b/src/core/registry.ts index 0220d12..bd9e155 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -5,7 +5,7 @@ import type { Permission, PermissionDefinition, SlashCommand, -} from './feature.js'; +} from './feature'; export type Registry = { features: readonly Feature[]; @@ -26,6 +26,7 @@ function addUnique( if (map.has(key)) { throw new Error(`Duplicate ${what} "${key}"`); } + map.set(key, value); } @@ -41,19 +42,24 @@ export function buildRegistry(features: readonly Feature[]): Registry { for (const command of feature.commands ?? []) { addUnique(commands, command.data.name, command, 'command'); } + for (const component of feature.components ?? []) { if (!componentPrefix.test(component.prefix)) { throw new Error(`Invalid component prefix "${component.prefix}"`); } + addUnique(components, component.prefix, component, 'component prefix'); } + for (const job of feature.jobs ?? []) { addUnique(jobs, job.type, job, 'job type'); } + for (const permission of feature.permissions ?? []) { if (permissions.has(permission.id)) { throw new Error(`Duplicate permission "${permission.id}"`); } + permissions.set(permission.id, permission); } } @@ -61,14 +67,15 @@ export function buildRegistry(features: readonly Feature[]): Registry { return { features, commands, components, jobs, permissions }; } -/** Splits `feature:action:arg...` into its handler prefix and arguments. */ export function parseCustomId( id: string, ): { prefix: string; args: string[] } | undefined { const [feature, action, ...args] = id.split(':'); + if (feature === undefined || action === undefined) { return undefined; } + return { prefix: `${feature}:${action}`, args }; } @@ -77,8 +84,10 @@ export function customId( ...args: Array ): string { const id = [prefix, ...args].join(':'); + if (id.length > 100) { throw new Error(`Custom ID exceeds 100 characters: ${id}`); } + return id; } diff --git a/src/core/scheduler/scheduler.ts b/src/core/scheduler/scheduler.ts index deda9b3..10cbb26 100644 --- a/src/core/scheduler/scheduler.ts +++ b/src/core/scheduler/scheduler.ts @@ -1,10 +1,10 @@ import { setTimeout as sleep } from 'node:timers/promises'; -import type { Db } from '../../db/client.js'; -import { PermanentError } from '../../shared/errors.js'; -import type { AppContext, Job, Scheduler } from '../feature.js'; -import type { Logger } from '../logger.js'; -import type { JobRow } from './schema.js'; -import { cancelJob, claimDueJobs, finishJob, upsertJob } from './store.js'; +import type { Db } from '~/db/client'; +import { PermanentError } from '~/shared/errors'; +import type { AppContext, Job, Scheduler } from '~/core/feature'; +import type { Logger } from '~/core/logger'; +import type { JobRow } from './schema'; +import { cancelJob, claimDueJobs, finishJob, upsertJob } from './store'; export type SchedulerOptions = { pollIntervalMs?: number; @@ -13,7 +13,6 @@ export type SchedulerOptions = { }; export type SchedulerRuntime = Scheduler & { - /** Claims and runs one batch; returns how many jobs were claimed. */ tick: (ctx: AppContext) => Promise; start: (ctx: AppContext) => void; stop: () => Promise; @@ -25,11 +24,6 @@ export function retryDelayMs(attempt: number): number { return Math.min(30_000 * 2 ** (attempt - 1), maxBackoffMs); } -/** - * One persistent, database-backed scheduler shared by every feature. Delivery - * is at-least-once: a handler may run again if the process dies mid-job, so - * handlers must be idempotent. - */ export function createScheduler( db: Db, jobs: ReadonlyMap>, @@ -46,22 +40,27 @@ export function createScheduler( async function execute(row: JobRow, ctx: AppContext): Promise { const job = jobs.get(row.type); const jobLog = log.child({ jobId: row.id, jobType: row.type }); + if (!job) { return; } + if (row.attempts > row.maxAttempts) { await finishJob(db, row.id, { kind: 'failed', error: 'Exceeded max attempts', }); + return; } + try { const outcome = await job.run( row.payload, { id: row.id, runAt: row.runAt, attempt: row.attempts }, { ...ctx, log: jobLog }, ); + await finishJob( db, row.id, @@ -73,6 +72,7 @@ export function createScheduler( const message = error instanceof Error ? error.message : String(error); const permanent = error instanceof PermanentError || row.attempts >= row.maxAttempts; + jobLog.error( { err: error, attempt: row.attempts, permanent }, 'Job failed', @@ -93,19 +93,22 @@ export function createScheduler( async function tick(ctx: AppContext): Promise { const rows = await claimDueJobs(db, { types, limit: batchSize, leaseMs }); + await Promise.all(rows.map((row) => execute(row, ctx))); + return rows.length; } async function run(ctx: AppContext): Promise { while (!abort.signal.aborted) { let claimed = 0; + try { claimed = await tick(ctx); } catch (error) { log.error({ err: error }, 'Scheduler tick failed'); } - // A full batch suggests a backlog, so poll again immediately. + if (claimed < batchSize) { await sleep(pollIntervalMs, undefined, { signal: abort.signal }).catch( () => false, diff --git a/src/core/scheduler/store.ts b/src/core/scheduler/store.ts index 94091e4..f65a553 100644 --- a/src/core/scheduler/store.ts +++ b/src/core/scheduler/store.ts @@ -1,6 +1,6 @@ import { and, asc, eq, inArray, lte, lt, or, sql } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { scheduledJobs, type JobRow } from './schema.js'; +import type { Db } from '~/db/client'; +import { scheduledJobs, type JobRow } from './schema'; export type NewJob = { type: string; @@ -10,7 +10,6 @@ export type NewJob = { maxAttempts?: number | undefined; }; -/** Inserts a job, or replaces the job holding the same key. */ export async function upsertJob(db: Db, job: NewJob): Promise { const values = { type: job.type, @@ -19,6 +18,7 @@ export async function upsertJob(db: Db, job: NewJob): Promise { key: job.key ?? null, maxAttempts: job.maxAttempts ?? 5, }; + await db .insert(scheduledJobs) .values(values) @@ -47,11 +47,6 @@ export async function cancelJob(db: Db, key: string): Promise { ); } -/** - * Claims due jobs, including running jobs whose lease expired because the - * process that claimed them died. SKIP LOCKED lets concurrent workers claim - * disjoint batches. - */ export async function claimDueJobs( db: Db, options: { types: readonly string[]; limit: number; leaseMs: number }, @@ -59,6 +54,7 @@ export async function claimDueJobs( if (options.types.length === 0) { return []; } + const due = db .select({ id: scheduledJobs.id }) .from(scheduledJobs) @@ -98,10 +94,6 @@ type Finish = | { kind: 'retry'; runAt: Date; error: string } | { kind: 'failed'; error: string }; -/** - * Records a job's outcome. Only applies while the job is still running, so a - * concurrent cancel or replacement wins over a finishing handler. - */ export async function finishJob( db: Db, id: number, @@ -114,6 +106,7 @@ export async function finishJob( retry: { status: 'pending' }, failed: { status: 'failed', finishedAt: now }, } as const; + await db .update(scheduledJobs) .set({ diff --git a/src/db/client.ts b/src/db/client.ts index 08a7d1a..e0c962f 100644 --- a/src/db/client.ts +++ b/src/db/client.ts @@ -1,11 +1,11 @@ +import { resolve } from 'node:path'; import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { migrate } from 'drizzle-orm/postgres-js/migrator'; import postgres from 'postgres'; -import { ignore } from '../shared/errors.js'; +import { ignore } from '~/shared/errors'; export type Db = PostgresJsDatabase; -/** A database handle or an open transaction; both accept the same queries. */ export type Tx = Parameters[0]>[0]; export type Database = { @@ -13,10 +13,11 @@ export type Database = { close: () => Promise; }; -const migrationsFolder = new URL('../../drizzle', import.meta.url).pathname; +const migrationsFolder = resolve('drizzle'); export function connectDatabase(url: string): Database { const sql = postgres(url, { max: 10, onnotice: ignore }); + return { db: drizzle(sql), close: () => sql.end({ timeout: 5 }), diff --git a/src/features/announcements/index.ts b/src/features/announcements/index.ts index 8335cd7..e066718 100644 --- a/src/features/announcements/index.ts +++ b/src/features/announcements/index.ts @@ -15,20 +15,20 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, defineJob } from '../../core/define.js'; -import { asJobError } from '../../core/discord/errors.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, defineJob } from '~/core/define'; +import { asJobError } from '~/core/discord/errors'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; -import { customId } from '../../core/registry.js'; -import { PermanentError, UserError } from '../../shared/errors.js'; -import { discordTime, parseFutureWhen } from '../../shared/time.js'; -import type { Announcement } from './schema.js'; +} from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; +import { customId } from '~/core/registry'; +import { PermanentError, UserError } from '~/shared/errors'; +import { discordTime, parseFutureWhen } from '~/shared/time'; +import type { Announcement } from './schema'; import { getAnnouncement, insertAnnouncement, @@ -36,10 +36,9 @@ import { requireAnnouncement, transition, updateContent, -} from './service.js'; +} from './service'; const jobKey = (id: number) => `announcement:${id}`; -/** A scheduled announcement this late is stale and is not posted. */ const maxLatenessMs = 60 * 60 * 1000; const maxContent = 4000; @@ -48,44 +47,53 @@ function mentions(announcement: Announcement): { allowed: MessageMentionOptions; } { const role = announcement.mentionRoleId; + if (role === null) { return { prefix: '', allowed: { parse: [] } }; } + if (role === announcement.guildId) { return { prefix: '@everyone ', allowed: { parse: ['everyone'] } }; } + return { prefix: `<@&${role}> `, allowed: { roles: [role] } }; } export function render(announcement: Announcement): BaseMessageOptions { const { prefix, allowed } = mentions(announcement); + if (announcement.embed) { const embed = new EmbedBuilder() .setDescription(announcement.content) .setColor(0xff_ac_1c); + if (announcement.title !== null) { embed.setTitle(announcement.title); } + return { ...(prefix === '' ? {} : { content: prefix.trim() }), embeds: [embed], allowedMentions: allowed, }; } + const heading = announcement.title === null ? '' : `**${announcement.title}**\n`; const content = `${prefix}${heading}${announcement.content}`; + if (content.length > 2000) { throw new UserError( 'Plain announcements are limited to 2000 characters; use an embed.', ); } + return { content, allowedMentions: allowed }; } -/** A private rendering that shows, but never sends, the mention. */ function preview(announcement: Announcement, note: string) { const rendered = render(announcement); + return { content: [note, rendered.content].filter(Boolean).join('\n\n'), embeds: rendered.embeds ?? [], @@ -94,23 +102,26 @@ function preview(announcement: Announcement, note: string) { } as const; } -/** Claims, posts and records an announcement. Posting happens at most once. */ async function publish( ctx: AppContext, id: number, from: Array, ): Promise { const claimed = await transition(ctx.db, id, from, { status: 'publishing' }); + if (!claimed) { throw new UserError( `Announcement #${id} cannot be published in its current state.`, ); } + try { const channel = await ctx.client.channels.fetch(claimed.channelId); + if (channel?.isSendable() !== true) { throw new PermanentError('Destination channel is not available'); } + const message = await channel.send(render(claimed)); const published = await transition(ctx.db, id, ['publishing'], { status: 'published', @@ -118,17 +129,19 @@ async function publish( messageId: message.id, failure: null, }); + ctx.log.info( { announcementId: id, messageId: message.id }, 'Announcement published', ); + return published ?? claimed; } catch (error) { const jobError = asJobError(error); const permanent = jobError instanceof PermanentError || error instanceof UserError; const message = error instanceof Error ? error.message : String(error); - // Transient failures return to their previous state so they can be retried. + await transition(ctx.db, id, ['publishing'], { status: permanent ? 'failed' : (from[0] ?? 'draft'), failure: message, @@ -142,19 +155,23 @@ const publishJob = defineJob({ payload: z.object({ announcementId: z.number().int() }), handle: async ({ announcementId }, _info, ctx) => { const announcement = await getAnnouncement(ctx.db, announcementId); + if (announcement?.status !== 'scheduled') { return; } + const due = announcement.scheduledAt ?? announcement.createdAt; + if (Date.now() - due.getTime() > maxLatenessMs) { await transition(ctx.db, announcementId, ['scheduled'], { status: 'failed', failure: 'Skipped: the scheduled time passed while the bot was offline', }); ctx.log.warn({ announcementId }, 'Skipped stale scheduled announcement'); + return; } - // Retries come back here while still 'scheduled'; publish() restores that state. + await publish(ctx, announcementId, ['scheduled']); }, }); @@ -163,10 +180,12 @@ function checkMention(member: GuildMember, roleId: string | null): void { if (roleId === null) { return; } + const canPingAll = member.permissions.has( PermissionFlagsBits.MentionEveryone, ); const role = member.guild.roles.cache.get(roleId); + if ( roleId === member.guild.id ? !canPingAll @@ -190,12 +209,15 @@ function contentModal( .setCustomId('content') .setStyle(TextInputStyle.Paragraph) .setMaxLength(maxContent); + if (current?.title !== null && current?.title !== undefined) { titleInput.setValue(current.title); } + if (current) { contentInput.setValue(current.content); } + return new ModalBuilder() .setCustomId(id) .setTitle(title) @@ -217,9 +239,11 @@ async function requireEditable( interaction.guildId, id, ); + if (announcement.authorId !== interaction.user.id) { await ctx.authz.require(interaction.member, 'announcement:publish'); } + return announcement; } @@ -230,8 +254,10 @@ const createModal: ComponentHandler = { if (!interaction.isModalSubmit()) { return; } + const [channelId = '', embed, role] = args; const mentionRoleId = role === undefined || role === '-' ? null : role; + checkMention(interaction.member, mentionRoleId); const title = interaction.fields.getTextInputValue('title').trim(); const announcement = await insertAnnouncement(ctx.db, { @@ -243,6 +269,7 @@ const createModal: ComponentHandler = { embed: embed === '1', mentionRoleId, }); + await interaction.reply( preview( announcement, @@ -258,6 +285,7 @@ const editModal: ComponentHandler = { if (!interaction.isModalSubmit()) { return; } + const announcement = await requireEditable( interaction, ctx, @@ -269,13 +297,15 @@ const editModal: ComponentHandler = { title: title === '' ? null : title, content: interaction.fields.getTextInputValue('content'), }; - render(updated); // Validates length before saving. + + render(updated); await updateContent(ctx.db, announcement.id, updated); if ( announcement.status === 'published' && announcement.messageId !== null ) { const channel = await ctx.client.channels.fetch(announcement.channelId); + if (channel?.isTextBased() === true) { await channel.messages.edit(announcement.messageId, { ...render(updated), @@ -283,6 +313,7 @@ const editModal: ComponentHandler = { }); } } + await interaction.reply({ content: `Announcement #${announcement.id} updated.`, flags: MessageFlags.Ephemeral, @@ -383,6 +414,7 @@ export const announcementsFeature: Feature = { create: async (interaction) => { const channel = interaction.options.getChannel('channel', true); const role = interaction.options.getRole('mention'); + checkMention(interaction.member, role?.id ?? null); const embed = interaction.options.getBoolean('embed') ?? true; const id = customId( @@ -391,6 +423,7 @@ export const announcementsFeature: Feature = { embed ? 1 : 0, role?.id ?? '-', ); + await interaction.showModal(contentModal(id, 'New announcement')); }, preview: async (interaction, ctx) => { @@ -399,6 +432,7 @@ export const announcementsFeature: Feature = { ctx, interaction.options.getInteger('id', true), ); + await interaction.reply( preview( announcement, @@ -409,6 +443,7 @@ export const announcementsFeature: Feature = { publish: async (interaction, ctx) => { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const id = interaction.options.getInteger('id', true); + await requireAnnouncement(ctx.db, interaction.guildId, id); await ctx.scheduler.cancel(jobKey(id)); const published = await publish(ctx, id, [ @@ -416,12 +451,14 @@ export const announcementsFeature: Feature = { 'scheduled', 'failed', ]); + await interaction.editReply( `Published #${id} in <#${published.channelId}>.`, ); }, schedule: async (interaction, ctx) => { const id = interaction.options.getInteger('id', true); + await requireAnnouncement(ctx.db, interaction.guildId, id); const zone = await getGuildTimezone( ctx.db, @@ -442,11 +479,13 @@ export const announcementsFeature: Feature = { failure: null, }, ); + if (!scheduled) { throw new UserError( `Announcement #${id} cannot be scheduled in its current state.`, ); } + await ctx.scheduler.schedule( publishJob, { announcementId: id }, @@ -463,6 +502,7 @@ export const announcementsFeature: Feature = { ctx, interaction.options.getInteger('id', true), ); + await interaction.showModal( contentModal( customId('announcements:edit', announcement.id), @@ -485,11 +525,13 @@ export const announcementsFeature: Feature = { status: 'cancelled', }, ); + if (!cancelled) { throw new UserError( `Announcement #${announcement.id} is already ${announcement.status}.`, ); } + await ctx.scheduler.cancel(jobKey(announcement.id)); await respond( interaction, @@ -499,6 +541,7 @@ export const announcementsFeature: Feature = { }), autocomplete: async (interaction, ctx) => { const rows = await listAnnouncements(ctx.db, interaction.guildId); + await interaction.respond( rows.map((row) => ({ name: `#${row.id} [${row.status}] ${row.title ?? row.content}`.slice( diff --git a/src/features/announcements/schema.ts b/src/features/announcements/schema.ts index 5c857cc..7ed9c32 100644 --- a/src/features/announcements/schema.ts +++ b/src/features/announcements/schema.ts @@ -27,7 +27,6 @@ export const announcements = pgTable( title: text('title'), content: text('content').notNull(), embed: boolean('embed').notNull().default(true), - /** A role ID, or the guild ID for @everyone. */ mentionRoleId: text('mention_role_id'), status: announcementStatus('status').notNull().default('draft'), scheduledAt: timestamp('scheduled_at', { withTimezone: true }), diff --git a/src/features/announcements/service.ts b/src/features/announcements/service.ts index 9a3a0c9..5de8cf2 100644 --- a/src/features/announcements/service.ts +++ b/src/features/announcements/service.ts @@ -1,7 +1,7 @@ import { and, desc, eq, inArray } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; -import { announcements, type Announcement } from './schema.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; +import { announcements, type Announcement } from './schema'; type Status = Announcement['status']; @@ -19,9 +19,11 @@ export async function insertAnnouncement( >, ): Promise { const [row] = await db.insert(announcements).values(input).returning(); + if (!row) { throw new Error('Insert returned no row'); } + return row; } @@ -34,9 +36,11 @@ export async function requireAnnouncement( .select() .from(announcements) .where(and(eq(announcements.id, id), eq(announcements.guildId, guildId))); + if (!row) { throw new UserError(`Announcement #${id} does not exist.`); } + return row; } @@ -48,6 +52,7 @@ export async function getAnnouncement( .select() .from(announcements) .where(eq(announcements.id, id)); + return row; } @@ -70,11 +75,6 @@ export async function listAnnouncements(db: Db, guildId: string) { .limit(25); } -/** - * Moves an announcement between states only if it is currently in one of - * `from`. Publishing claims the row this way first, so concurrent publish - * attempts cannot post it twice. - */ export async function transition( db: Db, id: number, @@ -88,6 +88,7 @@ export async function transition( and(eq(announcements.id, id), inArray(announcements.status, [...from])), ) .returning(); + return row; } diff --git a/src/features/birthdays/index.ts b/src/features/birthdays/index.ts index a78217c..7c9d485 100644 --- a/src/features/birthdays/index.ts +++ b/src/features/birthdays/index.ts @@ -6,24 +6,21 @@ import { roleMention, userMention, } from 'discord.js'; -import { DateTime } from 'luxon'; +import { format } from 'date-fns'; import { z } from 'zod'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, defineJob } from '../../core/define.js'; -import { isPermanentDiscordError } from '../../core/discord/errors.js'; -import type { - AppContext, - CommandInteraction, - Feature, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; -import { UserError } from '../../shared/errors.js'; -import { nextDailyRun } from '../../shared/time.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, defineJob } from '~/core/define'; +import { isPermanentDiscordError } from '~/core/discord/errors'; +import type { AppContext, CommandInteraction, Feature } from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; +import { sequential } from '~/shared/async'; +import { UserError } from '~/shared/errors'; +import { calendarDay, nextDailyRun } from '~/shared/time'; import { birthdayVisibility, type Birthday, type BirthdayVisibility, -} from './schema.js'; +} from './schema'; import { claimTodaysBirthdays, deleteSettings, @@ -34,7 +31,7 @@ import { saveSettings, setBirthday, upcomingBirthdays, -} from './service.js'; +} from './service'; const dailyKey = (guildId: string) => `birthdays:${guildId}`; const visibilities = birthdayVisibility.enumValues; @@ -50,9 +47,9 @@ const removeRoleJob = defineJob({ try { const guild = await ctx.client.guilds.fetch(guildId); const member = await guild.members.fetch(userId); + await member.roles.remove(roleId, 'Birthday is over'); } catch (error) { - // A member who left, or a deleted role, needs no cleanup. if (!isPermanentDiscordError(error)) { throw error; } @@ -62,20 +59,17 @@ const removeRoleJob = defineJob({ async function giveRole( ctx: AppContext, - guildId: string, - roleId: string, + target: { guildId: string; roleId: string; zone: string }, userIds: string[], - zone: string, ) { + const { guildId, roleId, zone } = target; const guild = await ctx.client.guilds.fetch(guildId); - const midnight = DateTime.now() - .setZone(zone) - .plus({ days: 1 }) - .startOf('day') - .toJSDate(); - for (const userId of userIds) { + const midnight = nextDailyRun(zone, 0); + + await sequential(userIds, async (userId) => { try { const member = await guild.members.fetch(userId); + await member.roles.add(roleId, 'Birthday'); await ctx.scheduler.schedule( removeRoleJob, @@ -88,32 +82,35 @@ async function giveRole( } catch (error) { ctx.log.warn({ err: error, userId }, 'Could not give birthday role'); } - } + }); } export const dailyJob = defineJob({ type: 'birthdays:daily', payload: z.object({ guildId: z.string() }), - // When the bot was down at the usual hour, today's birthdays are still - // announced on recovery; birthdays on days fully missed are not. handle: async ({ guildId }, _info, ctx) => { const settings = await getSettings(ctx.db, guildId); + if (!settings) { return null; } + const zone = await getGuildTimezone( ctx.db, guildId, ctx.config.DEFAULT_TIMEZONE, ); - const today = DateTime.now().setZone(zone); + const today = calendarDay(new Date(), zone); const userIds = await claimTodaysBirthdays(ctx.db, guildId, today); + if (userIds.length > 0) { try { const channel = await ctx.client.channels.fetch(settings.channelId); + if (channel?.isSendable() !== true) { throw new UserError('Birthday channel is not available'); } + await channel.send({ content: `🎉 Palju õnne! Happy birthday ${userIds.map((id) => userMention(id)).join(', ')}!`, allowedMentions: { users: userIds }, @@ -123,23 +120,32 @@ export const dailyJob = defineJob({ await releaseClaims(ctx.db, guildId, userIds, today.year); throw error; } + ctx.log.error( { err: error, guildId }, 'Birthday channel is unusable; skipping today', ); } + if (settings.roleId !== null) { - await giveRole(ctx, guildId, settings.roleId, userIds, zone); + await giveRole( + ctx, + { guildId, roleId: settings.roleId, zone }, + userIds, + ); } } + return { rescheduleAt: nextDailyRun(zone, settings.hour) }; }, }); function describe(birthday: Birthday): string { - const date = DateTime.local(2024, birthday.month, birthday.day).toFormat( - 'd LLLL', + const date = format( + new Date(2024, birthday.month - 1, birthday.day), + 'd MMMM', ); + return `<@${birthday.userId}> — ${date}`; } @@ -227,13 +233,17 @@ async function readSettings( const current = await getSettings(ctx.db, interaction.guildId); const channelId = interaction.options.getChannel('channel')?.id ?? current?.channelId; + if (channelId === undefined) { throw new UserError('Choose an announcement channel.'); } + const role = interaction.options.getRole('role'); + if (role && (role.managed || !role.editable)) { throw new UserError(`I cannot manage ${role.name}.`); } + return { guildId: interaction.guildId, channelId, @@ -247,19 +257,24 @@ async function configure( ctx: AppContext, ): Promise { const guildId = interaction.guildId; + if (interaction.options.getBoolean('disable') === true) { await deleteSettings(ctx.db, guildId); await ctx.scheduler.cancel(dailyKey(guildId)); await respond(interaction, 'Birthday announcements are off.'); + return; } + const settings = await readSettings(interaction, ctx); + await saveSettings(ctx.db, settings); const zone = await getGuildTimezone( ctx.db, guildId, ctx.config.DEFAULT_TIMEZONE, ); + await ctx.scheduler.schedule( dailyJob, { guildId }, @@ -273,6 +288,7 @@ async function configure( settings.roleId === null ? '' : ` with ${roleMention(settings.roleId)} for the day`; + await respond( interaction, `Birthdays are announced in ${channelMention(settings.channelId)} at ${settings.hour}:00 (${zone})${role}.`, @@ -295,6 +311,7 @@ export const birthdaysFeature: Feature = { visibilities.find( (v) => v === interaction.options.getString('visibility'), ) ?? 'public'; + await setBirthday(ctx.db, { guildId: interaction.guildId, userId: interaction.user.id, @@ -307,6 +324,7 @@ export const birthdaysFeature: Feature = { interaction.options.getInteger('day', true) === 29 ? ' In non-leap years it is celebrated on 28 February.' : ''; + await respond(interaction, `Saved (${visibility}).${leap}`); }, remove: async (interaction, ctx) => { @@ -315,6 +333,7 @@ export const birthdaysFeature: Feature = { interaction.guildId, interaction.user.id, ); + await respond( interaction, removed @@ -334,6 +353,7 @@ export const birthdaysFeature: Feature = { birthday && (user.id === interaction.user.id || birthday.visibility === 'public'); + await respond( interaction, visible === true ? describe(birthday) : 'No birthday to show.', @@ -348,13 +368,14 @@ export const birthdaysFeature: Feature = { const list = await upcomingBirthdays( ctx.db, interaction.guildId, - DateTime.now().setZone(zone), + calendarDay(new Date(), zone), ); + await respond( interaction, list.length === 0 ? 'No public birthdays yet.' - : list.map(describe).join('\n'), + : list.map((birthday) => describe(birthday)).join('\n'), ); }, settings: configure, diff --git a/src/features/birthdays/schema.ts b/src/features/birthdays/schema.ts index d17b09b..bf2733c 100644 --- a/src/features/birthdays/schema.ts +++ b/src/features/birthdays/schema.ts @@ -8,10 +8,6 @@ import { text, } from 'drizzle-orm/pg-core'; -/** - * public: announced and listed. announce: announced but never listed. - * private: stored for the member only; never announced or shown to others. - */ export const birthdayVisibility = pgEnum('birthday_visibility', [ 'public', 'announce', diff --git a/src/features/birthdays/service.ts b/src/features/birthdays/service.ts index 3df54cf..91acd64 100644 --- a/src/features/birthdays/service.ts +++ b/src/features/birthdays/service.ts @@ -1,32 +1,36 @@ import { and, eq, inArray, isNull, lt, ne, or, sql } from 'drizzle-orm'; -import { DateTime } from 'luxon'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; +import { isLeapYear } from 'date-fns'; +import type { CalendarDay } from '~/shared/time'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; import { birthdays, birthdaySettings, type Birthday, type BirthdayVisibility, -} from './schema.js'; +} from './schema'; export function validateDate(month: number, day: number): void { - // 2024 is a leap year, so 29 February is accepted. - if (!DateTime.local(2024, month, day).isValid) { + const date = new Date(2024, month - 1, day); + + if (date.getMonth() !== month - 1 || date.getDate() !== day) { throw new UserError('That is not a valid date.'); } } -/** - * The (month, day) pairs celebrated on a date. 29 February birthdays are - * celebrated on 28 February in non-leap years. - */ export function celebratedOn( - date: DateTime, + date: CalendarDay, ): Array<{ month: number; day: number }> { const dates = [{ month: date.month, day: date.day }]; - if (date.month === 2 && date.day === 28 && !date.isInLeapYear) { + + if ( + date.month === 2 && + date.day === 28 && + !isLeapYear(new Date(date.year, 0, 1)) + ) { dates.push({ month: 2, day: 29 }); } + return dates; } @@ -59,6 +63,7 @@ export async function removeBirthday( .delete(birthdays) .where(and(eq(birthdays.guildId, guildId), eq(birthdays.userId, userId))) .returning({ userId: birthdays.userId }); + return rows.length > 0; } @@ -71,14 +76,14 @@ export async function getBirthday( .select() .from(birthdays) .where(and(eq(birthdays.guildId, guildId), eq(birthdays.userId, userId))); + return row; } -/** Public birthdays ordered from `today` onward, wrapping around the year. */ export async function upcomingBirthdays( db: Db, guildId: string, - today: DateTime, + today: CalendarDay, limit = 10, ): Promise { const rows = await db @@ -90,23 +95,21 @@ export async function upcomingBirthdays( .limit(2000); const key = (b: { month: number; day: number }) => b.month * 100 + b.day; const start = key(today); + return rows .toSorted((a, b) => { const ka = (key(a) - start + 1300) % 1300; const kb = (key(b) - start + 1300) % 1300; + return ka - kb; }) .slice(0, limit); } -/** - * Claims today's birthdays for announcement by stamping the year. Only rows - * not yet stamped are returned, so a rerun on the same day announces nobody. - */ export async function claimTodaysBirthdays( db: Db, guildId: string, - today: DateTime, + today: CalendarDay, ): Promise { const dates = celebratedOn(today); const rows = await db @@ -128,10 +131,10 @@ export async function claimTodaysBirthdays( ), ) .returning({ userId: birthdays.userId }); + return rows.map((row) => row.userId); } -/** Undoes a claim when the announcement could not be posted, so a retry can. */ export async function releaseClaims( db: Db, guildId: string, @@ -141,6 +144,7 @@ export async function releaseClaims( if (userIds.length === 0) { return; } + await db .update(birthdays) .set({ lastAnnouncedYear: sql`${year} - 1` }) @@ -158,6 +162,7 @@ export async function getSettings(db: Db, guildId: string) { .select() .from(birthdaySettings) .where(eq(birthdaySettings.guildId, guildId)); + return row; } diff --git a/src/features/events/index.ts b/src/features/events/index.ts index cc33ea0..ffde799 100644 --- a/src/features/events/index.ts +++ b/src/features/events/index.ts @@ -13,25 +13,25 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, defineJob } from '../../core/define.js'; -import { asJobError, isUnknownObject } from '../../core/discord/errors.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, defineJob } from '~/core/define'; +import { asJobError, isUnknownObject } from '~/core/discord/errors'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; -import { customId } from '../../core/registry.js'; -import { UserError } from '../../shared/errors.js'; +} from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; +import { customId } from '~/core/registry'; +import { UserError } from '~/shared/errors'; import { discordTime, parseFutureWhen, parseWhen, requireZone, -} from '../../shared/time.js'; -import type { Event, RsvpStatus } from './schema.js'; +} from '~/shared/time'; +import type { Event, RsvpStatus } from './schema'; import { getEvent, insertEvent, @@ -44,7 +44,7 @@ import { updateEvent, type NewEvent, type RsvpCounts, -} from './service.js'; +} from './service'; const rsvpLabels: Record = { going: 'Going', @@ -84,9 +84,11 @@ export function renderEvent( { name: 'Maybe', value: String(counts.maybe), inline: true }, ) .setFooter({ text: `Event #${event.id}` }); + if (event.description !== null) { embed.setDescription(event.description); } + const buttons = rsvpStatuses.map((status) => new ButtonBuilder() .setCustomId(customId('events:rsvp', event.id, status)) @@ -95,6 +97,7 @@ export function renderEvent( status === 'going' ? ButtonStyle.Success : ButtonStyle.Secondary, ), ); + return { embeds: [embed], components: cancelled @@ -107,8 +110,10 @@ async function refreshMessage(ctx: AppContext, event: Event): Promise { if (event.messageId === null) { return; } + try { const channel = await ctx.client.channels.fetch(event.channelId); + if (channel?.isTextBased() === true) { await channel.messages.edit( event.messageId, @@ -119,6 +124,7 @@ async function refreshMessage(ctx: AppContext, event: Event): Promise { if (!isUnknownObject(error)) { throw error; } + ctx.log.warn({ eventId: event.id }, 'Event message or channel was deleted'); } } @@ -131,13 +137,14 @@ export const remindJob = defineJob({ payload: z.object({ eventId: z.number().int(), minutes: z.number().int() }), handle: async ({ eventId, minutes }, _info, ctx) => { const event = await getEvent(ctx.db, eventId); - // A reminder after the start is pointless, so late ones are dropped. + if ( event?.status !== 'scheduled' || event.startsAt.getTime() <= Date.now() ) { return; } + const attendees = await listAttendees(ctx.db, eventId); const going = attendees .filter((a) => a.status === 'going') @@ -148,8 +155,10 @@ export const remindJob = defineJob({ ? '' : ` https://discord.com/channels/${event.guildId}/${event.channelId}/${event.messageId}`; const pings = going.map((id) => `<@${id}>`).join(' '); + try { const channel = await ctx.client.channels.fetch(event.channelId); + if (channel?.isSendable() === true) { await channel.send({ content: `⏰ **${event.title}** starts ${discordTime(event.startsAt, 'R')} (${minutes} min reminder).${link}\n${pings}`, @@ -167,37 +176,49 @@ async function scheduleReminders( event: Event, previous: readonly number[] = [], ): Promise { - for (const minutes of previous) { - await ctx.scheduler.cancel(reminderKey(event.id, minutes)); - } + await Promise.all( + previous.map((minutes) => + ctx.scheduler.cancel(reminderKey(event.id, minutes)), + ), + ); + if (event.status !== 'scheduled') { return; } - for (const minutes of event.reminderMinutes) { - const runAt = new Date(event.startsAt.getTime() - minutes * 60_000); - if (runAt.getTime() > Date.now()) { - await ctx.scheduler.schedule( + + const upcoming = event.reminderMinutes + .map((minutes) => ({ + minutes, + runAt: new Date(event.startsAt.getTime() - minutes * 60_000), + })) + .filter(({ runAt }) => runAt.getTime() > Date.now()); + + await Promise.all( + upcoming.map(({ minutes, runAt }) => + ctx.scheduler.schedule( remindJob, { eventId: event.id, minutes }, { runAt, key: reminderKey(event.id, minutes) }, - ); - } - } + ), + ), + ); } -/** Mirrors the event as a native Discord scheduled event. Failures are not fatal. */ async function syncNativeEvent( ctx: AppContext, event: Event, ): Promise { try { const guild = await ctx.client.guilds.fetch(event.guildId); + if (event.status === 'cancelled') { if (event.discordEventId !== null) { await guild.scheduledEvents.delete(event.discordEventId); } + return null; } + const details = { name: event.title.slice(0, 100), scheduledStartTime: event.startsAt, @@ -209,29 +230,30 @@ async function syncNativeEvent( location: (event.location ?? 'See the event post').slice(0, 100), }, }; + if (event.discordEventId !== null) { await guild.scheduledEvents.edit(event.discordEventId, details); + return event.discordEventId; } + const created = await guild.scheduledEvents.create({ ...details, privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly, entityType: GuildScheduledEventEntityType.External, }); + return created.id; } catch (error) { ctx.log.warn( { err: error, eventId: event.id }, 'Could not sync native Discord event', ); + return event.discordEventId; } } -/** - * Public API: creates, publishes and schedules reminders for an event. Movie - * nights and any other feature that needs an event go through this. - */ export async function createEvent( ctx: AppContext, input: NewEvent & { native?: boolean }, @@ -240,9 +262,11 @@ export async function createEvent( const channel = await ctx.client.channels .fetch(values.channelId) .catch(() => null); + if (channel?.isSendable() !== true) { throw new UserError('I cannot post in that channel.'); } + let event = await insertEvent(ctx.db, values); const message = await channel.send({ ...renderEvent(event, { going: 0, maybe: 0, not_going: 0 }), @@ -254,11 +278,13 @@ export async function createEvent( }), }); const discordEventId = native ? await syncNativeEvent(ctx, event) : null; + event = await updateEvent(ctx.db, event.id, { messageId: message.id, discordEventId, }); await scheduleReminders(ctx, event); + return event; } @@ -266,10 +292,13 @@ function parseReminderMinutes(value: string | null): number[] { if (value === null) { return [60]; } + if (value.trim() === '') { return []; } + const minutes = value.split(',').map((part) => Number(part.trim())); + if ( minutes.length > maxReminders || minutes.some((m) => !Number.isInteger(m) || m < 1 || m > 10_080) @@ -278,6 +307,7 @@ function parseReminderMinutes(value: string | null): number[] { `Reminders are up to ${maxReminders} comma-separated minute values, e.g. "60,15".`, ); } + return [...new Set(minutes)]; } @@ -290,9 +320,11 @@ async function requireManageable( interaction.guildId, interaction.options.getInteger('id', true), ); + if (event.organizerId !== interaction.user.id) { await ctx.authz.require(interaction.member, 'event:manage'); } + return event; } @@ -301,6 +333,7 @@ const rsvpHandler: ComponentHandler = { execute: async (interaction, [id, answer], ctx) => { const status = rsvpStatuses.find((s) => s === answer); const eventId = Number(id); + if ( !interaction.isButton() || status === undefined || @@ -308,13 +341,16 @@ const rsvpHandler: ComponentHandler = { ) { throw new UserError('This button is invalid.'); } + await setRsvp(ctx.db, eventId, interaction.user.id, status); const event = await getEvent(ctx.db, eventId); + if (event) { await interaction.update( renderEvent(event, await rsvpCounts(ctx.db, eventId)), ); } + await interaction.followUp({ content: `RSVP saved: **${rsvpLabels[status]}**.`, flags: MessageFlags.Ephemeral, @@ -444,9 +480,11 @@ async function editEvent( ctx: AppContext, ): Promise { const event = await requireManageable(interaction, ctx); + if (event.status !== 'scheduled') { throw new UserError('Cancelled events cannot be edited.'); } + const option = (name: string) => interaction.options.getString(name) ?? undefined; const start = option('start'); @@ -462,16 +500,20 @@ async function editEvent( : parseFutureWhen(start, event.timezone), endsAt: end === undefined ? event.endsAt : parseWhen(end, event.timezone), }; + if (changes.endsAt && changes.endsAt <= changes.startsAt) { throw new UserError('The end must be after the start.'); } + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); let updated = await updateEvent(ctx.db, event.id, changes); + if (updated.discordEventId !== null) { updated = await updateEvent(ctx.db, event.id, { discordEventId: await syncNativeEvent(ctx, updated), }); } + await refreshMessage(ctx, updated); await scheduleReminders(ctx, updated, event.reminderMinutes); ctx.log.info( @@ -506,6 +548,7 @@ export const eventsFeature: Feature = { : requireZone(zoneOption); const end = interaction.options.getString('end'); const mention = interaction.options.getRole('mention'); + if ( mention && !mention.mentionable && @@ -513,6 +556,7 @@ export const eventsFeature: Feature = { ) { throw new UserError('You may not mention that role.'); } + const input = { guildId: interaction.guildId, title: interaction.options.getString('title', true), @@ -535,8 +579,10 @@ export const eventsFeature: Feature = { ), native: interaction.options.getBoolean('native') ?? false, }; + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const event = await createEvent(ctx, input); + ctx.log.info( { eventId: event.id, actorId: interaction.user.id }, 'Event created', @@ -548,13 +594,16 @@ export const eventsFeature: Feature = { edit: editEvent, cancel: async (interaction, ctx) => { const event = await requireManageable(interaction, ctx); + if (event.status === 'cancelled') { throw new UserError('That event is already cancelled.'); } + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const cancelled = await updateEvent(ctx.db, event.id, { status: 'cancelled', }); + await Promise.all([ refreshMessage(ctx, cancelled), scheduleReminders(ctx, cancelled, event.reminderMinutes), @@ -570,6 +619,7 @@ export const eventsFeature: Feature = { }, list: async (interaction, ctx) => { const upcoming = await listUpcoming(ctx.db, interaction.guildId); + await respond( interaction, upcoming.length === 0 @@ -589,6 +639,7 @@ export const eventsFeature: Feature = { interaction.options.getInteger('id', true), ); const counts = await rsvpCounts(ctx.db, event.id); + await interaction.reply({ embeds: renderEvent(event, counts).embeds ?? [], flags: MessageFlags.Ephemeral, @@ -605,16 +656,22 @@ export const eventsFeature: Feature = { const ids = attendees .filter((a) => a.status === status) .map((a) => `<@${a.userId}>`); + return `**${rsvpLabels[status]} (${ids.length})**\n${ids.join(' ') || '—'}`; }; + await respond( interaction, - rsvpStatuses.map(section).join('\n\n').slice(0, 2000), + rsvpStatuses + .map((status) => section(status)) + .join('\n\n') + .slice(0, 2000), ); }, }), autocomplete: async (interaction, ctx) => { const upcoming = await listUpcoming(ctx.db, interaction.guildId); + await interaction.respond( upcoming.map((e) => ({ name: `#${e.id} ${e.title}`.slice(0, 100), diff --git a/src/features/events/schema.ts b/src/features/events/schema.ts index 53bb715..820d539 100644 --- a/src/features/events/schema.ts +++ b/src/features/events/schema.ts @@ -16,10 +16,6 @@ export const rsvpStatus = pgEnum('rsvp_status', [ 'not_going', ]); -/** - * The bot's events are the source of truth for RSVPs and reminders. A native - * Discord scheduled event, when enabled, is only a mirror of this row. - */ export const events = pgTable( 'events', { diff --git a/src/features/events/service.ts b/src/features/events/service.ts index cea4ad3..6f27585 100644 --- a/src/features/events/service.ts +++ b/src/features/events/service.ts @@ -1,13 +1,13 @@ import { and, asc, count, eq, gte, ne } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; import { eventRsvps, events, rsvpStatus, type Event, type RsvpStatus, -} from './schema.js'; +} from './schema'; export type NewEvent = Omit< typeof events.$inferInsert, @@ -22,6 +22,7 @@ export async function insertEvent(db: Db, input: NewEvent): Promise { if (input.endsAt && input.endsAt <= input.startsAt) { throw new UserError('The end must be after the start.'); } + if ( input.capacity !== undefined && input.capacity !== null && @@ -29,15 +30,19 @@ export async function insertEvent(db: Db, input: NewEvent): Promise { ) { throw new UserError('Capacity must be at least 1.'); } + const [row] = await db.insert(events).values(input).returning(); + if (!row) { throw new Error('Insert returned no row'); } + return row; } export async function getEvent(db: Db, id: number): Promise { const [row] = await db.select().from(events).where(eq(events.id, id)); + return row; } @@ -47,9 +52,11 @@ export async function requireEvent( id: number, ): Promise { const event = await getEvent(db, id); + if (event?.guildId !== guildId) { throw new UserError(`Event #${id} does not exist.`); } + return event; } @@ -82,9 +89,11 @@ export async function updateEvent( .set(changes) .where(eq(events.id, id)) .returning(); + if (!row) { throw new UserError(`Event #${id} does not exist.`); } + return row; } @@ -95,16 +104,14 @@ export async function rsvpCounts(db: Db, eventId: number): Promise { .where(eq(eventRsvps.eventId, eventId)) .groupBy(eventRsvps.status); const counts: RsvpCounts = { going: 0, maybe: 0, not_going: 0 }; + for (const row of rows) { counts[row.status] = row.total; } + return counts; } -/** - * Records or changes a member's RSVP. The event row is locked so that - * concurrent "going" responses can never exceed the capacity. - */ export async function setRsvp( db: Db, eventId: number, @@ -121,9 +128,11 @@ export async function setRsvp( .from(events) .where(eq(events.id, eventId)) .for('update'); + if (event?.status !== 'scheduled') { throw new UserError('This event is no longer open for RSVPs.'); } + if (status === 'going' && event.capacity !== null) { const [others] = await tx .select({ total: count() }) @@ -135,12 +144,14 @@ export async function setRsvp( ne(eventRsvps.userId, userId), ), ); + if ((others?.total ?? 0) >= event.capacity) { throw new UserError( 'This event is full. You can still answer "Maybe".', ); } } + await tx .insert(eventRsvps) .values({ eventId, userId, status }) diff --git a/src/features/movies/index.ts b/src/features/movies/index.ts index 268e341..e657ef5 100644 --- a/src/features/movies/index.ts +++ b/src/features/movies/index.ts @@ -5,19 +5,15 @@ import { SlashCommandBuilder, type SlashCommandIntegerOption, } from 'discord.js'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand } from '../../core/define.js'; -import type { - AppContext, - CommandInteraction, - Feature, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; -import { UserError } from '../../shared/errors.js'; -import { discordTime, parseFutureWhen, parseWhen } from '../../shared/time.js'; -import { createEvent } from '../events/index.js'; -import { createPoll, getResults, latestPollBySource } from '../polls/index.js'; -import type { MovieSuggestion } from './schema.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand } from '~/core/define'; +import type { AppContext, CommandInteraction, Feature } from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; +import { UserError } from '~/shared/errors'; +import { discordTime, parseFutureWhen, parseWhen } from '~/shared/time'; +import { createEvent } from '~/features/events'; +import { createPoll, getResults, latestPollBySource } from '~/features/polls'; +import type { MovieSuggestion } from './schema'; import { listUnwatched, markWatched, @@ -26,17 +22,13 @@ import { requireSuggestion, suggestMovie, watchHistory, -} from './service.js'; +} from './service'; const pollSource = 'movies'; const label = (movie: Pick) => movie.year === null ? movie.title : `${movie.title} (${movie.year})`; -/** - * The movie for a screening: the one given, otherwise the winner of the most - * recent movie poll. Ties are never broken automatically. - */ export async function pickMovie( ctx: AppContext, guildId: string, @@ -48,21 +40,29 @@ export async function pickMovie( pollId: null, }; } + const poll = await latestPollBySource(ctx.db, guildId, pollSource); + if (poll?.status !== 'closed') { throw new UserError('Pick a movie, or close a `/movie vote` poll first.'); } + const { winners, tie } = await getResults(ctx.db, poll); + if (winners.length === 0) { throw new UserError('The last movie poll had no votes. Pick a movie.'); } + if (tie) { const tied = winners.map((w) => `#${w.ref ?? '?'} ${w.label}`).join(', '); + throw new UserError( `The last poll is a tie between ${tied}. Pick one with the \`movie\` option.`, ); } + const winner = winners[0]; + return { movie: await requireSuggestion(ctx.db, guildId, Number(winner?.ref)), pollId: poll.id, @@ -195,6 +195,7 @@ export const moviesFeature: Feature = { note: interaction.options.getString('note'), suggestedBy: interaction.user.id, }); + await respond( interaction, `Added #${movie.id} ${label(movie)} to the list.`, @@ -202,6 +203,7 @@ export const moviesFeature: Feature = { }, suggestions: async (interaction, ctx) => { const movies = await listUnwatched(ctx.db, interaction.guildId); + await respond( interaction, movies.length === 0 @@ -217,9 +219,11 @@ export const moviesFeature: Feature = { interaction.guildId, interaction.options.getInteger('movie', true), ); + if (movie.suggestedBy !== interaction.user.id) { await ctx.authz.require(interaction.member, 'movie:manage'); } + await removeSuggestion(ctx.db, movie.id); await respond(interaction, `Removed ${label(movie)}.`); }, @@ -229,15 +233,18 @@ export const moviesFeature: Feature = { interaction.guildId, interaction.options.getInteger('count') ?? 10, ); + if (movies.length < 2) { throw new UserError( 'At least two unwatched suggestions are needed for a vote.', ); } + const closesAt = parseFutureWhen( interaction.options.getString('closes') ?? '2d', await zoneOf(interaction, ctx), ); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const poll = await createPoll(ctx, { guildId: interaction.guildId, @@ -253,6 +260,7 @@ export const moviesFeature: Feature = { closesAt, source: pollSource, }); + await interaction.editReply( `Movie poll #${poll.id} closes ${discordTime(closesAt, 'R')}.`, ); @@ -268,6 +276,7 @@ export const moviesFeature: Feature = { interaction.options.getString('start', true), timezone, ); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const event = await createEvent(ctx, { guildId: interaction.guildId, @@ -283,6 +292,7 @@ export const moviesFeature: Feature = { capacity: interaction.options.getInteger('capacity'), reminderMinutes: [60], }); + await recordScreening(ctx.db, { guildId: interaction.guildId, suggestionId: movie.id, @@ -305,11 +315,13 @@ export const moviesFeature: Feature = { date === null ? new Date() : parseWhen(date, await zoneOf(interaction, ctx)); + await markWatched(ctx.db, interaction.guildId, movie.id, watchedAt); await respond(interaction, `Marked ${label(movie)} as watched.`); }, history: async (interaction, ctx) => { const history = await watchHistory(ctx.db, interaction.guildId); + await respond( interaction, history.length === 0 @@ -326,6 +338,7 @@ export const moviesFeature: Feature = { autocomplete: async (interaction, ctx) => { const query = interaction.options.getFocused().toLowerCase(); const movies = await listUnwatched(ctx.db, interaction.guildId); + await interaction.respond( movies .filter((m) => m.title.toLowerCase().includes(query)) diff --git a/src/features/movies/schema.ts b/src/features/movies/schema.ts index 7de3250..c7d71cc 100644 --- a/src/features/movies/schema.ts +++ b/src/features/movies/schema.ts @@ -32,10 +32,6 @@ export const movieSuggestions = pgTable( ], ); -/** - * A movie night. Voting and scheduling live in the polls and events features; - * these IDs only link to them, so they carry no foreign keys across features. - */ export const movieScreenings = pgTable( 'movie_screenings', { diff --git a/src/features/movies/service.ts b/src/features/movies/service.ts index 42fd753..5778196 100644 --- a/src/features/movies/service.ts +++ b/src/features/movies/service.ts @@ -1,13 +1,12 @@ import { and, asc, desc, eq, isNotNull, isNull, notExists } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; import { movieScreenings, movieSuggestions, type MovieSuggestion, -} from './schema.js'; +} from './schema'; -/** "The Matrix!" and "the matrix" are the same suggestion. */ export function normalizeTitle(title: string): string { return title .normalize('NFKD') @@ -38,23 +37,28 @@ export async function suggestMovie( }, ): Promise { const normalizedTitle = normalizeTitle(input.title); + if (normalizedTitle === '') { throw new UserError('Give a movie title.'); } + const [row] = await db .insert(movieSuggestions) .values({ ...input, title: input.title.trim(), normalizedTitle }) .onConflictDoNothing() .returning(); + if (!row) { const existing = await findActive(db, input.guildId, normalizedTitle); const when = existing && (await lastWatched(db, existing.id)); + throw new UserError( when ? `That movie was already watched (${when.toISOString().slice(0, 10)}).` : 'That movie is already suggested.', ); } + return row; } @@ -69,6 +73,7 @@ async function findActive(db: Db, guildId: string, normalizedTitle: string) { isNull(movieSuggestions.removedAt), ), ); + return row; } @@ -87,6 +92,7 @@ export async function lastWatched( ) .orderBy(desc(movieScreenings.watchedAt)) .limit(1); + return row?.watchedAt ?? undefined; } @@ -105,13 +111,14 @@ export async function requireSuggestion( isNull(movieSuggestions.removedAt), ), ); + if (!row) { throw new UserError(`Movie #${id} is not on the list.`); } + return row; } -/** Suggestions not yet watched, oldest first so long-waiting ones get a turn. */ export async function listUnwatched( db: Db, guildId: string, @@ -152,13 +159,14 @@ export async function recordScreening( .insert(movieScreenings) .values(input) .returning({ id: movieScreenings.id }); + if (!row) { throw new Error('Insert returned no row'); } + return row.id; } -/** Marks the latest unwatched screening as watched, or records a new one. */ export async function markWatched( db: Db, guildId: string, @@ -176,6 +184,7 @@ export async function markWatched( ) .orderBy(desc(movieScreenings.createdAt)) .limit(1); + await (pending ? db .update(movieScreenings) diff --git a/src/features/permissions/index.ts b/src/features/permissions/index.ts index ebeee08..c93cef7 100644 --- a/src/features/permissions/index.ts +++ b/src/features/permissions/index.ts @@ -5,18 +5,18 @@ import { type Role, type SlashCommandStringOption, } from 'discord.js'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, deferred } from '../../core/define.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, deferred } from '~/core/define'; import type { AppContext, CommandInteraction, Feature, Permission, PermissionDefinition, -} from '../../core/feature.js'; -import { isAdministrator } from '../../core/permissions/authorizer.js'; -import { grant, listGrants, revoke } from '../../core/permissions/store.js'; -import { UserError } from '../../shared/errors.js'; +} from '~/core/feature'; +import { isAdministrator } from '~/core/permissions/authorizer'; +import { grant, listGrants, revoke } from '~/core/permissions/store'; +import { UserError } from '~/shared/errors'; const managePermission: Permission = 'permissions:manage'; @@ -65,11 +65,6 @@ const data = new SlashCommandBuilder() .addStringOption(permissionOption), ); -/** - * Stops members with `permissions:manage` from escalating: they may only hand - * out permissions they hold themselves, only to roles below their own, and - * never `permissions:manage` itself. Discord administrators are exempt. - */ export async function checkDelegation( ctx: Pick, actor: GuildMember, @@ -79,14 +74,17 @@ export async function checkDelegation( if (isAdministrator(actor)) { return; } + if (permission === managePermission) { throw new UserError( 'Only administrators can delegate permission management.', ); } + if (actor.roles.highest.comparePositionTo(role) <= 0) { throw new UserError(`${role.name} is not below your highest role.`); } + if (!(await ctx.authz.can(actor, permission))) { throw new UserError('You can only grant permissions you hold yourself.'); } @@ -98,9 +96,11 @@ export function createPermissionsFeature( const readPermission = (interaction: CommandInteraction): Permission => { const value = interaction.options.getString('permission', true); const definition = [...known().values()].find((p) => p.id === value); + if (!definition) { throw new UserError(`Unknown permission \`${value}\`.`); } + return definition.id; }; @@ -109,6 +109,7 @@ export function createPermissionsFeature( async (interaction: CommandInteraction, ctx: AppContext) => { const role = interaction.options.getRole('role', true); const permission = readPermission(interaction); + await checkDelegation(ctx, interaction.member, role, permission); const input = { guildId: interaction.guildId, @@ -119,11 +120,13 @@ export function createPermissionsFeature( action === 'grant' ? await grant(ctx.db, { ...input, grantedBy: interaction.user.id }) : await revoke(ctx.db, input); + ctx.log.info( { ...input, actorId: interaction.user.id, action, changed }, 'Permission change', ); const verb = action === 'grant' ? 'Granted' : 'Revoked'; + await respond( interaction, changed @@ -154,6 +157,7 @@ export function createPermissionsFeature( const lines = grants.map( (g) => `<@&${g.roleId}> — \`${g.permission}\``, ); + await respond( interaction, lines.length === 0 @@ -166,6 +170,7 @@ export function createPermissionsFeature( const member = await interaction.guild.members.fetch(user.id); const permission = readPermission(interaction); const allowed = await ctx.authz.can(member, permission); + await respond( interaction, `${member.toString()} ${allowed ? 'holds' : 'does not hold'} \`${permission}\`.`, @@ -174,6 +179,7 @@ export function createPermissionsFeature( }), autocomplete: async (interaction) => { const query = interaction.options.getFocused().toLowerCase(); + await interaction.respond( [...known().values()] .filter( diff --git a/src/features/polls/index.ts b/src/features/polls/index.ts index 8343464..9431ede 100644 --- a/src/features/polls/index.ts +++ b/src/features/polls/index.ts @@ -13,20 +13,20 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, defineJob } from '../../core/define.js'; -import { isUnknownObject } from '../../core/discord/errors.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, defineJob } from '~/core/define'; +import { isUnknownObject } from '~/core/discord/errors'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; -import { customId } from '../../core/registry.js'; -import { UserError } from '../../shared/errors.js'; -import { discordTime, parseFutureWhen } from '../../shared/time.js'; -import type { Poll } from './schema.js'; +} from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; +import { customId } from '~/core/registry'; +import { UserError } from '~/shared/errors'; +import { discordTime, parseFutureWhen } from '~/shared/time'; +import type { Poll } from './schema'; import { castVote, finishPoll, @@ -42,20 +42,22 @@ import { type NewPoll, type PollResults, type PollWithOptions, -} from './service.js'; +} from './service'; -export type { PollResults, PollWithOptions } from './service.js'; -export { getResults, latestPollBySource } from './service.js'; +export type { PollResults, PollWithOptions } from './service'; +export { getResults, latestPollBySource } from './service'; const closeKey = (id: number) => `poll:${id}:close`; function bar(votes: number, total: number): string { const filled = total === 0 ? 0 : Math.round((votes / total) * 10); + return '█'.repeat(filled) + '░'.repeat(10 - filled); } function describeOutcome(results: PollResults, leader: string): string { const label = results.tie ? 'Tie' : leader; + return `**${label}:** ${results.winners.map((w) => w.label).join(', ')}`; } @@ -71,12 +73,14 @@ export function renderPoll( : `• ${option.label}`, ); let status = poll.status === 'cancelled' ? 'Cancelled' : 'Closed'; + if (open) { status = poll.closesAt === null ? 'Open' : `Closes ${discordTime(poll.closesAt, 'R')}`; } + const outcome = !open && results.winners.length > 0 ? `\n\n${describeOutcome(results, 'Winner')}` @@ -93,9 +97,11 @@ export function renderPoll( status, ].join(' · '), }); + if (!open) { return { embeds: [embed], components: [] }; } + const select = new StringSelectMenuBuilder() .setCustomId(customId('polls:vote', poll.id)) .setPlaceholder(poll.multiple ? 'Choose one or more' : 'Choose one') @@ -111,6 +117,7 @@ export function renderPoll( .setCustomId(customId('polls:clear', poll.id)) .setLabel('Clear my vote') .setStyle(ButtonStyle.Secondary); + return { embeds: [embed], components: [ @@ -122,11 +129,14 @@ export function renderPoll( async function refreshMessage(ctx: AppContext, poll: Poll): Promise { const full = await getPoll(ctx.db, poll.id); + if (full?.messageId === null || full?.messageId === undefined) { return; } + try { const channel = await ctx.client.channels.fetch(full.channelId); + if (channel?.isTextBased() === true) { await channel.messages.edit( full.messageId, @@ -137,6 +147,7 @@ async function refreshMessage(ctx: AppContext, poll: Poll): Promise { if (!isUnknownObject(error)) { throw error; } + ctx.log.warn({ pollId: poll.id }, 'Poll message or channel was deleted'); } } @@ -144,16 +155,15 @@ async function refreshMessage(ctx: AppContext, poll: Poll): Promise { export const closeJob = defineJob({ type: 'polls:close', payload: z.object({ pollId: z.number().int() }), - // Polls are closed even when the job runs late; only the message is updated. handle: async ({ pollId }, _info, ctx) => { const closed = await finishPoll(ctx.db, pollId, 'closed'); + if (closed) { await refreshMessage(ctx, closed); } }, }); -/** Public API: publishes a poll and schedules its closing. */ export async function createPoll( ctx: AppContext, input: NewPoll, @@ -161,13 +171,16 @@ export async function createPoll( const channel = await ctx.client.channels .fetch(input.channelId) .catch(() => null); + if (channel?.isSendable() !== true) { throw new UserError('I cannot post in that channel.'); } + const poll = await insertPoll(ctx.db, input); const message = await channel.send( renderPoll(poll, await getResults(ctx.db, poll)), ); + await setPollMessage(ctx.db, poll.id, message.id); if (poll.closesAt !== null) { await ctx.scheduler.schedule( @@ -176,20 +189,23 @@ export async function createPoll( { runAt: poll.closesAt, key: closeKey(poll.id) }, ); } + return { ...poll, messageId: message.id }; } -/** Public API: closes a poll now. Returns false if it was not open. */ export async function closePoll( ctx: AppContext, pollId: number, ): Promise { const closed = await finishPoll(ctx.db, pollId, 'closed'); + if (!closed) { return false; } + await ctx.scheduler.cancel(closeKey(pollId)); await refreshMessage(ctx, closed); + return true; } @@ -201,14 +217,18 @@ async function vote( ): Promise { await castVote(ctx.db, pollId, interaction.user.id, optionIds); const poll = await getPoll(ctx.db, pollId); + if (!poll || interaction.isModalSubmit()) { return; } + const results = await getResults(ctx.db, poll); + await interaction.update(renderPoll(poll, results)); const chosen = poll.options .filter((o) => optionIds.includes(o.id)) .map((o) => o.label); + await interaction.followUp({ content: chosen.length === 0 @@ -220,9 +240,11 @@ async function vote( function parseId(value: string | undefined): number { const id = Number(value); + if (!Number.isSafeInteger(id)) { throw new UserError('This poll control is invalid.'); } + return id; } @@ -232,6 +254,7 @@ const voteHandler: ComponentHandler = { if (!interaction.isStringSelectMenu()) { return; } + await vote(interaction, parseId(id), interaction.values.map(Number), ctx); }, }; @@ -241,9 +264,11 @@ const clearHandler: ComponentHandler = { execute: async (interaction, [id], ctx) => { const pollId = parseId(id); const current = await getVoterChoices(ctx.db, pollId, interaction.user.id); + if (current.length === 0) { throw new UserError('You have not voted.'); } + await vote(interaction, pollId, [], ctx); }, }; @@ -257,9 +282,11 @@ async function requireManageable( interaction.guildId, interaction.options.getInteger('id', true), ); + if (poll.creatorId !== interaction.user.id) { await ctx.authz.require(interaction.member, 'poll:manage'); } + return poll; } @@ -348,20 +375,24 @@ async function showResults( const manager = poll.creatorId === interaction.user.id || (await ctx.authz.can(interaction.member, 'poll:manage')); + if (poll.showResults === 'closed' && isOpen(poll) && !manager) { throw new UserError('Results are shown when the poll closes.'); } + const results = await getResults(ctx.db, poll); const voters = !poll.anonymous && manager ? await getVoters(ctx.db, poll.id) : undefined; const lines = results.options.map((option) => { const names = voters?.get(option.id)?.map((id) => userMention(id)) ?? []; + return [`**${option.label}** — ${option.votes}`, ...names].join(' '); }); const winner = results.winners.length === 0 ? 'No votes yet.' : describeOutcome(results, 'Leading'); + await respond( interaction, [`**${poll.question}**`, ...lines, winner].join('\n').slice(0, 2000), @@ -388,6 +419,7 @@ export const pollsFeature: Feature = { interaction.guildId, ctx.config.DEFAULT_TIMEZONE, ); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const poll = await createPoll(ctx, { guildId: interaction.guildId, @@ -408,12 +440,14 @@ export const pollsFeature: Feature = { : 'live', closesAt: closes === null ? null : parseFutureWhen(closes, zone), }); + await interaction.editReply( `Poll #${poll.id} is up in <#${poll.channelId}>.`, ); }, list: async (interaction, ctx) => { const open = await listOpenPolls(ctx.db, interaction.guildId); + await respond( interaction, open.length === 0 @@ -426,17 +460,21 @@ export const pollsFeature: Feature = { results: showResults, close: async (interaction, ctx) => { const poll = await requireManageable(interaction, ctx); + if (!(await closePoll(ctx, poll.id))) { throw new UserError('That poll is not open.'); } + await respond(interaction, `Poll #${poll.id} is closed.`); }, cancel: async (interaction, ctx) => { const poll = await requireManageable(interaction, ctx); const cancelled = await finishPoll(ctx.db, poll.id, 'cancelled'); + if (!cancelled) { throw new UserError('That poll is not open.'); } + await ctx.scheduler.cancel(closeKey(poll.id)); await refreshMessage(ctx, cancelled); await respond(interaction, `Poll #${poll.id} is cancelled.`); @@ -444,6 +482,7 @@ export const pollsFeature: Feature = { }), autocomplete: async (interaction, ctx) => { const open = await listOpenPolls(ctx.db, interaction.guildId); + await interaction.respond( open.map((p) => ({ name: `#${p.id} ${p.question}`.slice(0, 100), diff --git a/src/features/polls/schema.ts b/src/features/polls/schema.ts index 093ea7e..7d54bca 100644 --- a/src/features/polls/schema.ts +++ b/src/features/polls/schema.ts @@ -35,7 +35,6 @@ export const polls = pgTable( showResults: pollResultVisibility('show_results').notNull().default('live'), closesAt: timestamp('closes_at', { withTimezone: true }), status: pollStatus('status').notNull().default('open'), - /** The feature that created the poll, e.g. 'movies'; null for /poll. */ source: text('source'), createdAt: timestamp('created_at', { withTimezone: true }) .notNull() @@ -56,7 +55,6 @@ export const pollOptions = pgTable( .references(() => polls.id, { onDelete: 'cascade' }), position: integer('position').notNull(), label: text('label').notNull(), - /** An identifier owned by the source feature, e.g. a movie suggestion. */ ref: text('ref'), }, (table) => [ diff --git a/src/features/polls/service.ts b/src/features/polls/service.ts index 505502c..a484a22 100644 --- a/src/features/polls/service.ts +++ b/src/features/polls/service.ts @@ -8,15 +8,15 @@ import { inArray, sql, } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; import { pollOptions, polls, pollVotes, type Poll, type PollOption, -} from './schema.js'; +} from './schema'; export const maxOptions = 25; @@ -37,7 +37,6 @@ export type OptionResult = PollOption & { votes: number }; export type PollResults = { options: OptionResult[]; voters: number; - /** Options sharing the highest vote count; empty when nobody voted. */ winners: OptionResult[]; tie: boolean; }; @@ -47,23 +46,29 @@ export async function insertPoll( input: NewPoll, ): Promise { const labels = input.options.map((option) => option.label.trim()); + if (labels.length < 2 || labels.length > maxOptions) { throw new UserError(`A poll needs between 2 and ${maxOptions} options.`); } + if (labels.some((label) => label === '' || label.length > 100)) { throw new UserError('Options must be 1–100 characters.'); } + if ( new Set(labels.map((label) => label.toLowerCase())).size !== labels.length ) { throw new UserError('Options must be distinct.'); } + return db.transaction(async (tx) => { const { options, ...values } = input; const [poll] = await tx.insert(polls).values(values).returning(); + if (!poll) { throw new Error('Insert returned no row'); } + const inserted = await tx .insert(pollOptions) .values( @@ -75,6 +80,7 @@ export async function insertPoll( })), ) .returning(); + return { ...poll, options: inserted.toSorted((a, b) => a.position - b.position), @@ -87,14 +93,17 @@ export async function getPoll( id: number, ): Promise { const [poll] = await db.select().from(polls).where(eq(polls.id, id)); + if (!poll) { return undefined; } + const options = await db .select() .from(pollOptions) .where(eq(pollOptions.pollId, id)) .orderBy(asc(pollOptions.position)); + return { ...poll, options }; } @@ -104,9 +113,11 @@ export async function requirePoll( id: number, ): Promise { const poll = await getPoll(db, id); + if (poll?.guildId !== guildId) { throw new UserError(`Poll #${id} does not exist.`); } + return poll; } @@ -116,11 +127,6 @@ export function isOpen(poll: Poll, now = new Date()): boolean { ); } -/** - * Replaces a member's votes with `optionIds` (empty clears them). The poll - * row is locked so a vote cannot race with closing or with the same member - * voting twice at once. - */ export async function castVote( db: Db, pollId: number, @@ -133,13 +139,17 @@ export async function castVote( .from(polls) .where(eq(polls.id, pollId)) .for('update'); + if (!poll || !isOpen(poll)) { throw new UserError('This poll is closed.'); } + const unique = [...new Set(optionIds)]; + if (!poll.multiple && unique.length > 1) { throw new UserError('This poll allows only one choice.'); } + if (unique.length > 0) { const valid = await tx .select({ id: pollOptions.id }) @@ -147,10 +157,12 @@ export async function castVote( .where( and(eq(pollOptions.pollId, pollId), inArray(pollOptions.id, unique)), ); + if (valid.length !== unique.length) { throw new UserError('That option is not part of this poll.'); } } + await tx .delete(pollVotes) .where(and(eq(pollVotes.pollId, pollId), eq(pollVotes.userId, userId))); @@ -185,6 +197,7 @@ export async function getResults( const top = Math.max(0, ...options.map((option) => option.votes)); const winners = top === 0 ? [] : options.filter((option) => option.votes === top); + return { options, voters: voters?.total ?? 0, @@ -202,10 +215,10 @@ export async function getVoterChoices( .select({ optionId: pollVotes.optionId }) .from(pollVotes) .where(and(eq(pollVotes.pollId, pollId), eq(pollVotes.userId, userId))); + return rows.map((row) => row.optionId); } -/** Voter IDs per option. Never call this for anonymous polls. */ export async function getVoters( db: Db, pollId: number, @@ -217,13 +230,14 @@ export async function getVoters( .orderBy(asc(pollVotes.createdAt)) .limit(5000); const voters = new Map(); + for (const row of rows) { voters.set(row.optionId, [...(voters.get(row.optionId) ?? []), row.userId]); } + return voters; } -/** Returns the poll if this call closed it, so closing side effects run once. */ export async function finishPoll( db: Db, id: number, @@ -239,6 +253,7 @@ export async function finishPoll( }) .where(and(eq(polls.id, id), eq(polls.status, 'open'))) .returning(); + return row; } @@ -270,5 +285,6 @@ export async function latestPollBySource( .where(and(eq(polls.guildId, guildId), eq(polls.source, source))) .orderBy(desc(polls.createdAt), desc(polls.id)) .limit(1); + return row ? getPoll(db, row.id) : undefined; } diff --git a/src/features/redmine/index.ts b/src/features/redmine/index.ts index d173d7d..27daf0d 100644 --- a/src/features/redmine/index.ts +++ b/src/features/redmine/index.ts @@ -10,42 +10,41 @@ import { TextInputStyle, type SlashCommandIntegerOption, } from 'discord.js'; -import { DateTime } from 'luxon'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, deferred } from '../../core/define.js'; -import type { Config } from '../../core/config.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, deferred } from '~/core/define'; +import type { Config } from '~/core/config'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, SlashCommand, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; +} from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; import { RedmineClient, RedmineError, type RedmineIssue, type RedmineUser, -} from '../../integrations/redmine/client.js'; -import { createSecretBox, type SecretBox } from '../../shared/crypto.js'; -import { UserError } from '../../shared/errors.js'; -import { createReminder } from '../reminders/index.js'; -import { createNotificationJobs } from './notifications.js'; +} from '~/integrations/redmine/client'; +import { createSecretBox, type SecretBox } from '~/shared/crypto'; +import { UserError } from '~/shared/errors'; +import { addCalendarDays, parseCalendarDay, zonedTime } from '~/shared/time'; +import { createReminder } from '~/features/reminders'; +import { createNotificationJobs } from './notifications'; import { addSubscription, deleteLink, getLink, removeSubscription, saveLink, -} from './service.js'; +} from './service'; type Handler = ( interaction: CommandInteraction, ctx: AppContext, ) => Promise; -/** Redmine failures become user-facing messages; nothing about keys leaks. */ function withRedmineErrors(handler: Handler): Handler { return async (interaction, ctx) => { try { @@ -58,6 +57,7 @@ function withRedmineErrors(handler: Handler): Handler { ); throw new UserError(error.message); } + throw error; } }; @@ -231,6 +231,7 @@ const data = new SlashCommandBuilder() function issueLine(baseUrl: string, issue: RedmineIssue): string { const assignee = issue.assigned_to ? ` · ${issue.assigned_to.name}` : ''; + return `[#${issue.id}](<${baseUrl}issues/${issue.id}>) **${issue.subject}** — ${issue.status.name}${assignee}`; } @@ -248,20 +249,19 @@ function issueEmbed(baseUrl: string, issue: RedmineIssue): EmbedBuilder { ); } -/** - * Discord-side permission is necessary but never sufficient: every request - * below runs with the member's own Redmine key, so Redmine still decides. - */ export function createRedmineFeature(config: Config): Feature | undefined { const base = config.REDMINE_BASE_URL; + if (base === undefined) { return undefined; } + if (config.CREDENTIAL_ENCRYPTION_KEY === undefined) { throw new Error( 'CREDENTIAL_ENCRYPTION_KEY is required when REDMINE_BASE_URL is set', ); } + const baseUrl = base.endsWith('/') ? base : `${base}/`; const box: SecretBox = createSecretBox(config.CREDENTIAL_ENCRYPTION_KEY); const service = @@ -275,11 +275,13 @@ export function createRedmineFeature(config: Config): Feature | undefined { userId: string, ): Promise<{ client: RedmineClient; redmineUserId: number }> { const link = await getLink(ctx.db, userId); + if (!link) { throw new UserError( 'Link your Redmine account first with `/redmine link`.', ); } + return { client: new RedmineClient(baseUrl, box.decrypt(link.encryptedApiKey)), redmineUserId: link.redmineUserId, @@ -292,6 +294,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { 'Redmine notifications are not configured (REDMINE_API_KEY).', ); } + return service; }; @@ -300,18 +303,19 @@ export function createRedmineFeature(config: Config): Feature | undefined { async (interaction, ctx) => { const channelId = interaction.options.getChannel('channel')?.id ?? interaction.channelId; - // The project must be visible to the member and to the service account. const { client } = await clientFor(ctx, interaction.user.id); const identifier = interaction.options.getString('project', true); const { projects } = await client.listProjects(0, 100); const project = projects.find( (p) => p.identifier === identifier || String(p.id) === identifier, ); + if (!project) { throw new UserError( `Project "${identifier}" not found among your projects.`, ); } + if (action === 'unsubscribe') { const removed = await removeSubscription( ctx.db, @@ -319,14 +323,17 @@ export function createRedmineFeature(config: Config): Feature | undefined { channelId, project.id, ); + await respond( interaction, removed ? `Unsubscribed <#${channelId}> from ${project.name}.` : 'No such subscription.', ); + return; } + await requireService().listIssues({ projectId: project.id, limit: 1 }); const added = await addSubscription(ctx.db, { guildId: interaction.guildId, @@ -335,6 +342,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { projectName: project.name, createdBy: interaction.user.id, }); + ctx.log.info( { guildId: interaction.guildId, @@ -357,6 +365,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { const { client } = await clientFor(ctx, interaction.user.id); const { projects, total } = await client.listProjects(); const lines = projects.map((p) => `\`${p.identifier}\` ${p.name}`); + await respond( interaction, [ @@ -376,6 +385,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { limit: 15, }); const lines = issues.map((issue) => issueLine(baseUrl, issue)); + await respond( interaction, lines.length === 0 @@ -388,6 +398,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { const issue = await client.getIssue( interaction.options.getInteger('issue', true), ); + await respond(interaction, { embeds: [issueEmbed(baseUrl, issue)] }); }, 'issue create': async (interaction, ctx) => { @@ -404,16 +415,20 @@ export function createRedmineFeature(config: Config): Feature | undefined { ? { assigned_to_id: redmineUserId } : {}), }); + await respond(interaction, `Created ${issueLine(baseUrl, issue)}`); }, 'issue update': async (interaction, ctx) => { const { client } = await clientFor(ctx, interaction.user.id); const status = interaction.options.getInteger('status'); const notes = interaction.options.getString('notes'); + if (status === null && notes === null) { throw new UserError('Give a new status or notes.'); } + const id = interaction.options.getInteger('issue', true); + await client.updateIssue(id, { ...(status === null ? {} : { status_id: status }), ...(notes === null ? {} : { notes }), @@ -427,22 +442,28 @@ export function createRedmineFeature(config: Config): Feature | undefined { ); const member = interaction.options.getUser('member'); let assignee = redmineUserId; + if (member && member.id !== interaction.user.id) { const link = await getLink(ctx.db, member.id); + if (!link) { throw new UserError( `${member.username} has not linked a Redmine account.`, ); } + assignee = link.redmineUserId; } + const id = interaction.options.getInteger('issue', true); + await client.updateIssue(id, { assigned_to_id: assignee }); await respond(interaction, `Assigned #${id}.`); }, 'issue comment': async (interaction, ctx) => { const { client } = await clientFor(ctx, interaction.user.id); const id = interaction.options.getInteger('issue', true); + await client.updateIssue(id, { notes: interaction.options.getString('text', true), }); @@ -453,21 +474,29 @@ export function createRedmineFeature(config: Config): Feature | undefined { const issue = await client.getIssue( interaction.options.getInteger('issue', true), ); + if (issue.due_date === undefined || issue.due_date === null) { throw new UserError(`#${issue.id} has no due date.`); } + const timezone = await getGuildTimezone( ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE, ); - const runAt = DateTime.fromISO(issue.due_date, { zone: timezone }) - .minus({ days: interaction.options.getInteger('days_before') ?? 1 }) - .set({ hour: 9 }) - .toJSDate(); + const due = parseCalendarDay(issue.due_date); + + if (!due) { + throw new UserError(`#${issue.id} has an unreadable due date.`); + } + + const daysBefore = interaction.options.getInteger('days_before') ?? 1; + const runAt = zonedTime(addCalendarDays(due, -daysBefore), 9, timezone); + if (runAt.getTime() <= Date.now()) { throw new UserError('That reminder time has already passed.'); } + const reminder = await createReminder(ctx, { guildId: interaction.guildId, userId: interaction.user.id, @@ -477,6 +506,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { recurrence: null, timezone, }); + await respond( interaction, `I will DM you (reminder #${reminder.id}).`, @@ -488,6 +518,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { .setStyle(TextInputStyle.Short) .setMinLength(20) .setMaxLength(100); + await interaction.showModal( new ModalBuilder() .setCustomId('redmine:link') @@ -504,6 +535,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { }, unlink: async (interaction, ctx) => { const removed = await deleteLink(ctx.db, interaction.user.id); + ctx.log.info( { userId: interaction.user.id, removed }, 'Redmine account unlinked', @@ -523,9 +555,11 @@ export function createRedmineFeature(config: Config): Feature | undefined { if (!interaction.isModalSubmit()) { return; } + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const apiKey = interaction.fields.getTextInputValue('key').trim(); let user: RedmineUser; + try { user = await new RedmineClient(baseUrl, apiKey).currentUser(); } catch (error) { @@ -536,8 +570,10 @@ export function createRedmineFeature(config: Config): Feature | undefined { : error.message, ); } + throw error; } + await saveLink(ctx.db, { userId: interaction.user.id, redmineUserId: user.id, @@ -562,7 +598,6 @@ export function createRedmineFeature(config: Config): Feature | undefined { subscribe: 'redmine:subscription:manage', unsubscribe: 'redmine:subscription:manage', }, - // Redmine can be slow, so everything but the modal is deferred first. execute: bySubcommand( Object.fromEntries( Object.entries(handlers).map(([path, handler]) => [ @@ -574,6 +609,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { autocomplete: async (interaction, ctx) => { const { client } = await clientFor(ctx, interaction.user.id); const statuses = await client.listStatuses(); + await interaction.respond( statuses.slice(0, 25).map((s) => ({ name: s.name, value: s.id })), ); diff --git a/src/features/redmine/notifications.ts b/src/features/redmine/notifications.ts index 306c845..99a1c40 100644 --- a/src/features/redmine/notifications.ts +++ b/src/features/redmine/notifications.ts @@ -1,20 +1,26 @@ import { MessageFlags } from 'discord.js'; -import { DateTime } from 'luxon'; import { z } from 'zod'; -import { defineJob } from '../../core/define.js'; -import type { AppContext } from '../../core/feature.js'; +import { defineJob } from '~/core/define'; +import { sequential } from '~/shared/async'; +import type { AppContext } from '~/core/feature'; import type { RedmineClient, RedmineStatus, -} from '../../integrations/redmine/client.js'; -import { nextDailyRun } from '../../shared/time.js'; -import type { RedmineSubscription } from './schema.js'; +} from '~/integrations/redmine/client'; +import { + addCalendarDays, + calendarDay, + formatCalendarDay, + nextDailyRun, +} from '~/shared/time'; +import type { RedmineSubscription } from './schema'; import { claimNotification, issueNotifications, listSubscriptions, setCheckpoint, -} from './service.js'; + type Notification, +} from './service'; const pollIntervalMs = 2 * 60 * 1000; const issuesPerPoll = 25; @@ -23,62 +29,63 @@ const deadlineHour = 9; export const pollKey = 'redmine:poll'; export const deadlineKey = 'redmine:deadlines'; +type Source = { + redmine: RedmineClient; + baseUrl: string; + statuses: ReadonlyMap; +}; + async function forEachSubscription( ctx: AppContext, handle: (subscription: RedmineSubscription) => Promise, + afterId = 0, ): Promise { - let afterId = 0; - for (;;) { - const page = await listSubscriptions(ctx.db, afterId); - for (const subscription of page) { - try { - await handle(subscription); - } catch (error) { - ctx.log.warn( - { err: error, subscriptionId: subscription.id }, - 'Redmine subscription update failed', - ); - } - } - const last = page.at(-1); - if (last === undefined) { - return; + const page = await listSubscriptions(ctx.db, afterId); + + await sequential(page, async (subscription) => { + try { + await handle(subscription); + } catch (error) { + ctx.log.warn( + { err: error, subscriptionId: subscription.id }, + 'Redmine subscription update failed', + ); } - afterId = last.id; + }); + + const last = page.at(-1); + + if (last !== undefined) { + await forEachSubscription(ctx, handle, last.id); } } async function sendOnce( ctx: AppContext, subscription: RedmineSubscription, - key: string, - text: string, + notification: Notification, ) { - if (!(await claimNotification(ctx.db, subscription.id, key))) { + if (!(await claimNotification(ctx.db, subscription.id, notification.key))) { return; } + const channel = await ctx.client.channels.fetch(subscription.channelId); + if (channel?.isSendable() === true) { await channel.send({ - content: text.slice(0, 2000), + content: notification.text.slice(0, 2000), allowedMentions: { parse: [] }, flags: MessageFlags.SuppressEmbeds, }); } } -/** - * Incremental polling: each subscription remembers the newest update it has - * processed and only asks Redmine for issues updated since. Notifications - * are claimed in the database before sending, so none repeat. - */ async function pollSubscription( ctx: AppContext, - redmine: RedmineClient, - baseUrl: string, + source: Source, subscription: RedmineSubscription, - statuses: ReadonlyMap, ): Promise { + const { redmine, baseUrl, statuses } = source; const { issues } = await redmine.listIssues({ projectId: subscription.projectId, status: '*', @@ -87,22 +94,28 @@ async function pollSubscription( limit: issuesPerPoll, }); let checkpoint = subscription.checkpoint; - for (const summary of issues) { + + await sequential(issues, async (summary) => { const issue = await redmine.getIssue(summary.id, true); const url = new URL(`issues/${issue.id}`, baseUrl).href; - for (const notification of issueNotifications( + const notifications = issueNotifications( issue, subscription.checkpoint, statuses, url, - )) { - await sendOnce(ctx, subscription, notification.key, notification.text); - } + ); + + await sequential(notifications, (notification) => + sendOnce(ctx, subscription, notification), + ); + const updated = new Date(issue.updated_on); + if (updated > checkpoint) { checkpoint = updated; } - } + }); + if (checkpoint > subscription.checkpoint) { await setCheckpoint(ctx.db, subscription.id, checkpoint); } @@ -118,12 +131,17 @@ export function createNotificationJobs( type: 'redmine:poll', payload: z.object({}), handle: async (_payload, _info, ctx) => { - // Without statuses, notifications show "?" names instead of failing. const known = await redmine.listStatuses().catch(() => []); const statuses = new Map(known.map((status) => [status.id, status])); + await forEachSubscription(ctx, (subscription) => - pollSubscription(ctx, redmine, root, subscription, statuses), + pollSubscription( + ctx, + { redmine, baseUrl: root, statuses }, + subscription, + ), ); + return { rescheduleAt: new Date(Date.now() + pollIntervalMs) }; }, }); @@ -133,29 +151,35 @@ export function createNotificationJobs( payload: z.object({}), handle: async (_payload, _info, ctx) => { const zone = ctx.config.DEFAULT_TIMEZONE; - const tomorrow = - DateTime.now().setZone(zone).plus({ days: 1 }).toISODate() ?? ''; + const tomorrow = formatCalendarDay( + addCalendarDays(calendarDay(new Date(), zone), 1), + ); + await forEachSubscription(ctx, async (subscription) => { const { issues } = await redmine.listIssues({ projectId: subscription.projectId, dueDate: tomorrow, limit: 50, }); - for (const issue of issues.filter((i) => i.is_private !== true)) { + + const visible = issues.filter((issue) => issue.is_private !== true); + + await sequential(visible, (issue) => { const url = new URL(`issues/${issue.id}`, root).href; - await sendOnce( - ctx, - subscription, - `due:${issue.id}:${tomorrow}`, - [ - `⏳ Due tomorrow: [#${issue.id}](${url}) ${issue.subject}`, - issue.assigned_to?.name, - ] - .filter(Boolean) - .join(' · '), - ); - } + const text = [ + `⏳ Due tomorrow: [#${issue.id}](${url}) ${issue.subject}`, + issue.assigned_to?.name, + ] + .filter(Boolean) + .join(' · '); + + return sendOnce(ctx, subscription, { + key: `due:${issue.id}:${tomorrow}`, + text, + }); + }); }); + return { rescheduleAt: nextDailyRun(zone, deadlineHour) }; }, }); diff --git a/src/features/redmine/schema.ts b/src/features/redmine/schema.ts index 59d4047..cb1d621 100644 --- a/src/features/redmine/schema.ts +++ b/src/features/redmine/schema.ts @@ -8,7 +8,6 @@ import { unique, } from 'drizzle-orm/pg-core'; -/** API keys are stored encrypted with CREDENTIAL_ENCRYPTION_KEY. */ export const redmineLinks = pgTable('redmine_links', { userId: text('user_id').primaryKey(), redmineUserId: integer('redmine_user_id').notNull(), @@ -28,7 +27,6 @@ export const redmineSubscriptions = pgTable( projectId: integer('project_id').notNull(), projectName: text('project_name').notNull(), createdBy: text('created_by').notNull(), - /** Issues updated at or after this time have not been fully processed. */ checkpoint: timestamp('checkpoint', { withTimezone: true }) .notNull() .defaultNow(), @@ -38,7 +36,6 @@ export const redmineSubscriptions = pgTable( ], ); -/** One row per notification sent, so overlapping polls never repeat one. */ export const redmineNotifications = pgTable( 'redmine_notifications', { diff --git a/src/features/redmine/service.ts b/src/features/redmine/service.ts index 8ec5876..29039b6 100644 --- a/src/features/redmine/service.ts +++ b/src/features/redmine/service.ts @@ -1,15 +1,15 @@ import { and, asc, eq, gt } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; +import type { Db } from '~/db/client'; import type { RedmineIssue, RedmineStatus, -} from '../../integrations/redmine/client.js'; +} from '~/integrations/redmine/client'; import { redmineLinks, redmineNotifications, redmineSubscriptions, type RedmineLink, -} from './schema.js'; +} from './schema'; export async function saveLink( db: Db, @@ -32,6 +32,7 @@ export async function getLink( .select() .from(redmineLinks) .where(eq(redmineLinks.userId, userId)); + return row; } @@ -40,6 +41,7 @@ export async function deleteLink(db: Db, userId: string): Promise { .delete(redmineLinks) .where(eq(redmineLinks.userId, userId)) .returning({ userId: redmineLinks.userId }); + return rows.length > 0; } @@ -52,6 +54,7 @@ export async function addSubscription( .values(input) .onConflictDoNothing() .returning({ id: redmineSubscriptions.id }); + return rows.length > 0; } @@ -71,10 +74,10 @@ export async function removeSubscription( ), ) .returning({ id: redmineSubscriptions.id }); + return rows.length > 0; } -/** Subscriptions in ID order, paged so each poll run stays bounded. */ export async function listSubscriptions(db: Db, afterId = 0, limit = 50) { return db .select() @@ -95,7 +98,6 @@ export async function setCheckpoint( .where(eq(redmineSubscriptions.id, id)); } -/** Records a notification; false means it was already sent. */ export async function claimNotification( db: Db, subscriptionId: number, @@ -106,15 +108,12 @@ export async function claimNotification( .values({ subscriptionId, key }) .onConflictDoNothing() .returning({ key: redmineNotifications.key }); + return rows.length > 0; } export type Notification = { key: string; text: string }; -/** - * Turns an issue with journals into notifications for changes at or after - * `since`. Private issues and private notes are never included. - */ export function issueNotifications( issue: RedmineIssue, since: Date, @@ -124,17 +123,21 @@ export function issueNotifications( if (issue.is_private === true) { return []; } + const title = `[#${issue.id}](${issueUrl}) ${issue.subject}`; const notifications: Notification[] = []; + if (new Date(issue.created_on) >= since) { const assignee = issue.assigned_to ? `, assigned to ${issue.assigned_to.name}` : ''; + notifications.push({ key: `issue:${issue.id}:created`, text: `🆕 ${issue.tracker.name} ${title} by ${issue.author.name}${assignee}`, }); } + for (const journal of issue.journals ?? []) { if ( new Date(journal.created_on) < since || @@ -142,38 +145,48 @@ export function issueNotifications( ) { continue; } + const changes = journal.details.flatMap((detail) => { if (detail.property !== 'attr') { return []; } + if (detail.name === 'status_id') { const name = (id: string | null | undefined) => statuses.get(Number(id))?.name ?? '?'; + return [`status ${name(detail.old_value)} → ${name(detail.new_value)}`]; } + if (detail.name === 'assigned_to_id') { const matches = issue.assigned_to && String(issue.assigned_to.id) === detail.new_value; + return [ matches === true ? `assigned to ${issue.assigned_to?.name ?? ''}` : 'assignee changed', ]; } + return []; }); const notes = journal.notes?.trim() ?? ''; + if (changes.length === 0 && notes === '') { continue; } + const who = journal.user?.name ?? 'Someone'; const comment = notes === '' ? '' : `\n> ${notes.slice(0, 300).replaceAll('\n', '\n> ')}`; + notifications.push({ key: `journal:${journal.id}`, text: `✏️ ${title}: ${[who, ...changes].join(' · ')}${comment}`, }); } + return notifications; } diff --git a/src/features/reminders/index.ts b/src/features/reminders/index.ts index 4b70fa2..6e688bc 100644 --- a/src/features/reminders/index.ts +++ b/src/features/reminders/index.ts @@ -5,24 +5,20 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, defineJob } from '../../core/define.js'; -import { asJobError } from '../../core/discord/errors.js'; -import type { - AppContext, - CommandInteraction, - Feature, -} from '../../core/feature.js'; -import { getGuildTimezone } from '../../core/guild-settings.js'; -import { PermanentError, UserError } from '../../shared/errors.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, defineJob } from '~/core/define'; +import { asJobError } from '~/core/discord/errors'; +import type { AppContext, CommandInteraction, Feature } from '~/core/feature'; +import { getGuildTimezone } from '~/core/guild-settings'; +import { PermanentError, UserError } from '~/shared/errors'; import { discordTime, nextFutureOccurrence, parseFutureWhen, recurrences, requireZone, -} from '../../shared/time.js'; -import type { Reminder } from './schema.js'; +} from '~/shared/time'; +import type { Reminder } from './schema'; import { getReminder, insertReminder, @@ -30,21 +26,27 @@ import { requireOwnReminder, updateReminder, type NewReminder, -} from './service.js'; +} from './service'; const jobKey = (id: number) => `reminder:${id}`; async function deliver(ctx: AppContext, reminder: Reminder): Promise { const text = `⏰ **Reminder:** ${reminder.message}`; + if (reminder.channelId === null) { const user = await ctx.client.users.fetch(reminder.userId); + await user.send({ content: text }); + return; } + const channel = await ctx.client.channels.fetch(reminder.channelId); + if (channel?.isSendable() !== true) { throw new PermanentError('Reminder channel is not a text channel'); } + await channel.send({ content: `<@${reminder.userId}> ${text}`, allowedMentions: { users: [reminder.userId] }, @@ -54,44 +56,52 @@ async function deliver(ctx: AppContext, reminder: Reminder): Promise { export const deliverJob = defineJob({ type: 'reminders:deliver', payload: z.object({ reminderId: z.number().int() }), - // Reminders are still useful late, so overdue ones are delivered on recovery. handle: async ({ reminderId }, _info, ctx) => { const reminder = await getReminder(ctx.db, reminderId); + if (reminder?.status !== 'active') { return null; } + try { await deliver(ctx, reminder); } catch (error) { const jobError = asJobError(error); + if (jobError instanceof PermanentError) { await updateReminder(ctx.db, reminder.id, { status: 'failed', failure: jobError.message, }); } + throw jobError; } + if (reminder.recurrence === null) { await updateReminder(ctx.db, reminder.id, { status: 'done' }); + return null; } + const next = nextFutureOccurrence( reminder.runAt, reminder.recurrence, reminder.timezone, ); + await updateReminder(ctx.db, reminder.id, { runAt: next }); + return { rescheduleAt: next }; }, }); -/** Public API: other features create reminders through this. */ export async function createReminder( ctx: AppContext, input: NewReminder, ): Promise { const reminder = await insertReminder(ctx.db, input); + await ctx.scheduler.schedule( deliverJob, { reminderId: reminder.id }, @@ -100,12 +110,14 @@ export async function createReminder( key: jobKey(reminder.id), }, ); + return reminder; } export function describeReminder(reminder: Reminder): string { const where = reminder.channelId === null ? 'DM' : `<#${reminder.channelId}>`; const repeat = reminder.recurrence === null ? '' : `, ${reminder.recurrence}`; + return `#${reminder.id} ${discordTime(reminder.runAt, 'f')} (${where}${repeat}) — ${reminder.message.slice(0, 80)}`; } @@ -178,6 +190,7 @@ async function zoneFor( ctx: AppContext, ): Promise { const explicit = interaction.options.getString('timezone'); + return explicit === null ? getGuildTimezone(ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE) : requireZone(explicit); @@ -196,9 +209,11 @@ export const remindersFeature: Feature = { const channel = interaction.options.getChannel('channel', false, [ ChannelType.GuildText, ]); + if (channel) { await ctx.authz.require(interaction.member, 'reminder:channel'); } + const timezone = await zoneFor(interaction, ctx); const reminder = await createReminder(ctx, { guildId: interaction.guildId, @@ -209,7 +224,6 @@ export const remindersFeature: Feature = { interaction.options.getString('when', true), timezone, ), - // Discord enforces the choices, but option values are still untrusted. recurrence: recurrences.find( (r) => r === interaction.options.getString('repeat'), @@ -219,6 +233,7 @@ export const remindersFeature: Feature = { const note = channel ? '' : ' Make sure you allow DMs from server members.'; + await respond( interaction, `Reminder set: ${describeReminder(reminder)}.${note}`, @@ -234,11 +249,12 @@ export const remindersFeature: Feature = { interaction.guildId, interaction.user.id, ); + await respond( interaction, active.length === 0 ? 'You have no active reminders.' - : active.map(describeReminder).join('\n'), + : active.map((reminder) => describeReminder(reminder)).join('\n'), ); }, edit: async (interaction, ctx) => { @@ -251,13 +267,16 @@ export const remindersFeature: Feature = { const when = interaction.options.getString('when'); const message = interaction.options.getString('message') ?? reminder.message; + if (when === null && message === reminder.message) { throw new UserError('Give a new time or message.'); } + const runAt = when === null ? reminder.runAt : parseFutureWhen(when, reminder.timezone); + await updateReminder(ctx.db, reminder.id, { message, runAt }); await ctx.scheduler.schedule( deliverJob, @@ -276,6 +295,7 @@ export const remindersFeature: Feature = { interaction.user.id, interaction.options.getInteger('id', true), ); + await updateReminder(ctx.db, reminder.id, { status: 'cancelled' }); await ctx.scheduler.cancel(jobKey(reminder.id)); await respond(interaction, `Cancelled reminder #${reminder.id}.`); @@ -287,6 +307,7 @@ export const remindersFeature: Feature = { interaction.guildId, interaction.user.id, ); + await interaction.respond( active.map((r) => ({ name: `#${r.id} ${r.message}`.slice(0, 100), diff --git a/src/features/reminders/schema.ts b/src/features/reminders/schema.ts index 617dfdd..d7a3c0f 100644 --- a/src/features/reminders/schema.ts +++ b/src/features/reminders/schema.ts @@ -25,7 +25,6 @@ export const reminders = pgTable( id: serial('id').primaryKey(), guildId: text('guild_id').notNull(), userId: text('user_id').notNull(), - /** Null delivers by direct message. */ channelId: text('channel_id'), message: text('message').notNull(), runAt: timestamp('run_at', { withTimezone: true }).notNull(), diff --git a/src/features/reminders/service.ts b/src/features/reminders/service.ts index 54e4097..65e5752 100644 --- a/src/features/reminders/service.ts +++ b/src/features/reminders/service.ts @@ -1,8 +1,8 @@ import { and, asc, count, eq } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; -import type { Recurrence } from '../../shared/time.js'; -import { reminders, type Reminder } from './schema.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; +import type { Recurrence } from '~/shared/time'; +import { reminders, type Reminder } from './schema'; export const maxActivePerUser = 25; export const maxMessageLength = 1000; @@ -26,8 +26,8 @@ export async function insertReminder( `Reminders can be at most ${maxMessageLength} characters.`, ); } + return db.transaction(async (tx) => { - // ponytail: two simultaneous requests can both pass this soft limit; fine for abuse prevention. const [active] = await tx .select({ total: count() }) .from(reminders) @@ -38,15 +38,19 @@ export async function insertReminder( eq(reminders.status, 'active'), ), ); + if ((active?.total ?? 0) >= maxActivePerUser) { throw new UserError( `You can have at most ${maxActivePerUser} active reminders.`, ); } + const [row] = await tx.insert(reminders).values(input).returning(); + if (!row) { throw new Error('Insert returned no row'); } + return row; }); } @@ -56,6 +60,7 @@ export async function getReminder( id: number, ): Promise { const [row] = await db.select().from(reminders).where(eq(reminders.id, id)); + return row; } @@ -86,7 +91,6 @@ export async function updateReminder( await db.update(reminders).set(changes).where(eq(reminders.id, id)); } -/** Active reminders the user owns in this guild; others are reported as missing. */ export async function requireOwnReminder( db: Db, guildId: string, @@ -94,6 +98,7 @@ export async function requireOwnReminder( id: number, ): Promise { const reminder = await getReminder(db, id); + if ( reminder?.guildId !== guildId || reminder.userId !== userId || @@ -101,5 +106,6 @@ export async function requireOwnReminder( ) { throw new UserError(`You have no active reminder #${id}.`); } + return reminder; } diff --git a/src/features/roles/guards.ts b/src/features/roles/guards.ts index 6198c37..b41b8ff 100644 --- a/src/features/roles/guards.ts +++ b/src/features/roles/guards.ts @@ -1,5 +1,5 @@ import { PermissionFlagsBits, type GuildMember, type Role } from 'discord.js'; -import { UserError } from '../../shared/errors.js'; +import { UserError } from '~/shared/errors'; const moderatorPermissions = [ PermissionFlagsBits.Administrator, @@ -14,35 +14,39 @@ const moderatorPermissions = [ PermissionFlagsBits.MentionEveryone, ]; -/** Why the bot must not hand this role out, or undefined when it may. */ export function selfAssignProblem(role: Role): string | undefined { if (role.id === role.guild.id) { return 'is the @everyone role'; } + if (role.managed) { return 'is managed by an integration'; } + if (moderatorPermissions.some((flag) => role.permissions.has(flag))) { return 'grants moderator permissions'; } + if (!role.editable) { return 'is above my highest role, or I lack Manage Roles'; } + return undefined; } export function requireSelfAssignable(role: Role): void { const problem = selfAssignProblem(role); + if (problem !== undefined) { throw new UserError(`${role.name} cannot be self-assigned: it ${problem}.`); } } -/** Members may only manage roles strictly below their own highest role. */ export function requireAbove(actor: GuildMember, role: Role): void { if (actor.id === actor.guild.ownerId) { return; } + if (actor.roles.highest.comparePositionTo(role) <= 0) { throw new UserError(`${role.name} is not below your highest role.`); } diff --git a/src/features/roles/index.ts b/src/features/roles/index.ts index f556832..1d1dae0 100644 --- a/src/features/roles/index.ts +++ b/src/features/roles/index.ts @@ -6,21 +6,13 @@ import { type GuildMember, type Role, } from 'discord.js'; -import { respond } from '../../core/discord/router.js'; -import { bySubcommand, deferred, defineListener } from '../../core/define.js'; -import type { - CommandInteraction, - Feature, - SlashCommand, -} from '../../core/feature.js'; -import { UserError } from '../../shared/errors.js'; -import { - requireAbove, - requireEditable, - requireSelfAssignable, -} from './guards.js'; -import { handleReaction, syncLegacyPanel } from './legacy.js'; -import { panelComponents, publishPanel } from './panels.js'; +import { respond } from '~/core/discord/router'; +import { bySubcommand, deferred, defineListener } from '~/core/define'; +import type { CommandInteraction, Feature, SlashCommand } from '~/core/feature'; +import { UserError } from '~/shared/errors'; +import { requireAbove, requireEditable, requireSelfAssignable } from './guards'; +import { handleReaction, syncLegacyPanel } from './legacy'; +import { panelComponents, publishPanel } from './panels'; import { addPanelRole, createPanel, @@ -30,7 +22,7 @@ import { removePanelRole, requirePanel, setPanelTitle, -} from './service.js'; +} from './service'; const data = new SlashCommandBuilder() .setName('role') @@ -155,10 +147,13 @@ function parseColor(value: string | null): number | undefined { if (value === null) { return undefined; } + const match = /^#?([\da-f]{6})$/i.exec(value); + if (match?.[1] === undefined) { throw new UserError('Color must be a hex value like #FFAC1C.'); } + return Number.parseInt(match[1], 16); } @@ -167,6 +162,7 @@ async function memberAndRole( ): Promise<{ role: Role; member: GuildMember }> { const role = interaction.options.getRole('role', true); const user = interaction.options.getUser('member', true); + requireAbove(interaction.member, role); requireEditable(role); if ( @@ -177,6 +173,7 @@ async function memberAndRole( 'Only administrators can hand out administrator roles.', ); } + return { role, member: await interaction.guild.members.fetch(user.id) }; } @@ -200,13 +197,16 @@ const command = { reason: `Requested by ${interaction.user.tag}`, ...(() => { const color = parseColor(interaction.options.getString('color')); + return color === undefined ? {} : { colors: { primaryColor: color } }; })(), }); + await respond(interaction, `Created ${role.toString()}.`); }), delete: deferred(async (interaction) => { const role = interaction.options.getRole('role', true); + requireAbove(interaction.member, role); requireEditable(role); await role.delete(`Requested by ${interaction.user.tag}`); @@ -214,6 +214,7 @@ const command = { }), assign: deferred(async (interaction) => { const { role, member } = await memberAndRole(interaction); + await member.roles.add(role, `Assigned by ${interaction.user.tag}`); await respond( interaction, @@ -222,6 +223,7 @@ const command = { }), remove: deferred(async (interaction) => { const { role, member } = await memberAndRole(interaction); + await member.roles.remove(role, `Removed by ${interaction.user.tag}`); await respond( interaction, @@ -246,6 +248,7 @@ const command = { (p) => `• #${p.id} ${p.title} (${p.kind}) in <#${p.channelId}>`, )), ]; + await respond(interaction, lines.join('\n')); }, 'panel create': deferred(async (interaction, ctx) => { @@ -259,6 +262,7 @@ const command = { title: interaction.options.getString('title', true), createdBy: interaction.user.id, }); + await publishPanel( ctx, await requirePanel(ctx.db, interaction.guildId, id), @@ -274,30 +278,37 @@ const command = { interaction.guildId, interaction.options.getInteger('panel', true), ); + if (panel.kind === 'reaction') { throw new UserError( 'The legacy reaction panel is configured through environment variables.', ); } + const add = interaction.options.getRole('add'); const remove = interaction.options.getRole('remove'); const title = interaction.options.getString('title'); + if (add) { requireSelfAssignable(add); requireAbove(interaction.member, add); const label = interaction.options.getString('label') ?? add.name; + await addPanelRole(ctx.db, panel.id, { roleId: add.id, label, emoji: null, }); } + if (remove && !(await removePanelRole(ctx.db, panel.id, remove.id))) { throw new UserError(`${remove.name} is not on this panel.`); } + if (title !== null) { await setPanelTitle(ctx.db, panel.id, title); } + await publishPanel( ctx, await requirePanel(ctx.db, interaction.guildId, panel.id), @@ -310,25 +321,30 @@ const command = { interaction.guildId, interaction.options.getInteger('panel', true), ); + if (panel.messageId !== null) { const channel = await ctx.client.channels .fetch(panel.channelId) .catch(() => null); + if (channel?.isTextBased() === true) { await channel.messages.delete(panel.messageId).catch(() => null); } } + await deletePanel(ctx.db, panel.id); const note = panel.kind === 'reaction' ? ' Unset ROLE_SELECTION_CHANNEL_ID, or it will be posted again on the next start.' : ''; + await respond(interaction, `Removed panel #${panel.id}.${note}`); }), }), autocomplete: async (interaction, ctx) => { const query = interaction.options.getFocused().toLowerCase(); const panels = await listPanels(ctx.db, interaction.guildId); + await interaction.respond( panels .filter( diff --git a/src/features/roles/legacy.ts b/src/features/roles/legacy.ts index 942468e..164bd87 100644 --- a/src/features/roles/legacy.ts +++ b/src/features/roles/legacy.ts @@ -7,22 +7,23 @@ import { type TextChannel, type User, } from 'discord.js'; -import type { AppContext } from '../../core/feature.js'; +import type { AppContext } from '~/core/feature'; +import { sequential } from '~/shared/async'; import { createPanel, findReactionPanel, findReactionRole, replacePanelRoles, setPanelMessage, -} from './service.js'; -import { selfAssignProblem } from './guards.js'; +} from './service'; +import { selfAssignProblem } from './guards'; -// Kept verbatim so the message posted by the previous bot is recognised. export const legacyMessage = 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur'; export function legacyRoles(ctx: Pick) { const { config } = ctx; + return [ { emoji: '1️⃣', roleId: config.TARKVARA_ROLE_ID, label: 'Tarkvara' }, { emoji: '2️⃣', roleId: config.HELPDESK_ROLE_ID, label: 'Helpdesk' }, @@ -48,36 +49,48 @@ async function findOrPostMessage( ); } } + const recent = await channel.messages.fetch({ limit: 50 }); const existing = recent.find( (message) => message.author.id === ctx.client.user.id && message.content === legacyMessage, ); + return existing ?? post(); } -/** - * Ensures the env-configured reaction panel exists exactly once. Its message - * ID is persisted, so later restarts never search the channel or repost. - */ export async function syncLegacyPanel(ctx: AppContext): Promise { const channelId = ctx.config.ROLE_SELECTION_CHANNEL_ID; + if (channelId === undefined) { return; } + const channel = await ctx.client.channels.fetch(channelId); + if (channel?.type !== ChannelType.GuildText) { ctx.log.error( { channelId }, 'ROLE_SELECTION_CHANNEL_ID is not a server text channel', ); + return; } + const roles = legacyRoles(ctx); - for (const { roleId, label } of roles) { - const role = await channel.guild.roles.fetch(roleId); + + const fetched = await Promise.all( + roles.map(async ({ roleId, label }) => ({ + roleId, + label, + role: await channel.guild.roles.fetch(roleId), + })), + ); + + for (const { roleId, label, role } of fetched) { const problem = role ? selfAssignProblem(role) : 'does not exist'; + if (problem !== undefined) { ctx.log.error( { roleId, label, problem }, @@ -100,6 +113,7 @@ export async function syncLegacyPanel(ctx: AppContext): Promise { }), messageId: null, }; + await replacePanelRoles(ctx.db, panel.id, roles); const message = await findOrPostMessage( @@ -108,17 +122,20 @@ export async function syncLegacyPanel(ctx: AppContext): Promise { panel.messageId, async () => { ctx.log.info({ channelId }, 'Posting role selection message'); + return channel.send(legacyMessage); }, ); + if (message.id !== panel.messageId) { await setPanelMessage(ctx.db, panel.id, message.id); } - for (const { emoji } of roles) { - if (message.reactions.cache.get(emoji)?.me !== true) { - await message.react(emoji); - } - } + + const missing = roles.filter( + ({ emoji }) => message.reactions.cache.get(emoji)?.me !== true, + ); + + await sequential(missing, ({ emoji }) => message.react(emoji)); } export async function handleReaction( @@ -129,35 +146,44 @@ export async function handleReaction( ): Promise { const { message } = reaction; const emoji = reaction.emoji.name; + if (user.bot || message.guildId === null || emoji === null) { return; } - // One indexed lookup filters out reactions on every other message. + const roleId = await findReactionRole(ctx.db, { guildId: message.guildId, channelId: message.channelId, messageId: message.id, emoji, }); + if (roleId === undefined) { return; } + const guild = await ctx.client.guilds.fetch(message.guildId); const role = await guild.roles.fetch(roleId); const problem = role ? selfAssignProblem(role) : 'does not exist'; + if (!role || problem !== undefined) { ctx.log.warn({ roleId, problem }, 'Skipping reaction role change'); + return; } + const member = await guild.members.fetch(user.id); + if (member.user.bot) { return; } + if (add) { await member.roles.add(role, 'Role selection reaction'); } else { await member.roles.remove(role, 'Role selection reaction removed'); } + ctx.log.info( { guildId: guild.id, userId: user.id, role: role.name, add }, add ? 'Assigned role' : 'Removed role', diff --git a/src/features/roles/panels.ts b/src/features/roles/panels.ts index c4a57fc..de6eb0b 100644 --- a/src/features/roles/panels.ts +++ b/src/features/roles/panels.ts @@ -8,11 +8,11 @@ import { StringSelectMenuBuilder, type BaseMessageOptions, } from 'discord.js'; -import { customId } from '../../core/registry.js'; -import type { AppContext, ComponentHandler } from '../../core/feature.js'; -import { UserError } from '../../shared/errors.js'; -import { selfAssignProblem } from './guards.js'; -import { requirePanel, setPanelMessage, type Panel } from './service.js'; +import { customId } from '~/core/registry'; +import type { AppContext, ComponentHandler } from '~/core/feature'; +import { UserError } from '~/shared/errors'; +import { selfAssignProblem } from './guards'; +import { requirePanel, setPanelMessage, type Panel } from './service'; export function renderPanel(panel: Panel): BaseMessageOptions { const embed = new EmbedBuilder() @@ -26,6 +26,7 @@ export function renderPanel(panel: Panel): BaseMessageOptions { .setCustomId(customId('roles:open', panel.id)) .setLabel('Choose roles') .setStyle(ButtonStyle.Primary); + return { embeds: [embed], components: @@ -35,7 +36,6 @@ export function renderPanel(panel: Panel): BaseMessageOptions { }; } -/** Re-renders a panel message, reposting it if it was deleted. */ export async function publishPanel( ctx: AppContext, panel: Panel, @@ -43,28 +43,37 @@ export async function publishPanel( const channel = await ctx.client.channels .fetch(panel.channelId) .catch(() => null); + if (channel?.type !== ChannelType.GuildText) { throw new UserError(`I can no longer access <#${panel.channelId}>.`); } + const content = renderPanel(panel); + if (panel.messageId !== null) { const existing = await channel.messages .fetch(panel.messageId) .catch(() => null); + if (existing) { await existing.edit(content); + return; } } + const message = await channel.send(content); + await setPanelMessage(ctx.db, panel.id, message.id); } function parsePanelId(args: readonly string[]): number { const id = Number(args[0]); + if (!Number.isSafeInteger(id)) { throw new UserError('This role panel is invalid.'); } + return id; } @@ -76,9 +85,11 @@ const openHandler: ComponentHandler = { interaction.guildId, parsePanelId(args), ); + if (panel.roles.length === 0) { throw new UserError('This panel has no roles yet.'); } + const select = new StringSelectMenuBuilder() .setCustomId(customId('roles:choose', panel.id)) .setPlaceholder('Select your roles') @@ -91,6 +102,7 @@ const openHandler: ComponentHandler = { default: interaction.member.roles.cache.has(role.roleId), })), ); + await interaction.reply({ content: 'Pick the roles you want. Unselected roles from this panel are removed.', @@ -108,6 +120,7 @@ const chooseHandler: ComponentHandler = { if (!interaction.isStringSelectMenu()) { return; } + await interaction.deferUpdate(); const panel = await requirePanel( ctx.db, @@ -119,26 +132,31 @@ const chooseHandler: ComponentHandler = { const toRemove: string[] = []; const skipped: string[] = []; - // Re-validated against the panel's current roles; submitted values are untrusted. for (const { roleId, label } of panel.roles) { const role = interaction.guild.roles.cache.get(roleId); + if (!role || selfAssignProblem(role) !== undefined) { skipped.push(label); continue; } + const has = interaction.member.roles.cache.has(roleId); + if (wanted.has(roleId) && !has) { toAdd.push(roleId); } else if (!wanted.has(roleId) && has) { toRemove.push(roleId); } } + if (toAdd.length > 0) { await interaction.member.roles.add(toAdd, 'Role panel selection'); } + if (toRemove.length > 0) { await interaction.member.roles.remove(toRemove, 'Role panel selection'); } + ctx.log.info( { guildId: interaction.guildId, @@ -156,6 +174,7 @@ const chooseHandler: ComponentHandler = { ? [`Unavailable right now: ${skipped.join(', ')}`] : []), ]; + await interaction.editReply({ content: lines.join('\n'), components: [] }); }, }; diff --git a/src/features/roles/schema.ts b/src/features/roles/schema.ts index ad416af..f84545c 100644 --- a/src/features/roles/schema.ts +++ b/src/features/roles/schema.ts @@ -29,7 +29,6 @@ export const rolePanels = pgTable( }, (table) => [ index('role_panels_guild_idx').on(table.guildId), - // The env-configured legacy panel exists at most once per channel. uniqueIndex('role_panels_reaction_channel_idx') .on(table.guildId, table.channelId) .where(sql`${table.kind} = 'reaction'`), diff --git a/src/features/roles/service.ts b/src/features/roles/service.ts index f9bc3cc..81de264 100644 --- a/src/features/roles/service.ts +++ b/src/features/roles/service.ts @@ -1,7 +1,7 @@ import { and, asc, count, eq, max } from 'drizzle-orm'; -import type { Db } from '../../db/client.js'; -import { UserError } from '../../shared/errors.js'; -import { rolePanelRoles, rolePanels } from './schema.js'; +import type { Db } from '~/db/client'; +import { UserError } from '~/shared/errors'; +import { rolePanelRoles, rolePanels } from './schema'; export const maxPanelRoles = 25; @@ -13,7 +13,6 @@ export type PanelRole = { export type Panel = typeof rolePanels.$inferSelect & { roles: PanelRole[] }; -/** The role bound to a reaction on a reaction panel, if that is what it is. */ export async function findReactionRole( db: Db, reaction: { @@ -37,6 +36,7 @@ export async function findReactionRole( ), ) .limit(1); + return row?.roleId; } @@ -49,9 +49,11 @@ export async function getPanel( .select() .from(rolePanels) .where(and(eq(rolePanels.id, panelId), eq(rolePanels.guildId, guildId))); + if (!panel) { return undefined; } + const roles = await db .select({ roleId: rolePanelRoles.roleId, @@ -61,6 +63,7 @@ export async function getPanel( .from(rolePanelRoles) .where(eq(rolePanelRoles.panelId, panelId)) .orderBy(asc(rolePanelRoles.position)); + return { ...panel, roles }; } @@ -70,9 +73,11 @@ export async function requirePanel( panelId: number, ): Promise { const panel = await getPanel(db, guildId, panelId); + if (!panel) { throw new UserError(`Role panel #${panelId} does not exist.`); } + return panel; } @@ -90,7 +95,6 @@ export async function listPanels(db: Db, guildId: string) { .limit(100); } -/** Every role members can give themselves through a panel in this guild. */ export async function listSelfAssignableRoles( db: Db, guildId: string, @@ -121,9 +125,11 @@ export async function createPanel( .insert(rolePanels) .values(input) .returning({ id: rolePanels.id }); + if (!row) { throw new Error('Insert returned no row'); } + return row.id; } @@ -142,6 +148,7 @@ export async function findReactionPanel( eq(rolePanels.kind, 'reaction'), ), ); + return panel; } @@ -187,7 +194,6 @@ export async function addPanelRole( role: PanelRole, ): Promise { await db.transaction(async (tx) => { - // Lock the panel so concurrent additions cannot exceed the limit. await tx .select({ id: rolePanels.id }) .from(rolePanels) @@ -197,14 +203,17 @@ export async function addPanelRole( .select({ total: count(), last: max(rolePanelRoles.position) }) .from(rolePanelRoles) .where(eq(rolePanelRoles.panelId, panelId)); + if ((stats?.total ?? 0) >= maxPanelRoles) { throw new UserError(`A panel can hold at most ${maxPanelRoles} roles.`); } + const inserted = await tx .insert(rolePanelRoles) .values({ ...role, panelId, position: (stats?.last ?? -1) + 1 }) .onConflictDoNothing() .returning({ roleId: rolePanelRoles.roleId }); + if (inserted.length === 0) { throw new UserError('That role is already on this panel.'); } @@ -225,6 +234,7 @@ export async function removePanelRole( ), ) .returning({ roleId: rolePanelRoles.roleId }); + return rows.length > 0; } diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts index 66015e5..b39f870 100644 --- a/src/features/settings/index.ts +++ b/src/features/settings/index.ts @@ -3,13 +3,10 @@ import { MessageFlags, SlashCommandBuilder, } from 'discord.js'; -import { bySubcommand } from '../../core/define.js'; -import type { Feature } from '../../core/feature.js'; -import { - getGuildTimezone, - setGuildTimezone, -} from '../../core/guild-settings.js'; -import { requireZone } from '../../shared/time.js'; +import { bySubcommand } from '~/core/define'; +import type { Feature } from '~/core/feature'; +import { getGuildTimezone, setGuildTimezone } from '~/core/guild-settings'; +import { requireZone } from '~/shared/time'; const data = new SlashCommandBuilder() .setName('settings') @@ -35,6 +32,7 @@ export const settingsFeature: Feature = { execute: bySubcommand({ timezone: async (interaction, ctx) => { const zone = interaction.options.getString('zone'); + if (zone !== null) { await ctx.authz.require(interaction.member, 'settings:manage'); await setGuildTimezone( @@ -43,11 +41,13 @@ export const settingsFeature: Feature = { requireZone(zone), ); } + const current = await getGuildTimezone( ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE, ); + await interaction.reply({ content: `Server timezone: **${current}**`, flags: MessageFlags.Ephemeral, diff --git a/src/index.ts b/src/index.ts index a9b2121..be5bb6b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,14 +1,16 @@ -import { startApp } from './app.js'; -import { loadConfig } from './core/config.js'; -import { createLogger } from './core/logger.js'; +import { startApp } from './app'; +import { loadConfig } from '~/core/config'; +import { createLogger } from '~/core/logger'; let config: ReturnType; + try { config = loadConfig(); } catch (error) { console.error(error instanceof Error ? error.message : error); process.exit(1); } + const log = createLogger(config.LOG_LEVEL); process.on('unhandledRejection', (reason) => { @@ -22,6 +24,7 @@ try { if (stopping) { return; } + stopping = true; log.info({ signal }, 'Shutting down'); stop().then( @@ -32,6 +35,7 @@ try { }, ); }; + process.once('SIGINT', shutdown); process.once('SIGTERM', shutdown); } catch (error) { diff --git a/src/integrations/redmine/client.ts b/src/integrations/redmine/client.ts index e7b58ec..51815f5 100644 --- a/src/integrations/redmine/client.ts +++ b/src/integrations/redmine/client.ts @@ -81,7 +81,6 @@ export type RedmineErrorKind = | 'unavailable' | 'invalid_response'; -/** A normalised Redmine failure. `message` is safe to show to users. */ export class RedmineError extends Error { override readonly name = 'RedmineError'; constructor( @@ -126,7 +125,6 @@ const messages: Record = { 404: ['not_found', 'Redmine could not find that (or you cannot see it).'], }; -/** Redmine timestamps are second precision; this is the format its filters accept. */ const redmineTime = (date: Date) => `${date.toISOString().slice(0, 19)}Z`; export class RedmineClient { @@ -141,23 +139,26 @@ export class RedmineClient { path, this.baseUrl.endsWith('/') ? this.baseUrl : `${this.baseUrl}/`, ); + for (const [key, value] of Object.entries(request.query ?? {})) { url.searchParams.set(key, value); } + const method = request.method ?? 'GET'; - // Only reads are retried; repeating a write could apply it twice. - const attempts = method === 'GET' ? 2 : 1; - for (let attempt = 1; ; attempt++) { - try { - return await this.send(url, method, request.body); - } catch (error) { - if ( - !(error instanceof RedmineError && error.kind === 'unavailable') || - attempt >= attempts - ) { - throw error; - } + + try { + return await this.send(url, method, request.body); + } catch (error) { + const retryable = + method === 'GET' && + error instanceof RedmineError && + error.kind === 'unavailable'; + + if (!retryable) { + throw error; } + + return this.send(url, method, request.body); } } @@ -167,6 +168,7 @@ export class RedmineClient { body: unknown, ): Promise { let response: Response; + try { response = await (this.options.fetch ?? fetch)(url, { method, @@ -181,10 +183,12 @@ export class RedmineClient { } catch { throw new RedmineError('unavailable', 'Redmine did not respond in time.'); } + if (response.status === 422) { const parsed = z .object({ errors: z.array(z.string()) }) .safeParse(await response.json().catch(() => null)); + throw new RedmineError( 'validation', parsed.success @@ -192,17 +196,22 @@ export class RedmineClient { : 'Redmine rejected the request.', ); } + const known = messages[response.status]; + if (known) { throw new RedmineError(...known); } + if (!response.ok) { throw new RedmineError( 'unavailable', `Redmine is unavailable (HTTP ${response.status}).`, ); } + const text = await response.text(); + return text === '' ? null : JSON.parse(text); } @@ -214,12 +223,14 @@ export class RedmineClient { const parsed = schema.safeParse( await this.request(path, query === undefined ? {} : { query }), ); + if (!parsed.success) { throw new RedmineError( 'invalid_response', 'Redmine sent a response I do not understand.', ); } + return parsed.data; } @@ -228,6 +239,7 @@ export class RedmineClient { 'users/current.json', z.object({ user: userSchema }), ); + return data.user; } @@ -239,6 +251,7 @@ export class RedmineClient { offset: String(offset), limit: String(Math.min(limit, 100)), }); + return { projects: data.projects, total: data.total_count ?? data.projects.length, @@ -254,19 +267,25 @@ export class RedmineClient { offset: String(query.offset ?? 0), limit: String(Math.min(query.limit ?? 25, 100)), }; + if (query.projectId !== undefined) { params.project_id = String(query.projectId); } + if (query.assignedToMe === true) { params.assigned_to_id = 'me'; } + if (query.updatedSince) { params.updated_on = `>=${redmineTime(query.updatedSince)}`; } + if (query.dueDate !== undefined) { params.due_date = query.dueDate; } + const data = await this.get('issues.json', issuesPage, params); + return { issues: data.issues, total: data.total_count ?? data.issues.length, @@ -280,6 +299,7 @@ export class RedmineClient { z.object({ issue: issueSchema }), query, ); + return data.issue; } @@ -288,6 +308,7 @@ export class RedmineClient { 'issue_statuses.json', z.object({ issue_statuses: z.array(statusSchema) }), ); + return data.issue_statuses; } @@ -299,12 +320,14 @@ export class RedmineClient { body: { issue: fields }, }); const parsed = z.object({ issue: issueSchema }).safeParse(data); + if (!parsed.success) { throw new RedmineError( 'invalid_response', 'Redmine created the issue but sent an unexpected response.', ); } + return parsed.data.issue; } diff --git a/src/shared/crypto.ts b/src/shared/crypto.ts index 9759666..28e8c44 100644 --- a/src/shared/crypto.ts +++ b/src/shared/crypto.ts @@ -2,15 +2,13 @@ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; const version = 'v1'; -/** - * AES-256-GCM with a key held outside the database. The output carries its - * own IV and auth tag, so tampered or wrongly keyed values fail to decrypt. - */ export function createSecretBox(base64Key: string) { const key = Buffer.from(base64Key, 'base64'); + if (key.length !== 32) { throw new Error('Encryption key must be 32 bytes'); } + return { encrypt: (plaintext: string): string => { const iv = randomBytes(12); @@ -19,6 +17,7 @@ export function createSecretBox(base64Key: string) { cipher.update(plaintext, 'utf8'), cipher.final(), ]); + return [version, iv, cipher.getAuthTag(), data] .map((part) => typeof part === 'string' ? part : part.toString('base64'), @@ -27,6 +26,7 @@ export function createSecretBox(base64Key: string) { }, decrypt: (sealed: string): string => { const [prefix, iv, tag, data] = sealed.split(':'); + if ( prefix !== version || iv === undefined || @@ -35,12 +35,15 @@ export function createSecretBox(base64Key: string) { ) { throw new Error('Unrecognised secret format'); } + const decipher = createDecipheriv( 'aes-256-gcm', key, Buffer.from(iv, 'base64'), ); + decipher.setAuthTag(Buffer.from(tag, 'base64')); + return Buffer.concat([ decipher.update(Buffer.from(data, 'base64')), decipher.final(), diff --git a/src/shared/time.ts b/src/shared/time.ts index 2436128..636735f 100644 --- a/src/shared/time.ts +++ b/src/shared/time.ts @@ -1,5 +1,6 @@ -import { DateTime, IANAZone } from 'luxon'; -import { UserError } from './errors.js'; +import { TZDate, tz } from '@date-fns/tz'; +import { addDays, addMonths, addWeeks, isValid, parse, set } from 'date-fns'; +import { UserError } from './errors'; const unitMs: Partial> = { w: 604_800_000, @@ -7,24 +8,40 @@ const unitMs: Partial> = { h: 3_600_000, m: 60_000, }; + const absoluteFormats = [ 'yyyy-MM-dd HH:mm', "yyyy-MM-dd'T'HH:mm", - 'd.M.yyyy HH:mm', 'd.M.yyyy H:mm', 'yyyy-MM-dd', 'd.M.yyyy', ]; +const steps = { daily: addDays, weekly: addWeeks, monthly: addMonths }; + export const recurrences = ['daily', 'weekly', 'monthly'] as const; + export type Recurrence = (typeof recurrences)[number]; +export type CalendarDay = { year: number; month: number; day: number }; + +export function isZone(zone: string): boolean { + try { + new Intl.DateTimeFormat('en', { timeZone: zone }); + + return true; + } catch { + return false; + } +} + export function requireZone(zone: string): string { - if (!IANAZone.isValidZone(zone)) { + if (!isZone(zone)) { throw new UserError( `Unknown timezone "${zone}". Use an IANA name like Europe/Tallinn.`, ); } + return zone; } @@ -33,60 +50,72 @@ function parseRelative(input: string, now: Date): Date | undefined { .trim() .replace(/^in\s+/i, '') .replaceAll(/\s+/g, ''); + if (!/^(?:\d+[wdhm])+$/i.test(compact)) { return undefined; } - let total = 0; - for (const part of compact.toLowerCase().split(/(?<=[wdhm])/)) { - total += Number(part.slice(0, -1)) * (unitMs[part.slice(-1)] ?? 0); - } + + const total = compact + .toLowerCase() + .split(/(?<=[wdhm])/) + .reduce( + (sum, part) => + sum + Number(part.slice(0, -1)) * (unitMs[part.slice(-1)] ?? 0), + 0, + ); + return new Date(now.getTime() + total); } +function parseClock(input: string, zone: string, now: Date): Date | undefined { + const clock = /^(\d{1,2}):(\d{2})$/.exec(input); + + if (!clock) { + return undefined; + } + + const hours = Number(clock[1]); + const minutes = Number(clock[2]); + + if (hours > 23 || minutes > 59) { + return undefined; + } + + const today = set( + now, + { hours, minutes, seconds: 0, milliseconds: 0 }, + { in: tz(zone) }, + ); + + return today <= now ? addDays(today, 1, { in: tz(zone) }) : today; +} + function parseAbsolute( input: string, zone: string, now: Date, ): Date | undefined { const trimmed = input.trim(); - const clock = /^(\d{1,2}):(\d{2})$/.exec(trimmed); - if (clock) { - // A bare time means its next occurrence. - const today = DateTime.fromJSDate(now, { zone }).set({ - hour: Number(clock[1]), - minute: Number(clock[2]), - second: 0, - millisecond: 0, - }); - if (!today.isValid) { - return undefined; - } - return ( - today.toMillis() <= now.getTime() ? today.plus({ days: 1 }) : today - ).toJSDate(); - } - for (const format of absoluteFormats) { - const parsed = DateTime.fromFormat(trimmed, format, { zone }); - if (parsed.isValid) { - return parsed.toJSDate(); - } - } - return undefined; + + return ( + parseClock(trimmed, zone, now) ?? + absoluteFormats + .map((format) => parse(trimmed, format, now, { in: tz(zone) })) + .find((date) => isValid(date)) + ); } -/** - * Parses "10m", "2h30m", "1w 2d", "18:30", "2026-11-20 18:00" or - * "20.11.2026 18:00". Absolute times are read in the given IANA zone. - */ export function parseWhen(input: string, zone: string, now = new Date()): Date { const date = parseRelative(input, now) ?? parseAbsolute(input, requireZone(zone), now); + if (date === undefined) { throw new UserError( `I could not read "${input}". Try "30m", "2h", "1d", "18:30" or "2026-11-20 18:00".`, ); } - return date; + + return new Date(date.getTime()); } export function parseFutureWhen( @@ -95,27 +124,22 @@ export function parseFutureWhen( now = new Date(), ): Date { const date = parseWhen(input, zone, now); - if (date.getTime() <= now.getTime()) { + + if (date <= now) { throw new UserError('That time is in the past.'); } + return date; } -/** Advances by wall-clock time in the zone, so recurrences survive DST. */ export function nextOccurrence( from: Date, recurrence: Recurrence, zone: string, ): Date { - const step = { - daily: { days: 1 }, - weekly: { weeks: 1 }, - monthly: { months: 1 }, - }[recurrence]; - return DateTime.fromJSDate(from, { zone }).plus(step).toJSDate(); + return new Date(steps[recurrence](from, 1, { in: tz(zone) }).getTime()); } -/** First occurrence strictly after `now`, skipping any missed while offline. */ export function nextFutureOccurrence( from: Date, recurrence: Recurrence, @@ -123,13 +147,45 @@ export function nextFutureOccurrence( now = new Date(), ): Date { let next = nextOccurrence(from, recurrence, zone); - while (next.getTime() <= now.getTime()) { + + while (next <= now) { next = nextOccurrence(next, recurrence, zone); } + return next; } -/** Discord renders these in each reader's own timezone. */ +export function nextDailyRun( + zone: string, + hour: number, + now = new Date(), +): Date { + const today = set( + now, + { hours: hour, minutes: 0, seconds: 0, milliseconds: 0 }, + { in: tz(zone) }, + ); + const next = today <= now ? addDays(today, 1, { in: tz(zone) }) : today; + + return new Date(next.getTime()); +} + +export function calendarDay(date: Date, zone: string): CalendarDay { + const local = new TZDate(date, zone); + + return { + year: local.getFullYear(), + month: local.getMonth() + 1, + day: local.getDate(), + }; +} + +export function zonedTime(day: CalendarDay, hour: number, zone: string): Date { + return new Date( + new TZDate(day.year, day.month - 1, day.day, hour, 0, 0, zone).getTime(), + ); +} + export function discordTime( date: Date, style: 'F' | 'R' | 'f' | 'D' = 'F', @@ -137,14 +193,32 @@ export function discordTime( return ``; } -/** The next time the clock in `zone` reads `hour`:00, strictly after now. */ -export function nextDailyRun( - zone: string, - hour: number, - now = DateTime.now(), -): Date { - const today = now - .setZone(zone) - .set({ hour, minute: 0, second: 0, millisecond: 0 }); - return (today <= now ? today.plus({ days: 1 }) : today).toJSDate(); +export function addCalendarDays(day: CalendarDay, days: number): CalendarDay { + const date = new Date(Date.UTC(day.year, day.month - 1, day.day + days)); + + return { + year: date.getUTCFullYear(), + month: date.getUTCMonth() + 1, + day: date.getUTCDate(), + }; +} + +export function formatCalendarDay(day: CalendarDay): string { + return [day.year, day.month, day.day] + .map((part) => String(part).padStart(2, '0')) + .join('-'); +} + +export function parseCalendarDay(value: string): CalendarDay | undefined { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + + if (!match) { + return undefined; + } + + return { + year: Number(match[1]), + month: Number(match[2]), + day: Number(match[3]), + }; } From 0c1cbdce05bc6c2ba0f4c2c8ff9dc5c6f4a9cf2b Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:16:15 +0200 Subject: [PATCH 020/199] refactor: move infrastructure into infra/, domain/, config/ and lib/ behind barrels --- drizzle.config.ts | 4 +- eslint.config.ts | 85 ++++++++++++------- scripts/migrate.ts | 2 +- scripts/register-commands.ts | 4 +- src/app.ts | 20 +++-- src/{core/config.ts => config/env.ts} | 2 +- src/config/index.ts | 1 + src/{shared => domain}/errors.ts | 0 src/domain/index.ts | 2 + src/{shared => domain}/time.ts | 0 src/features/announcements/index.ts | 23 +++-- src/features/announcements/service.ts | 4 +- src/features/birthdays/index.ts | 18 ++-- src/features/birthdays/service.ts | 6 +- src/features/events/index.ts | 20 +++-- src/features/events/service.ts | 4 +- src/features/movies/index.ts | 10 +-- src/features/movies/service.ts | 4 +- src/features/permissions/index.ts | 15 ++-- src/features/polls/index.ts | 18 ++-- src/features/polls/service.ts | 4 +- src/features/redmine/index.ts | 21 +++-- src/features/redmine/notifications.ts | 13 ++- src/features/redmine/service.ts | 7 +- src/features/reminders/index.ts | 13 ++- src/features/reminders/service.ts | 6 +- src/features/roles/guards.ts | 2 +- src/features/roles/index.ts | 16 +++- src/features/roles/legacy.ts | 4 +- src/features/roles/panels.ts | 6 +- src/features/roles/service.ts | 4 +- src/features/settings/index.ts | 8 +- src/index.ts | 6 +- src/infra/crypto/index.ts | 1 + .../crypto.ts => infra/crypto/secret-box.ts} | 0 src/{ => infra}/db/client.ts | 2 +- src/infra/db/index.ts | 6 ++ .../schema.ts => infra/db/jobs/model.ts} | 0 .../store.ts => infra/db/jobs/repo.ts} | 4 +- .../db/permissions/model.ts} | 0 .../store.ts => infra/db/permissions/repo.ts} | 4 +- .../db/settings/repo.ts} | 2 +- .../discord}/authorizer.ts | 8 +- src/{core => infra}/discord/client.ts | 0 src/{core => infra/discord}/define.ts | 6 +- src/{core => infra}/discord/errors.ts | 2 +- src/infra/discord/index.ts | 8 ++ .../feature.ts => infra/discord/module.ts} | 6 +- src/{core => infra}/discord/registration.ts | 2 +- src/{core => infra/discord}/registry.ts | 2 +- src/{core => infra}/discord/router.ts | 6 +- src/infra/logging/index.ts | 1 + src/{core => infra/logging}/logger.ts | 0 src/{integrations => infra}/redmine/client.ts | 0 src/infra/redmine/index.ts | 1 + src/infra/scheduler/index.ts | 1 + src/{core => infra}/scheduler/scheduler.ts | 11 ++- src/{shared => lib}/async.ts | 0 src/lib/index.ts | 1 + tests/app.test.ts | 2 +- tests/core/discord/router.test.ts | 7 +- tests/core/permissions/authorizer.test.ts | 6 +- tests/core/registry.test.ts | 4 +- tests/core/scheduler/scheduler.test.ts | 11 ++- tests/db.ts | 2 +- .../announcements/announcements.test.ts | 2 +- tests/features/birthdays/birthdays.test.ts | 4 +- tests/features/events/events.test.ts | 4 +- tests/features/movies/movies.test.ts | 2 +- .../features/permissions/permissions.test.ts | 2 +- tests/features/polls/polls.test.ts | 4 +- tests/features/redmine/redmine.test.ts | 9 +- tests/features/reminders/reminders.test.ts | 4 +- tests/features/roles/roles.test.ts | 2 +- tests/global-setup.ts | 2 +- tests/integrations/redmine/client.test.ts | 2 +- tests/shared/crypto.test.ts | 2 +- tests/shared/time.test.ts | 4 +- 78 files changed, 280 insertions(+), 221 deletions(-) rename src/{core/config.ts => config/env.ts} (97%) create mode 100644 src/config/index.ts rename src/{shared => domain}/errors.ts (100%) create mode 100644 src/domain/index.ts rename src/{shared => domain}/time.ts (100%) create mode 100644 src/infra/crypto/index.ts rename src/{shared/crypto.ts => infra/crypto/secret-box.ts} (100%) rename src/{ => infra}/db/client.ts (94%) create mode 100644 src/infra/db/index.ts rename src/{core/scheduler/schema.ts => infra/db/jobs/model.ts} (100%) rename src/{core/scheduler/store.ts => infra/db/jobs/repo.ts} (96%) rename src/{core/permissions/schema.ts => infra/db/permissions/model.ts} (100%) rename src/{core/permissions/store.ts => infra/db/permissions/repo.ts} (95%) rename src/{core/guild-settings.ts => infra/db/settings/repo.ts} (95%) rename src/{core/permissions => infra/discord}/authorizer.ts (85%) rename src/{core => infra}/discord/client.ts (100%) rename src/{core => infra/discord}/define.ts (93%) rename src/{core => infra}/discord/errors.ts (95%) create mode 100644 src/infra/discord/index.ts rename src/{core/feature.ts => infra/discord/module.ts} (95%) rename src/{core => infra}/discord/registration.ts (92%) rename src/{core => infra/discord}/registry.ts (99%) rename src/{core => infra}/discord/router.ts (96%) create mode 100644 src/infra/logging/index.ts rename src/{core => infra/logging}/logger.ts (100%) rename src/{integrations => infra}/redmine/client.ts (100%) create mode 100644 src/infra/redmine/index.ts create mode 100644 src/infra/scheduler/index.ts rename src/{core => infra}/scheduler/scheduler.ts (91%) rename src/{shared => lib}/async.ts (100%) create mode 100644 src/lib/index.ts diff --git a/drizzle.config.ts b/drizzle.config.ts index c122bfb..62e2463 100644 --- a/drizzle.config.ts +++ b/drizzle.config.ts @@ -3,8 +3,8 @@ import { defineConfig } from 'drizzle-kit'; export default defineConfig({ dialect: 'postgresql', schema: [ - './src/core/**/schema.ts', - './src/core/guild-settings.ts', + './src/infra/db/**/model.ts', + './src/infra/db/settings/repo.ts', './src/features/*/schema.ts', ], out: './drizzle', diff --git a/eslint.config.ts b/eslint.config.ts index 5a89a37..a8c343f 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -79,27 +79,36 @@ const qualityRules: Linter.RulesRecord = { }; const transportFreeFiles = [ - 'src/db/**/*.ts', - 'src/integrations/**/*.ts', - 'src/shared/**/*.ts', - 'src/core/scheduler/store.ts', - 'src/core/permissions/store.ts', -]; -const transportFreeFeatureFiles = [ + 'src/config/**/*.ts', + 'src/domain/**/*.ts', + 'src/lib/**/*.ts', + 'src/core/**/*.ts', + 'src/infra/db/**/*.ts', + 'src/infra/redmine/**/*.ts', + 'src/infra/crypto/**/*.ts', + 'src/infra/logging/**/*.ts', + 'src/infra/scheduler/**/*.ts', + 'src/infra/web/**/*.ts', 'src/features/*/service.ts', 'src/features/*/schema.ts', ]; const noDiscordImport = { name: 'discord.js', - message: - 'Keep Discord transport code out of services, stores and integrations.', + message: 'Only the Discord adapter may use discord.js.', }; -const featurePrivatePattern = { - group: ['../*/*', '!../*/index.js', '!../../**'], - message: "Import other features only through their public 'index.js'.", -}; +const modulePatterns = [ + { + regex: + '^~/(config|domain|lib|core/ports|core/services|infra/[a-z-]+|features/[a-z-]+)/', + message: 'Import from the module barrel, not a file inside it.', + }, + { + regex: String.raw`^(\.\./)+(config|domain|lib|core|infra|features|app)(/|$)`, + message: 'Import other modules through their ~/ barrel.', + }, +]; const unicornRules: Linter.RulesRecord = { 'unicorn/prefer-set-has': 'error', @@ -326,24 +335,43 @@ export default defineConfig( ], }, ], + 'import-x/no-duplicates': 'error', 'import-x/no-restricted-paths': [ 'error', { zones: [ + { + target: './src/domain', + from: [ + './src/core', + './src/infra', + './src/config', + './src/features', + './src/app.ts', + ], + message: 'The domain depends on nothing but itself and lib.', + }, { target: './src/core', - from: ['./src/features', './src/app.ts', './src/index.ts'], - message: 'Core must not depend on concrete features.', + from: ['./src/infra', './src/features', './src/app.ts'], + message: 'Ports and services must not know their adapters.', }, { - target: './src/features', - from: ['./src/app.ts', './src/index.ts'], - message: 'Features must not import the composition root.', + target: './src/lib', + from: [ + './src/domain', + './src/core', + './src/infra', + './src/config', + './src/features', + './src/app.ts', + ], + message: 'lib is generic and depends on nothing in the app.', }, { - target: ['./src/db', './src/integrations', './src/shared'], - from: ['./src/features', './src/core', './src/app.ts'], - message: 'Infrastructure must not depend on application code.', + target: ['./src/infra', './src/features'], + from: ['./src/app.ts', './src/index.ts'], + message: 'Adapters must not import the composition root.', }, ], }, @@ -352,25 +380,18 @@ export default defineConfig( }, { - files: ['src/features/**/*.ts'], + files: ['src/**/*.ts'], rules: { - 'no-restricted-imports': ['error', { patterns: [featurePrivatePattern] }], + 'no-restricted-imports': ['error', { patterns: modulePatterns }], }, }, { files: transportFreeFiles, - rules: { - 'no-restricted-imports': ['error', { paths: [noDiscordImport] }], - }, - }, - - { - files: transportFreeFeatureFiles, rules: { 'no-restricted-imports': [ 'error', - { paths: [noDiscordImport], patterns: [featurePrivatePattern] }, + { paths: [noDiscordImport], patterns: modulePatterns }, ], }, }, @@ -389,7 +410,7 @@ export default defineConfig( }, { - files: ['src/shared/async.ts', 'src/core/scheduler/scheduler.ts'], + files: ['src/lib/async.ts', 'src/infra/scheduler/scheduler.ts'], rules: { 'no-await-in-loop': 'off' }, }, diff --git a/scripts/migrate.ts b/scripts/migrate.ts index 1c898d9..59f7c34 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { connectDatabase, runMigrations } from '~/db/client'; +import { connectDatabase, runMigrations } from '~/infra/db'; const url = z.url().parse(process.env.DATABASE_URL); const database = connectDatabase(url); diff --git a/scripts/register-commands.ts b/scripts/register-commands.ts index d9d3480..ffadee0 100644 --- a/scripts/register-commands.ts +++ b/scripts/register-commands.ts @@ -1,6 +1,6 @@ import { createRegistry } from '~/app'; -import { loadConfig } from '~/core/config'; -import { registerCommands } from '~/core/discord/registration'; +import { loadConfig } from '~/config'; +import { registerCommands } from '~/infra/discord'; const config = loadConfig(); diff --git a/src/app.ts b/src/app.ts index deec30b..eecaf5a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,13 +1,15 @@ import { Events, type Client } from 'discord.js'; -import type { Config } from '~/core/config'; -import { createClient } from '~/core/discord/client'; -import { createInteractionHandler } from '~/core/discord/router'; -import type { AppContext, Feature } from '~/core/feature'; -import type { Logger } from '~/core/logger'; -import { createAuthorizer } from '~/core/permissions/authorizer'; -import { buildRegistry, type Registry } from '~/core/registry'; -import { createScheduler } from '~/core/scheduler/scheduler'; -import { connectDatabase, runMigrations } from '~/db/client'; +import type { Config } from '~/config'; +import { + createClient, + createInteractionHandler, + createAuthorizer, + buildRegistry, +} from '~/infra/discord'; +import type { AppContext, Feature, Registry } from '~/infra/discord'; +import type { Logger } from '~/infra/logging'; +import { createScheduler } from '~/infra/scheduler'; +import { connectDatabase, runMigrations } from '~/infra/db'; import { announcementsFeature } from '~/features/announcements'; import { birthdaysFeature } from '~/features/birthdays'; import { eventsFeature } from '~/features/events'; diff --git a/src/core/config.ts b/src/config/env.ts similarity index 97% rename from src/core/config.ts rename to src/config/env.ts index 7546b06..1201583 100644 --- a/src/core/config.ts +++ b/src/config/env.ts @@ -1,4 +1,4 @@ -import { isZone } from '~/shared/time'; +import { isZone } from '~/domain'; import { z } from 'zod'; const optional = (schema: T) => diff --git a/src/config/index.ts b/src/config/index.ts new file mode 100644 index 0000000..c1532d6 --- /dev/null +++ b/src/config/index.ts @@ -0,0 +1 @@ +export * from './env'; diff --git a/src/shared/errors.ts b/src/domain/errors.ts similarity index 100% rename from src/shared/errors.ts rename to src/domain/errors.ts diff --git a/src/domain/index.ts b/src/domain/index.ts new file mode 100644 index 0000000..c1bd932 --- /dev/null +++ b/src/domain/index.ts @@ -0,0 +1,2 @@ +export * from './errors'; +export * from './time'; diff --git a/src/shared/time.ts b/src/domain/time.ts similarity index 100% rename from src/shared/time.ts rename to src/domain/time.ts diff --git a/src/features/announcements/index.ts b/src/features/announcements/index.ts index e066718..4da0927 100644 --- a/src/features/announcements/index.ts +++ b/src/features/announcements/index.ts @@ -15,19 +15,26 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, defineJob } from '~/core/define'; -import { asJobError } from '~/core/discord/errors'; +import { + respond, + bySubcommand, + defineJob, + asJobError, + customId, +} from '~/infra/discord'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, -} from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; -import { customId } from '~/core/registry'; -import { PermanentError, UserError } from '~/shared/errors'; -import { discordTime, parseFutureWhen } from '~/shared/time'; +} from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; +import { + PermanentError, + UserError, + discordTime, + parseFutureWhen, +} from '~/domain'; import type { Announcement } from './schema'; import { getAnnouncement, diff --git a/src/features/announcements/service.ts b/src/features/announcements/service.ts index 5de8cf2..09c1b90 100644 --- a/src/features/announcements/service.ts +++ b/src/features/announcements/service.ts @@ -1,6 +1,6 @@ import { and, desc, eq, inArray } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; import { announcements, type Announcement } from './schema'; type Status = Announcement['status']; diff --git a/src/features/birthdays/index.ts b/src/features/birthdays/index.ts index 7c9d485..df68193 100644 --- a/src/features/birthdays/index.ts +++ b/src/features/birthdays/index.ts @@ -8,14 +8,16 @@ import { } from 'discord.js'; import { format } from 'date-fns'; import { z } from 'zod'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, defineJob } from '~/core/define'; -import { isPermanentDiscordError } from '~/core/discord/errors'; -import type { AppContext, CommandInteraction, Feature } from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; -import { sequential } from '~/shared/async'; -import { UserError } from '~/shared/errors'; -import { calendarDay, nextDailyRun } from '~/shared/time'; +import { + respond, + bySubcommand, + defineJob, + isPermanentDiscordError, +} from '~/infra/discord'; +import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; +import { sequential } from '~/lib'; +import { UserError, calendarDay, nextDailyRun } from '~/domain'; import { birthdayVisibility, type Birthday, diff --git a/src/features/birthdays/service.ts b/src/features/birthdays/service.ts index 91acd64..58cfa95 100644 --- a/src/features/birthdays/service.ts +++ b/src/features/birthdays/service.ts @@ -1,8 +1,8 @@ import { and, eq, inArray, isNull, lt, ne, or, sql } from 'drizzle-orm'; import { isLeapYear } from 'date-fns'; -import type { CalendarDay } from '~/shared/time'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; +import type { CalendarDay } from '~/domain'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; import { birthdays, birthdaySettings, diff --git a/src/features/events/index.ts b/src/features/events/index.ts index ffde799..326e7d7 100644 --- a/src/features/events/index.ts +++ b/src/features/events/index.ts @@ -13,24 +13,28 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, defineJob } from '~/core/define'; -import { asJobError, isUnknownObject } from '~/core/discord/errors'; +import { + respond, + bySubcommand, + defineJob, + asJobError, + isUnknownObject, + customId, +} from '~/infra/discord'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, -} from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; -import { customId } from '~/core/registry'; -import { UserError } from '~/shared/errors'; +} from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; import { + UserError, discordTime, parseFutureWhen, parseWhen, requireZone, -} from '~/shared/time'; +} from '~/domain'; import type { Event, RsvpStatus } from './schema'; import { getEvent, diff --git a/src/features/events/service.ts b/src/features/events/service.ts index 6f27585..a23e0e9 100644 --- a/src/features/events/service.ts +++ b/src/features/events/service.ts @@ -1,6 +1,6 @@ import { and, asc, count, eq, gte, ne } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; import { eventRsvps, events, diff --git a/src/features/movies/index.ts b/src/features/movies/index.ts index e657ef5..dbe7c11 100644 --- a/src/features/movies/index.ts +++ b/src/features/movies/index.ts @@ -5,12 +5,10 @@ import { SlashCommandBuilder, type SlashCommandIntegerOption, } from 'discord.js'; -import { respond } from '~/core/discord/router'; -import { bySubcommand } from '~/core/define'; -import type { AppContext, CommandInteraction, Feature } from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; -import { UserError } from '~/shared/errors'; -import { discordTime, parseFutureWhen, parseWhen } from '~/shared/time'; +import { respond, bySubcommand } from '~/infra/discord'; +import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; +import { UserError, discordTime, parseFutureWhen, parseWhen } from '~/domain'; import { createEvent } from '~/features/events'; import { createPoll, getResults, latestPollBySource } from '~/features/polls'; import type { MovieSuggestion } from './schema'; diff --git a/src/features/movies/service.ts b/src/features/movies/service.ts index 5778196..8e6c3ee 100644 --- a/src/features/movies/service.ts +++ b/src/features/movies/service.ts @@ -1,6 +1,6 @@ import { and, asc, desc, eq, isNotNull, isNull, notExists } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; import { movieScreenings, movieSuggestions, diff --git a/src/features/permissions/index.ts b/src/features/permissions/index.ts index c93cef7..d99c56a 100644 --- a/src/features/permissions/index.ts +++ b/src/features/permissions/index.ts @@ -5,18 +5,21 @@ import { type Role, type SlashCommandStringOption, } from 'discord.js'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, deferred } from '~/core/define'; +import { + respond, + bySubcommand, + deferred, + isAdministrator, +} from '~/infra/discord'; import type { AppContext, CommandInteraction, Feature, Permission, PermissionDefinition, -} from '~/core/feature'; -import { isAdministrator } from '~/core/permissions/authorizer'; -import { grant, listGrants, revoke } from '~/core/permissions/store'; -import { UserError } from '~/shared/errors'; +} from '~/infra/discord'; +import { grant, listGrants, revoke } from '~/infra/db'; +import { UserError } from '~/domain'; const managePermission: Permission = 'permissions:manage'; diff --git a/src/features/polls/index.ts b/src/features/polls/index.ts index 9431ede..f1ce2e1 100644 --- a/src/features/polls/index.ts +++ b/src/features/polls/index.ts @@ -13,19 +13,21 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, defineJob } from '~/core/define'; -import { isUnknownObject } from '~/core/discord/errors'; +import { + respond, + bySubcommand, + defineJob, + isUnknownObject, + customId, +} from '~/infra/discord'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, -} from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; -import { customId } from '~/core/registry'; -import { UserError } from '~/shared/errors'; -import { discordTime, parseFutureWhen } from '~/shared/time'; +} from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; +import { UserError, discordTime, parseFutureWhen } from '~/domain'; import type { Poll } from './schema'; import { castVote, diff --git a/src/features/polls/service.ts b/src/features/polls/service.ts index a484a22..eb0a9b4 100644 --- a/src/features/polls/service.ts +++ b/src/features/polls/service.ts @@ -8,8 +8,8 @@ import { inArray, sql, } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; import { pollOptions, polls, diff --git a/src/features/redmine/index.ts b/src/features/redmine/index.ts index 27daf0d..f8d9319 100644 --- a/src/features/redmine/index.ts +++ b/src/features/redmine/index.ts @@ -10,26 +10,29 @@ import { TextInputStyle, type SlashCommandIntegerOption, } from 'discord.js'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, deferred } from '~/core/define'; -import type { Config } from '~/core/config'; +import { respond, bySubcommand, deferred } from '~/infra/discord'; +import type { Config } from '~/config'; import type { AppContext, CommandInteraction, ComponentHandler, Feature, SlashCommand, -} from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; +} from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; import { RedmineClient, RedmineError, type RedmineIssue, type RedmineUser, -} from '~/integrations/redmine/client'; -import { createSecretBox, type SecretBox } from '~/shared/crypto'; -import { UserError } from '~/shared/errors'; -import { addCalendarDays, parseCalendarDay, zonedTime } from '~/shared/time'; +} from '~/infra/redmine'; +import { createSecretBox, type SecretBox } from '~/infra/crypto'; +import { + UserError, + addCalendarDays, + parseCalendarDay, + zonedTime, +} from '~/domain'; import { createReminder } from '~/features/reminders'; import { createNotificationJobs } from './notifications'; import { diff --git a/src/features/redmine/notifications.ts b/src/features/redmine/notifications.ts index 99a1c40..8dfedb5 100644 --- a/src/features/redmine/notifications.ts +++ b/src/features/redmine/notifications.ts @@ -1,18 +1,15 @@ import { MessageFlags } from 'discord.js'; import { z } from 'zod'; -import { defineJob } from '~/core/define'; -import { sequential } from '~/shared/async'; -import type { AppContext } from '~/core/feature'; -import type { - RedmineClient, - RedmineStatus, -} from '~/integrations/redmine/client'; +import { defineJob } from '~/infra/discord'; +import { sequential } from '~/lib'; +import type { AppContext } from '~/infra/discord'; +import type { RedmineClient, RedmineStatus } from '~/infra/redmine'; import { addCalendarDays, calendarDay, formatCalendarDay, nextDailyRun, -} from '~/shared/time'; +} from '~/domain'; import type { RedmineSubscription } from './schema'; import { claimNotification, diff --git a/src/features/redmine/service.ts b/src/features/redmine/service.ts index 29039b6..c937cc9 100644 --- a/src/features/redmine/service.ts +++ b/src/features/redmine/service.ts @@ -1,9 +1,6 @@ import { and, asc, eq, gt } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import type { - RedmineIssue, - RedmineStatus, -} from '~/integrations/redmine/client'; +import type { Db } from '~/infra/db'; +import type { RedmineIssue, RedmineStatus } from '~/infra/redmine'; import { redmineLinks, redmineNotifications, diff --git a/src/features/reminders/index.ts b/src/features/reminders/index.ts index 6e688bc..a39b74c 100644 --- a/src/features/reminders/index.ts +++ b/src/features/reminders/index.ts @@ -5,19 +5,18 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, defineJob } from '~/core/define'; -import { asJobError } from '~/core/discord/errors'; -import type { AppContext, CommandInteraction, Feature } from '~/core/feature'; -import { getGuildTimezone } from '~/core/guild-settings'; -import { PermanentError, UserError } from '~/shared/errors'; +import { respond, bySubcommand, defineJob, asJobError } from '~/infra/discord'; +import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; +import { getGuildTimezone } from '~/infra/db'; import { + PermanentError, + UserError, discordTime, nextFutureOccurrence, parseFutureWhen, recurrences, requireZone, -} from '~/shared/time'; +} from '~/domain'; import type { Reminder } from './schema'; import { getReminder, diff --git a/src/features/reminders/service.ts b/src/features/reminders/service.ts index 65e5752..0f93349 100644 --- a/src/features/reminders/service.ts +++ b/src/features/reminders/service.ts @@ -1,7 +1,7 @@ import { and, asc, count, eq } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; -import type { Recurrence } from '~/shared/time'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; +import type { Recurrence } from '~/domain'; import { reminders, type Reminder } from './schema'; export const maxActivePerUser = 25; diff --git a/src/features/roles/guards.ts b/src/features/roles/guards.ts index b41b8ff..96ee20c 100644 --- a/src/features/roles/guards.ts +++ b/src/features/roles/guards.ts @@ -1,5 +1,5 @@ import { PermissionFlagsBits, type GuildMember, type Role } from 'discord.js'; -import { UserError } from '~/shared/errors'; +import { UserError } from '~/domain'; const moderatorPermissions = [ PermissionFlagsBits.Administrator, diff --git a/src/features/roles/index.ts b/src/features/roles/index.ts index 1d1dae0..5b08a1c 100644 --- a/src/features/roles/index.ts +++ b/src/features/roles/index.ts @@ -6,10 +6,18 @@ import { type GuildMember, type Role, } from 'discord.js'; -import { respond } from '~/core/discord/router'; -import { bySubcommand, deferred, defineListener } from '~/core/define'; -import type { CommandInteraction, Feature, SlashCommand } from '~/core/feature'; -import { UserError } from '~/shared/errors'; +import { + respond, + bySubcommand, + deferred, + defineListener, +} from '~/infra/discord'; +import type { + CommandInteraction, + Feature, + SlashCommand, +} from '~/infra/discord'; +import { UserError } from '~/domain'; import { requireAbove, requireEditable, requireSelfAssignable } from './guards'; import { handleReaction, syncLegacyPanel } from './legacy'; import { panelComponents, publishPanel } from './panels'; diff --git a/src/features/roles/legacy.ts b/src/features/roles/legacy.ts index 164bd87..298c6f7 100644 --- a/src/features/roles/legacy.ts +++ b/src/features/roles/legacy.ts @@ -7,8 +7,8 @@ import { type TextChannel, type User, } from 'discord.js'; -import type { AppContext } from '~/core/feature'; -import { sequential } from '~/shared/async'; +import type { AppContext } from '~/infra/discord'; +import { sequential } from '~/lib'; import { createPanel, findReactionPanel, diff --git a/src/features/roles/panels.ts b/src/features/roles/panels.ts index de6eb0b..22abec8 100644 --- a/src/features/roles/panels.ts +++ b/src/features/roles/panels.ts @@ -8,9 +8,9 @@ import { StringSelectMenuBuilder, type BaseMessageOptions, } from 'discord.js'; -import { customId } from '~/core/registry'; -import type { AppContext, ComponentHandler } from '~/core/feature'; -import { UserError } from '~/shared/errors'; +import { customId } from '~/infra/discord'; +import type { AppContext, ComponentHandler } from '~/infra/discord'; +import { UserError } from '~/domain'; import { selfAssignProblem } from './guards'; import { requirePanel, setPanelMessage, type Panel } from './service'; diff --git a/src/features/roles/service.ts b/src/features/roles/service.ts index 81de264..5c5aa23 100644 --- a/src/features/roles/service.ts +++ b/src/features/roles/service.ts @@ -1,6 +1,6 @@ import { and, asc, count, eq, max } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; import { rolePanelRoles, rolePanels } from './schema'; export const maxPanelRoles = 25; diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts index b39f870..09fa004 100644 --- a/src/features/settings/index.ts +++ b/src/features/settings/index.ts @@ -3,10 +3,10 @@ import { MessageFlags, SlashCommandBuilder, } from 'discord.js'; -import { bySubcommand } from '~/core/define'; -import type { Feature } from '~/core/feature'; -import { getGuildTimezone, setGuildTimezone } from '~/core/guild-settings'; -import { requireZone } from '~/shared/time'; +import { bySubcommand } from '~/infra/discord'; +import type { Feature } from '~/infra/discord'; +import { getGuildTimezone, setGuildTimezone } from '~/infra/db'; +import { requireZone } from '~/domain'; const data = new SlashCommandBuilder() .setName('settings') diff --git a/src/index.ts b/src/index.ts index be5bb6b..e8fe9f6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ -import { startApp } from './app'; -import { loadConfig } from '~/core/config'; -import { createLogger } from '~/core/logger'; +import { startApp } from '~/app'; +import { loadConfig } from '~/config'; +import { createLogger } from '~/infra/logging'; let config: ReturnType; diff --git a/src/infra/crypto/index.ts b/src/infra/crypto/index.ts new file mode 100644 index 0000000..1157635 --- /dev/null +++ b/src/infra/crypto/index.ts @@ -0,0 +1 @@ +export * from './secret-box'; diff --git a/src/shared/crypto.ts b/src/infra/crypto/secret-box.ts similarity index 100% rename from src/shared/crypto.ts rename to src/infra/crypto/secret-box.ts diff --git a/src/db/client.ts b/src/infra/db/client.ts similarity index 94% rename from src/db/client.ts rename to src/infra/db/client.ts index e0c962f..62e09d2 100644 --- a/src/db/client.ts +++ b/src/infra/db/client.ts @@ -2,7 +2,7 @@ import { resolve } from 'node:path'; import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { migrate } from 'drizzle-orm/postgres-js/migrator'; import postgres from 'postgres'; -import { ignore } from '~/shared/errors'; +import { ignore } from '~/domain'; export type Db = PostgresJsDatabase; diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts new file mode 100644 index 0000000..f607b5f --- /dev/null +++ b/src/infra/db/index.ts @@ -0,0 +1,6 @@ +export * from './client'; +export * from './jobs/model'; +export * from './jobs/repo'; +export * from './permissions/model'; +export * from './permissions/repo'; +export * from './settings/repo'; diff --git a/src/core/scheduler/schema.ts b/src/infra/db/jobs/model.ts similarity index 100% rename from src/core/scheduler/schema.ts rename to src/infra/db/jobs/model.ts diff --git a/src/core/scheduler/store.ts b/src/infra/db/jobs/repo.ts similarity index 96% rename from src/core/scheduler/store.ts rename to src/infra/db/jobs/repo.ts index f65a553..91364c2 100644 --- a/src/core/scheduler/store.ts +++ b/src/infra/db/jobs/repo.ts @@ -1,6 +1,6 @@ import { and, asc, eq, inArray, lte, lt, or, sql } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { scheduledJobs, type JobRow } from './schema'; +import type { Db } from '../client'; +import { scheduledJobs, type JobRow } from './model'; export type NewJob = { type: string; diff --git a/src/core/permissions/schema.ts b/src/infra/db/permissions/model.ts similarity index 100% rename from src/core/permissions/schema.ts rename to src/infra/db/permissions/model.ts diff --git a/src/core/permissions/store.ts b/src/infra/db/permissions/repo.ts similarity index 95% rename from src/core/permissions/store.ts rename to src/infra/db/permissions/repo.ts index 2887361..6b009d2 100644 --- a/src/core/permissions/store.ts +++ b/src/infra/db/permissions/repo.ts @@ -1,6 +1,6 @@ import { and, eq, inArray } from 'drizzle-orm'; -import type { Db } from '~/db/client'; -import { rolePermissions } from './schema'; +import type { Db } from '../client'; +import { rolePermissions } from './model'; export async function hasGrant( db: Db, diff --git a/src/core/guild-settings.ts b/src/infra/db/settings/repo.ts similarity index 95% rename from src/core/guild-settings.ts rename to src/infra/db/settings/repo.ts index 423f72f..6c2cadb 100644 --- a/src/core/guild-settings.ts +++ b/src/infra/db/settings/repo.ts @@ -1,6 +1,6 @@ import { eq } from 'drizzle-orm'; import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -import type { Db } from '~/db/client'; +import type { Db } from '../client'; export const guildSettings = pgTable('guild_settings', { guildId: text('guild_id').primaryKey(), diff --git a/src/core/permissions/authorizer.ts b/src/infra/discord/authorizer.ts similarity index 85% rename from src/core/permissions/authorizer.ts rename to src/infra/discord/authorizer.ts index 667b8eb..1cba613 100644 --- a/src/core/permissions/authorizer.ts +++ b/src/infra/discord/authorizer.ts @@ -1,8 +1,8 @@ import { PermissionFlagsBits, type GuildMember } from 'discord.js'; -import type { Db } from '~/db/client'; -import { UserError } from '~/shared/errors'; -import type { Authorizer, Permission } from '~/core/feature'; -import { hasGrant } from './store'; +import type { Db } from '~/infra/db'; +import { UserError } from '~/domain'; +import type { Authorizer, Permission } from './module'; +import { hasGrant } from '~/infra/db'; export function isAdministrator(member: GuildMember): boolean { return member.permissions.has(PermissionFlagsBits.Administrator); diff --git a/src/core/discord/client.ts b/src/infra/discord/client.ts similarity index 100% rename from src/core/discord/client.ts rename to src/infra/discord/client.ts diff --git a/src/core/define.ts b/src/infra/discord/define.ts similarity index 93% rename from src/core/define.ts rename to src/infra/discord/define.ts index 34eff27..6900352 100644 --- a/src/core/define.ts +++ b/src/infra/discord/define.ts @@ -1,7 +1,7 @@ import { MessageFlags, type ClientEvents } from 'discord.js'; import type { z } from 'zod'; -import { PermanentError } from '~/shared/errors'; -import { subcommandPath } from '~/core/discord/router'; +import { PermanentError } from '~/domain'; +import { subcommandPath } from './router'; import type { AppContext, CommandInteraction, @@ -10,7 +10,7 @@ import type { JobInfo, JobOutcome, SlashCommand, -} from './feature'; +} from './module'; export function defineJob(definition: { type: string; diff --git a/src/core/discord/errors.ts b/src/infra/discord/errors.ts similarity index 95% rename from src/core/discord/errors.ts rename to src/infra/discord/errors.ts index 9a6f502..efe3ff5 100644 --- a/src/core/discord/errors.ts +++ b/src/infra/discord/errors.ts @@ -1,5 +1,5 @@ import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; -import { PermanentError } from '~/shared/errors'; +import { PermanentError } from '~/domain'; const permanentCodes = new Set([ RESTJSONErrorCodes.UnknownChannel, diff --git a/src/infra/discord/index.ts b/src/infra/discord/index.ts new file mode 100644 index 0000000..d233f22 --- /dev/null +++ b/src/infra/discord/index.ts @@ -0,0 +1,8 @@ +export * from './client'; +export * from './router'; +export * from './errors'; +export * from './registration'; +export type * from './module'; +export * from './define'; +export * from './registry'; +export * from './authorizer'; diff --git a/src/core/feature.ts b/src/infra/discord/module.ts similarity index 95% rename from src/core/feature.ts rename to src/infra/discord/module.ts index c5e41d9..e1a0a2f 100644 --- a/src/core/feature.ts +++ b/src/infra/discord/module.ts @@ -9,9 +9,9 @@ import type { ModalSubmitInteraction, RESTPostAPIChatInputApplicationCommandsJSONBody, } from 'discord.js'; -import type { Db } from '~/db/client'; -import type { Config } from './config'; -import type { Logger } from './logger'; +import type { Db } from '~/infra/db'; +import type { Config } from '~/config'; +import type { Logger } from '~/infra/logging'; export type Permission = `${string}:${string}`; diff --git a/src/core/discord/registration.ts b/src/infra/discord/registration.ts similarity index 92% rename from src/core/discord/registration.ts rename to src/infra/discord/registration.ts index adfe38a..2e6a514 100644 --- a/src/core/discord/registration.ts +++ b/src/infra/discord/registration.ts @@ -1,5 +1,5 @@ import { REST, Routes } from 'discord.js'; -import type { Registry } from '~/core/registry'; +import type { Registry } from './registry'; export async function registerCommands( registry: Registry, diff --git a/src/core/registry.ts b/src/infra/discord/registry.ts similarity index 99% rename from src/core/registry.ts rename to src/infra/discord/registry.ts index bd9e155..efcec4a 100644 --- a/src/core/registry.ts +++ b/src/infra/discord/registry.ts @@ -5,7 +5,7 @@ import type { Permission, PermissionDefinition, SlashCommand, -} from './feature'; +} from './module'; export type Registry = { features: readonly Feature[]; diff --git a/src/core/discord/router.ts b/src/infra/discord/router.ts similarity index 96% rename from src/core/discord/router.ts rename to src/infra/discord/router.ts index 22df55d..c29d6b3 100644 --- a/src/core/discord/router.ts +++ b/src/infra/discord/router.ts @@ -5,13 +5,13 @@ import { type BaseMessageOptions, type Interaction, } from 'discord.js'; -import { ignore, UserError } from '~/shared/errors'; +import { ignore, UserError } from '~/domain'; import type { AppContext, CommandInteraction, ComponentInteraction, -} from '~/core/feature'; -import { parseCustomId, type Registry } from '~/core/registry'; +} from './module'; +import { parseCustomId, type Registry } from './registry'; type Repliable = CommandInteraction | ComponentInteraction; diff --git a/src/infra/logging/index.ts b/src/infra/logging/index.ts new file mode 100644 index 0000000..1ff09ef --- /dev/null +++ b/src/infra/logging/index.ts @@ -0,0 +1 @@ +export * from './logger'; diff --git a/src/core/logger.ts b/src/infra/logging/logger.ts similarity index 100% rename from src/core/logger.ts rename to src/infra/logging/logger.ts diff --git a/src/integrations/redmine/client.ts b/src/infra/redmine/client.ts similarity index 100% rename from src/integrations/redmine/client.ts rename to src/infra/redmine/client.ts diff --git a/src/infra/redmine/index.ts b/src/infra/redmine/index.ts new file mode 100644 index 0000000..4f1cce4 --- /dev/null +++ b/src/infra/redmine/index.ts @@ -0,0 +1 @@ +export * from './client'; diff --git a/src/infra/scheduler/index.ts b/src/infra/scheduler/index.ts new file mode 100644 index 0000000..3521c5c --- /dev/null +++ b/src/infra/scheduler/index.ts @@ -0,0 +1 @@ +export * from './scheduler'; diff --git a/src/core/scheduler/scheduler.ts b/src/infra/scheduler/scheduler.ts similarity index 91% rename from src/core/scheduler/scheduler.ts rename to src/infra/scheduler/scheduler.ts index 10cbb26..dc5d010 100644 --- a/src/core/scheduler/scheduler.ts +++ b/src/infra/scheduler/scheduler.ts @@ -1,10 +1,9 @@ import { setTimeout as sleep } from 'node:timers/promises'; -import type { Db } from '~/db/client'; -import { PermanentError } from '~/shared/errors'; -import type { AppContext, Job, Scheduler } from '~/core/feature'; -import type { Logger } from '~/core/logger'; -import type { JobRow } from './schema'; -import { cancelJob, claimDueJobs, finishJob, upsertJob } from './store'; +import type { Db, JobRow } from '~/infra/db'; +import { PermanentError } from '~/domain'; +import type { AppContext, Job, Scheduler } from '~/infra/discord'; +import type { Logger } from '~/infra/logging'; +import { cancelJob, claimDueJobs, finishJob, upsertJob } from '~/infra/db'; export type SchedulerOptions = { pollIntervalMs?: number; diff --git a/src/shared/async.ts b/src/lib/async.ts similarity index 100% rename from src/shared/async.ts rename to src/lib/async.ts diff --git a/src/lib/index.ts b/src/lib/index.ts new file mode 100644 index 0000000..780df27 --- /dev/null +++ b/src/lib/index.ts @@ -0,0 +1 @@ +export * from './async'; diff --git a/tests/app.test.ts b/tests/app.test.ts index 2c300ac..e40d567 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -4,7 +4,7 @@ import type { } from 'discord.js'; import { describe, expect, it } from 'vitest'; import { createRegistry } from '~/app'; -import type { Config } from '~/core/config'; +import type { Config } from '~/config'; const config = { DEFAULT_TIMEZONE: 'Europe/Tallinn' } as Config; diff --git a/tests/core/discord/router.test.ts b/tests/core/discord/router.test.ts index c7b8fd6..221c877 100644 --- a/tests/core/discord/router.test.ts +++ b/tests/core/discord/router.test.ts @@ -1,9 +1,8 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; -import { UserError } from '~/shared/errors'; -import type { AppContext, Feature } from '~/core/feature'; -import { buildRegistry } from '~/core/registry'; -import { createInteractionHandler } from '~/core/discord/router'; +import { UserError } from '~/domain'; +import type { AppContext, Feature } from '~/infra/discord'; +import { buildRegistry, createInteractionHandler } from '~/infra/discord'; function context(allowed: boolean) { const require = vi.fn(async () => { diff --git a/tests/core/permissions/authorizer.test.ts b/tests/core/permissions/authorizer.test.ts index 156eff9..37cc455 100644 --- a/tests/core/permissions/authorizer.test.ts +++ b/tests/core/permissions/authorizer.test.ts @@ -1,9 +1,9 @@ import type { GuildMember } from 'discord.js'; import { beforeAll, describe, expect, it } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import { UserError } from '~/shared/errors'; -import { createAuthorizer } from '~/core/permissions/authorizer'; -import { grant, listGrants, revoke } from '~/core/permissions/store'; +import { UserError } from '~/domain'; +import { createAuthorizer } from '~/infra/discord'; +import { grant, listGrants, revoke } from '~/infra/db'; function member( guildId: string, diff --git a/tests/core/registry.test.ts b/tests/core/registry.test.ts index 67616e3..0c749d2 100644 --- a/tests/core/registry.test.ts +++ b/tests/core/registry.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import type { Feature } from '~/core/feature'; -import { buildRegistry, customId, parseCustomId } from '~/core/registry'; +import type { Feature } from '~/infra/discord'; +import { buildRegistry, customId, parseCustomId } from '~/infra/discord'; const noop = async () => undefined; const noopJob = async () => null; diff --git a/tests/core/scheduler/scheduler.test.ts b/tests/core/scheduler/scheduler.test.ts index 9989b4b..1386294 100644 --- a/tests/core/scheduler/scheduler.test.ts +++ b/tests/core/scheduler/scheduler.test.ts @@ -3,12 +3,11 @@ import { pino } from 'pino'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod'; import { noDatabase, testDb } from '../../db'; -import { PermanentError } from '~/shared/errors'; -import { defineJob } from '~/core/define'; -import type { AppContext } from '~/core/feature'; -import { createScheduler, retryDelayMs } from '~/core/scheduler/scheduler'; -import { scheduledJobs } from '~/core/scheduler/schema'; -import { claimDueJobs } from '~/core/scheduler/store'; +import { PermanentError } from '~/domain'; +import { defineJob } from '~/infra/discord'; +import type { AppContext } from '~/infra/discord'; +import { createScheduler, retryDelayMs } from '~/infra/scheduler'; +import { scheduledJobs, claimDueJobs } from '~/infra/db'; const log = pino({ level: 'silent' }); diff --git a/tests/db.ts b/tests/db.ts index 33e0df0..b693127 100644 --- a/tests/db.ts +++ b/tests/db.ts @@ -1,5 +1,5 @@ import { afterAll } from 'vitest'; -import { connectDatabase, type Db } from '~/db/client'; +import { connectDatabase, type Db } from '~/infra/db'; const url = process.env.TEST_DATABASE_URL; diff --git a/tests/features/announcements/announcements.test.ts b/tests/features/announcements/announcements.test.ts index 8e18096..4d11ffc 100644 --- a/tests/features/announcements/announcements.test.ts +++ b/tests/features/announcements/announcements.test.ts @@ -1,7 +1,7 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; +import type { AppContext } from '~/infra/discord'; import { render } from '~/features/announcements'; import type { Announcement } from '~/features/announcements/schema'; import { diff --git a/tests/features/birthdays/birthdays.test.ts b/tests/features/birthdays/birthdays.test.ts index bb53e4f..cef3af4 100644 --- a/tests/features/birthdays/birthdays.test.ts +++ b/tests/features/birthdays/birthdays.test.ts @@ -1,8 +1,8 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; -import { calendarDay, nextDailyRun } from '~/shared/time'; +import type { AppContext } from '~/infra/discord'; +import { calendarDay, nextDailyRun } from '~/domain'; import { dailyJob } from '~/features/birthdays'; import { celebratedOn, diff --git a/tests/features/events/events.test.ts b/tests/features/events/events.test.ts index 9f8c342..9137444 100644 --- a/tests/features/events/events.test.ts +++ b/tests/features/events/events.test.ts @@ -1,8 +1,8 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; -import { UserError } from '~/shared/errors'; +import type { AppContext } from '~/infra/discord'; +import { UserError } from '~/domain'; import { createEvent, remindJob } from '~/features/events'; import { insertEvent, diff --git a/tests/features/movies/movies.test.ts b/tests/features/movies/movies.test.ts index f33a014..ffdc3d6 100644 --- a/tests/features/movies/movies.test.ts +++ b/tests/features/movies/movies.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; +import type { AppContext } from '~/infra/discord'; import { castVote, finishPoll, insertPoll } from '~/features/polls/service'; import { pickMovie } from '~/features/movies'; import { diff --git a/tests/features/permissions/permissions.test.ts b/tests/features/permissions/permissions.test.ts index 71b4f6e..0fb9c2f 100644 --- a/tests/features/permissions/permissions.test.ts +++ b/tests/features/permissions/permissions.test.ts @@ -1,6 +1,6 @@ import type { GuildMember, Role } from 'discord.js'; import { describe, expect, it } from 'vitest'; -import type { Authorizer } from '~/core/feature'; +import type { Authorizer } from '~/infra/discord'; import { checkDelegation } from '~/features/permissions'; const role = {} as Role; diff --git a/tests/features/polls/polls.test.ts b/tests/features/polls/polls.test.ts index 4983d47..5973399 100644 --- a/tests/features/polls/polls.test.ts +++ b/tests/features/polls/polls.test.ts @@ -1,8 +1,8 @@ import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; -import { UserError } from '~/shared/errors'; +import type { AppContext } from '~/infra/discord'; +import { UserError } from '~/domain'; import { closeJob, renderPoll } from '~/features/polls'; import { castVote, diff --git a/tests/features/redmine/redmine.test.ts b/tests/features/redmine/redmine.test.ts index 8680769..7e206c4 100644 --- a/tests/features/redmine/redmine.test.ts +++ b/tests/features/redmine/redmine.test.ts @@ -2,12 +2,9 @@ import { randomBytes } from 'node:crypto'; import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { Config } from '~/core/config'; -import type { AppContext } from '~/core/feature'; -import type { - RedmineClient, - RedmineIssue, -} from '~/integrations/redmine/client'; +import type { Config } from '~/config'; +import type { AppContext } from '~/infra/discord'; +import type { RedmineClient, RedmineIssue } from '~/infra/redmine'; import { createRedmineFeature } from '~/features/redmine'; import { createNotificationJobs } from '~/features/redmine/notifications'; import { diff --git a/tests/features/reminders/reminders.test.ts b/tests/features/reminders/reminders.test.ts index 10aaa34..34095de 100644 --- a/tests/features/reminders/reminders.test.ts +++ b/tests/features/reminders/reminders.test.ts @@ -2,8 +2,8 @@ import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; -import { PermanentError, UserError } from '~/shared/errors'; +import type { AppContext } from '~/infra/discord'; +import { PermanentError, UserError } from '~/domain'; import { createReminder, deliverJob } from '~/features/reminders'; import { getReminder, diff --git a/tests/features/roles/roles.test.ts b/tests/features/roles/roles.test.ts index 1ce6fbd..2d3dbfd 100644 --- a/tests/features/roles/roles.test.ts +++ b/tests/features/roles/roles.test.ts @@ -6,7 +6,7 @@ import { import { pino } from 'pino'; import { beforeAll, describe, expect, it, vi } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/core/feature'; +import type { AppContext } from '~/infra/discord'; import { requireAbove, selfAssignProblem } from '~/features/roles/guards'; import { handleReaction, diff --git a/tests/global-setup.ts b/tests/global-setup.ts index 56e57b8..7b9f283 100644 --- a/tests/global-setup.ts +++ b/tests/global-setup.ts @@ -1,5 +1,5 @@ import postgres from 'postgres'; -import { connectDatabase, runMigrations } from '~/db/client'; +import { connectDatabase, runMigrations } from '~/infra/db'; export default async function setup(): Promise { const url = process.env.TEST_DATABASE_URL; diff --git a/tests/integrations/redmine/client.test.ts b/tests/integrations/redmine/client.test.ts index 03a3a71..44cb650 100644 --- a/tests/integrations/redmine/client.test.ts +++ b/tests/integrations/redmine/client.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest'; -import { RedmineClient, RedmineError } from '~/integrations/redmine/client'; +import { RedmineClient, RedmineError } from '~/infra/redmine'; const issue = { id: 7, diff --git a/tests/shared/crypto.test.ts b/tests/shared/crypto.test.ts index 0300d62..4523cd2 100644 --- a/tests/shared/crypto.test.ts +++ b/tests/shared/crypto.test.ts @@ -1,6 +1,6 @@ import { randomBytes } from 'node:crypto'; import { describe, expect, it } from 'vitest'; -import { createSecretBox } from '~/shared/crypto'; +import { createSecretBox } from '~/infra/crypto'; describe('createSecretBox', () => { const box = createSecretBox(randomBytes(32).toString('base64')); diff --git a/tests/shared/time.test.ts b/tests/shared/time.test.ts index 6db9270..b25785a 100644 --- a/tests/shared/time.test.ts +++ b/tests/shared/time.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { UserError } from '~/shared/errors'; import { + UserError, nextFutureOccurrence, nextOccurrence, parseFutureWhen, parseWhen, -} from '~/shared/time'; +} from '~/domain'; const zone = 'Europe/Tallinn'; const now = new Date('2026-03-10T10:00:00Z'); From 18b40041eb0b506933407e754a86847b203ba344 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:29:23 +0200 Subject: [PATCH 021/199] feat(core): domain model, ports and Discord adapters for messaging and roles --- src/core/ports/authorization.ts | 25 ++++ src/core/ports/chat.ts | 72 ++++++++++ src/core/ports/clock.ts | 3 + src/core/ports/index.ts | 6 + src/core/ports/logger.ts | 9 ++ src/core/ports/scheduler.ts | 25 ++++ src/core/ports/secrets.ts | 4 + src/domain/actor.ts | 9 ++ src/domain/index.ts | 4 + src/domain/message.ts | 59 ++++++++ src/domain/permission.ts | 40 ++++++ src/domain/role.ts | 62 ++++++++ src/infra/discord/actor.ts | 43 ++++++ src/infra/discord/adapters.ts | 242 ++++++++++++++++++++++++++++++++ src/infra/discord/index.ts | 3 + src/infra/discord/render.ts | 98 +++++++++++++ 16 files changed, 704 insertions(+) create mode 100644 src/core/ports/authorization.ts create mode 100644 src/core/ports/chat.ts create mode 100644 src/core/ports/clock.ts create mode 100644 src/core/ports/index.ts create mode 100644 src/core/ports/logger.ts create mode 100644 src/core/ports/scheduler.ts create mode 100644 src/core/ports/secrets.ts create mode 100644 src/domain/actor.ts create mode 100644 src/domain/message.ts create mode 100644 src/domain/permission.ts create mode 100644 src/domain/role.ts create mode 100644 src/infra/discord/actor.ts create mode 100644 src/infra/discord/adapters.ts create mode 100644 src/infra/discord/render.ts diff --git a/src/core/ports/authorization.ts b/src/core/ports/authorization.ts new file mode 100644 index 0000000..97b42df --- /dev/null +++ b/src/core/ports/authorization.ts @@ -0,0 +1,25 @@ +import type { Actor, Permission } from '~/domain'; + +export type Grant = { roleId: string; permission: string }; + +export type GrantChange = { + guildId: string; + roleId: string; + permission: Permission; +}; + +export type GrantRepository = { + holds: ( + guildId: string, + roleIds: readonly string[], + permission: Permission, + ) => Promise; + grant: (change: GrantChange & { grantedBy: string }) => Promise; + revoke: (change: GrantChange) => Promise; + list: (guildId: string, roleId?: string) => Promise; +}; + +export type Authorizer = { + can: (actor: Actor, permission: Permission) => Promise; + require: (actor: Actor, permission: Permission) => Promise; +}; diff --git a/src/core/ports/chat.ts b/src/core/ports/chat.ts new file mode 100644 index 0000000..930b837 --- /dev/null +++ b/src/core/ports/chat.ts @@ -0,0 +1,72 @@ +import type { Actor, Message, RoleInfo } from '~/domain'; + +export type Sent = { channelId: string; messageId: string }; + +export type ChannelInfo = { + id: string; + name: string; + kind: 'text' | 'announcement'; +}; + +export type Messenger = { + send: (channelId: string, message: Message) => Promise; + edit: ( + channelId: string, + messageId: string, + message: Message, + ) => Promise; + remove: (channelId: string, messageId: string) => Promise; + direct: (userId: string, message: Message) => Promise; + exists: (channelId: string, messageId: string) => Promise; + findOwn: (channelId: string, content: string) => Promise; + ownReactions: (channelId: string, messageId: string) => Promise; + react: (channelId: string, messageId: string, emoji: string) => Promise; +}; + +export type NewRole = { name: string; color?: number; mentionable: boolean }; + +export type Directory = { + guildOf: (channelId: string) => Promise; + channels: (guildId: string) => Promise; + roles: (guildId: string) => Promise; + role: (guildId: string, roleId: string) => Promise; + member: (guildId: string, userId: string) => Promise; + canPost: (actor: Actor, channelId: string) => Promise; + addRoles: ( + member: { guildId: string; userId: string }, + roleIds: readonly string[], + reason: string, + ) => Promise; + removeRoles: ( + member: { guildId: string; userId: string }, + roleIds: readonly string[], + reason: string, + ) => Promise; + createRole: ( + guildId: string, + role: NewRole, + reason: string, + ) => Promise; + deleteRole: ( + guildId: string, + roleId: string, + reason: string, + ) => Promise; +}; + +export type CalendarEvent = { + title: string; + description: string; + location: string; + startsAt: Date; + endsAt: Date; +}; + +export type Calendar = { + upsert: ( + guildId: string, + id: string | null, + event: CalendarEvent, + ) => Promise; + remove: (guildId: string, id: string) => Promise; +}; diff --git a/src/core/ports/clock.ts b/src/core/ports/clock.ts new file mode 100644 index 0000000..708fa1a --- /dev/null +++ b/src/core/ports/clock.ts @@ -0,0 +1,3 @@ +export type Clock = { now: () => Date }; + +export const systemClock: Clock = { now: () => new Date() }; diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts new file mode 100644 index 0000000..d2516f8 --- /dev/null +++ b/src/core/ports/index.ts @@ -0,0 +1,6 @@ +export type * from './authorization'; +export type * from './chat'; +export * from './clock'; +export type * from './logger'; +export type * from './scheduler'; +export type * from './secrets'; diff --git a/src/core/ports/logger.ts b/src/core/ports/logger.ts new file mode 100644 index 0000000..718a795 --- /dev/null +++ b/src/core/ports/logger.ts @@ -0,0 +1,9 @@ +type Log = (details: object, message: string) => void; + +export type Logger = { + debug: Log; + info: Log; + warn: Log; + error: Log; + child: (bindings: object) => Logger; +}; diff --git a/src/core/ports/scheduler.ts b/src/core/ports/scheduler.ts new file mode 100644 index 0000000..b6a389f --- /dev/null +++ b/src/core/ports/scheduler.ts @@ -0,0 +1,25 @@ +export type JobInfo = { id: number; runAt: Date; attempt: number }; + +export type JobOutcome = null | { rescheduleAt: Date }; + +export type Job

= { + type: string; + maxAttempts: number; + run: (raw: unknown, info: JobInfo) => Promise; + payloadType?: P; +}; + +export type ScheduleOptions = { + runAt: Date; + key?: string; + maxAttempts?: number; +}; + +export type Scheduler = { + schedule:

( + job: Job

, + payload: P, + options: ScheduleOptions, + ) => Promise; + cancel: (key: string) => Promise; +}; diff --git a/src/core/ports/secrets.ts b/src/core/ports/secrets.ts new file mode 100644 index 0000000..7f75e88 --- /dev/null +++ b/src/core/ports/secrets.ts @@ -0,0 +1,4 @@ +export type SecretBox = { + encrypt: (plaintext: string) => string; + decrypt: (sealed: string) => string; +}; diff --git a/src/domain/actor.ts b/src/domain/actor.ts new file mode 100644 index 0000000..96677e4 --- /dev/null +++ b/src/domain/actor.ts @@ -0,0 +1,9 @@ +export type Actor = { + guildId: string; + userId: string; + roleIds: readonly string[]; + administrator: boolean; + owner: boolean; + mentionEveryone: boolean; + highestRolePosition: number; +}; diff --git a/src/domain/index.ts b/src/domain/index.ts index c1bd932..24fcec3 100644 --- a/src/domain/index.ts +++ b/src/domain/index.ts @@ -1,2 +1,6 @@ +export type * from './actor'; export * from './errors'; +export * from './message'; +export * from './permission'; +export * from './role'; export * from './time'; diff --git a/src/domain/message.ts b/src/domain/message.ts new file mode 100644 index 0000000..d072790 --- /dev/null +++ b/src/domain/message.ts @@ -0,0 +1,59 @@ +export type Mentions = { + users?: readonly string[]; + roles?: readonly string[]; + everyone?: boolean; +}; + +export type EmbedField = { name: string; value: string; inline?: boolean }; + +export type Embed = { + title?: string; + description?: string; + url?: string; + color?: number; + fields?: readonly EmbedField[]; + footer?: string; +}; + +export type ButtonStyle = 'primary' | 'secondary' | 'success' | 'danger'; + +export type Control = + | { kind: 'button'; id: string; label: string; style: ButtonStyle } + | { + kind: 'select'; + id: string; + placeholder: string; + min: number; + max: number; + options: ReadonlyArray<{ + label: string; + value: string; + default?: boolean; + }>; + }; + +export type Message = { + content?: string; + embeds?: readonly Embed[]; + mentions?: Mentions; + controls?: ReadonlyArray; + suppressEmbeds?: boolean; +}; + +export const maxContentLength = 2000; + +export const userMention = (id: string) => `<@${id}>`; + +export const roleMention = (id: string) => `<@&${id}>`; + +export const channelMention = (id: string) => `<#${id}>`; + +export const controlId = (prefix: string, ...args: Array) => { + const id = [prefix, ...args].join(':'); + + if (id.length > 100) { + throw new Error(`Control ID exceeds 100 characters: ${id}`); + } + + return id; +}; diff --git a/src/domain/permission.ts b/src/domain/permission.ts new file mode 100644 index 0000000..a25c6d4 --- /dev/null +++ b/src/domain/permission.ts @@ -0,0 +1,40 @@ +import type { Actor } from './actor'; +import { UserError } from './errors'; + +export type Permission = `${string}:${string}`; + +export type PermissionDefinition = { + id: Permission; + description: string; +}; + +export const managePermissions: Permission = 'permissions:manage'; + +export type Delegation = { + actor: Actor; + rolePosition: number; + permission: Permission; + actorHolds: boolean; +}; + +export function checkDelegation(delegation: Delegation): void { + const { actor, rolePosition, permission, actorHolds } = delegation; + + if (actor.administrator) { + return; + } + + if (permission === managePermissions) { + throw new UserError( + 'Only administrators can delegate permission management.', + ); + } + + if (actor.highestRolePosition <= rolePosition) { + throw new UserError('That role is not below your highest role.'); + } + + if (!actorHolds) { + throw new UserError('You can only grant permissions you hold yourself.'); + } +} diff --git a/src/domain/role.ts b/src/domain/role.ts new file mode 100644 index 0000000..577621e --- /dev/null +++ b/src/domain/role.ts @@ -0,0 +1,62 @@ +import type { Actor } from './actor'; +import { UserError } from './errors'; + +export type RoleInfo = { + id: string; + name: string; + position: number; + everyone: boolean; + managed: boolean; + mentionable: boolean; + moderator: boolean; + administrator: boolean; + botCanAssign: boolean; +}; + +export function selfAssignProblem(role: RoleInfo): string | undefined { + if (role.everyone) { + return 'is the @everyone role'; + } + + if (role.managed) { + return 'is managed by an integration'; + } + + if (role.moderator) { + return 'grants moderator permissions'; + } + + if (!role.botCanAssign) { + return 'is above my highest role, or I lack Manage Roles'; + } + + return undefined; +} + +export function requireSelfAssignable(role: RoleInfo): void { + const problem = selfAssignProblem(role); + + if (problem !== undefined) { + throw new UserError(`${role.name} cannot be self-assigned: it ${problem}.`); + } +} + +export function requireAbove(actor: Actor, role: RoleInfo): void { + if (!actor.owner && actor.highestRolePosition <= role.position) { + throw new UserError(`${role.name} is not below your highest role.`); + } +} + +export function requireManageable(role: RoleInfo): void { + if (role.managed || !role.botCanAssign) { + throw new UserError( + `I cannot manage ${role.name}: it is managed or above my highest role.`, + ); + } +} + +export function requireMentionable(actor: Actor, role: RoleInfo): void { + if (!actor.mentionEveryone && (role.everyone || !role.mentionable)) { + throw new UserError('You may not mention that role.'); + } +} diff --git a/src/infra/discord/actor.ts b/src/infra/discord/actor.ts new file mode 100644 index 0000000..2da4bfa --- /dev/null +++ b/src/infra/discord/actor.ts @@ -0,0 +1,43 @@ +import { PermissionFlagsBits, type GuildMember, type Role } from 'discord.js'; +import type { Actor, RoleInfo } from '~/domain'; + +const moderatorPermissions = [ + PermissionFlagsBits.Administrator, + PermissionFlagsBits.ManageGuild, + PermissionFlagsBits.ManageRoles, + PermissionFlagsBits.ManageChannels, + PermissionFlagsBits.ManageMessages, + PermissionFlagsBits.ManageWebhooks, + PermissionFlagsBits.BanMembers, + PermissionFlagsBits.KickMembers, + PermissionFlagsBits.ModerateMembers, + PermissionFlagsBits.MentionEveryone, +]; + +export function toActor(member: GuildMember): Actor { + return { + guildId: member.guild.id, + userId: member.id, + roleIds: [...member.roles.cache.keys()], + administrator: member.permissions.has(PermissionFlagsBits.Administrator), + owner: member.id === member.guild.ownerId, + mentionEveryone: member.permissions.has( + PermissionFlagsBits.MentionEveryone, + ), + highestRolePosition: member.roles.highest.position, + }; +} + +export function toRoleInfo(role: Role): RoleInfo { + return { + id: role.id, + name: role.name, + position: role.position, + everyone: role.id === role.guild.id, + managed: role.managed, + mentionable: role.mentionable, + moderator: moderatorPermissions.some((flag) => role.permissions.has(flag)), + administrator: role.permissions.has(PermissionFlagsBits.Administrator), + botCanAssign: role.editable, + }; +} diff --git a/src/infra/discord/adapters.ts b/src/infra/discord/adapters.ts new file mode 100644 index 0000000..e3e7ffc --- /dev/null +++ b/src/infra/discord/adapters.ts @@ -0,0 +1,242 @@ +import { + ChannelType, + GuildScheduledEventEntityType, + GuildScheduledEventPrivacyLevel, + PermissionFlagsBits, + type Client, + type Guild, + type GuildTextBasedChannel, +} from 'discord.js'; +import type { Calendar, Directory, Messenger } from '~/core/ports'; +import { PermanentError } from '~/domain'; +import { toActor, toRoleInfo } from './actor'; +import { isPermanentDiscordError, isUnknownObject } from './errors'; +import { render } from './render'; + +async function permanent(action: () => Promise): Promise { + try { + return await action(); + } catch (error) { + if (isPermanentDiscordError(error) && error instanceof Error) { + throw new PermanentError(error.message); + } + + throw error; + } +} + +async function orFalse(action: () => Promise): Promise { + try { + await action(); + + return true; + } catch (error) { + if (isUnknownObject(error)) { + return false; + } + + throw error; + } +} + +export function createDiscordMessenger(client: Client): Messenger { + const textChannel = async (id: string): Promise => { + const channel = await permanent(() => client.channels.fetch(id)); + + if (channel?.isTextBased() !== true || channel.isDMBased()) { + throw new PermanentError(`Channel ${id} is not a server text channel`); + } + + return channel; + }; + + return { + send: async (channelId, message) => { + const channel = await textChannel(channelId); + const sent = await permanent(() => channel.send(render(message))); + + return { channelId, messageId: sent.id }; + }, + edit: (channelId, messageId, message) => + orFalse(async () => { + const channel = await textChannel(channelId); + + await channel.messages.edit(messageId, render(message)); + }), + remove: (channelId, messageId) => + orFalse(async () => { + const channel = await textChannel(channelId); + + await channel.messages.delete(messageId); + }), + direct: async (userId, message) => { + const user = await permanent(() => client.users.fetch(userId)); + + await permanent(() => user.send(render(message))); + }, + exists: (channelId, messageId) => + orFalse(async () => { + const channel = await textChannel(channelId); + + await channel.messages.fetch(messageId); + }), + findOwn: async (channelId, content) => { + const channel = await textChannel(channelId); + const recent = await channel.messages.fetch({ limit: 50 }); + + return recent.find( + (message) => + message.author.id === client.user.id && message.content === content, + )?.id; + }, + ownReactions: async (channelId, messageId) => { + const channel = await textChannel(channelId); + const message = await channel.messages.fetch(messageId); + + return message.reactions.cache + .filter((reaction) => reaction.me) + .map((reaction) => reaction.emoji.name ?? ''); + }, + react: async (channelId, messageId, emoji) => { + const channel = await textChannel(channelId); + const message = await channel.messages.fetch(messageId); + + await message.react(emoji); + }, + }; +} + +export function createDiscordDirectory(client: Client): Directory { + const guild = (id: string): Promise => + permanent(() => client.guilds.fetch(id)); + + return { + guildOf: async (channelId) => { + const channel = await client.channels.fetch(channelId).catch(() => null); + + return channel && !channel.isDMBased() ? channel.guildId : undefined; + }, + channels: async (guildId) => { + const found = await guild(guildId); + const all = await found.channels.fetch(); + + return all + .filter( + (channel) => + channel?.type === ChannelType.GuildText || + channel?.type === ChannelType.GuildAnnouncement, + ) + .map((channel) => ({ + id: channel.id, + name: channel.name, + kind: + channel.type === ChannelType.GuildAnnouncement + ? ('announcement' as const) + : ('text' as const), + })); + }, + roles: async (guildId) => { + const found = await guild(guildId); + const roles = await found.roles.fetch(); + + return roles + .sort((a, b) => b.position - a.position) + .map((role) => toRoleInfo(role)); + }, + role: async (guildId, roleId) => { + const found = await guild(guildId); + const role = await found.roles.fetch(roleId).catch(() => null); + + return role ? toRoleInfo(role) : undefined; + }, + member: async (guildId, userId) => { + const found = await guild(guildId); + const member = await found.members.fetch(userId).catch(() => null); + + return member ? toActor(member) : undefined; + }, + canPost: async (actor, channelId) => { + const found = await guild(actor.guildId); + const [channel, member] = await Promise.all([ + found.channels.fetch(channelId).catch(() => null), + found.members.fetch(actor.userId).catch(() => null), + ]); + + if (!channel || !member) { + return false; + } + + return channel + .permissionsFor(member) + .has([ + PermissionFlagsBits.ViewChannel, + PermissionFlagsBits.SendMessages, + ]); + }, + addRoles: async ({ guildId, userId }, roleIds, reason) => { + const found = await guild(guildId); + const member = await permanent(() => found.members.fetch(userId)); + + await permanent(() => member.roles.add([...roleIds], reason)); + }, + removeRoles: async ({ guildId, userId }, roleIds, reason) => { + const found = await guild(guildId); + const member = await permanent(() => found.members.fetch(userId)); + + await permanent(() => member.roles.remove([...roleIds], reason)); + }, + createRole: async (guildId, role, reason) => { + const found = await guild(guildId); + const created = await found.roles.create({ + name: role.name, + permissions: [], + mentionable: role.mentionable, + reason, + ...(role.color !== undefined && { + colors: { primaryColor: role.color }, + }), + }); + + return toRoleInfo(created); + }, + deleteRole: async (guildId, roleId, reason) => { + const found = await guild(guildId); + + await found.roles.delete(roleId, reason); + }, + }; +} + +export function createDiscordCalendar(client: Client): Calendar { + return { + upsert: async (guildId, id, event) => { + const guild = await client.guilds.fetch(guildId); + const details = { + name: event.title.slice(0, 100), + scheduledStartTime: event.startsAt, + scheduledEndTime: event.endsAt, + description: event.description.slice(0, 1000), + entityMetadata: { location: event.location.slice(0, 100) }, + }; + + if (id !== null) { + await guild.scheduledEvents.edit(id, details); + + return id; + } + + const created = await guild.scheduledEvents.create({ + ...details, + privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly, + entityType: GuildScheduledEventEntityType.External, + }); + + return created.id; + }, + remove: async (guildId, id) => { + const guild = await client.guilds.fetch(guildId); + + await guild.scheduledEvents.delete(id); + }, + }; +} diff --git a/src/infra/discord/index.ts b/src/infra/discord/index.ts index d233f22..f3c49ae 100644 --- a/src/infra/discord/index.ts +++ b/src/infra/discord/index.ts @@ -6,3 +6,6 @@ export type * from './module'; export * from './define'; export * from './registry'; export * from './authorizer'; +export * from './actor'; +export * from './adapters'; +export * from './render'; diff --git a/src/infra/discord/render.ts b/src/infra/discord/render.ts new file mode 100644 index 0000000..32d1c2f --- /dev/null +++ b/src/infra/discord/render.ts @@ -0,0 +1,98 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + EmbedBuilder, + MessageFlags, + StringSelectMenuBuilder, + type MessageActionRowComponentBuilder, + type MessageMentionOptions, +} from 'discord.js'; +import type { Control, Embed, Mentions, Message } from '~/domain'; + +const buttonStyles = { + primary: ButtonStyle.Primary, + secondary: ButtonStyle.Secondary, + success: ButtonStyle.Success, + danger: ButtonStyle.Danger, +}; + +export function allowedMentions( + mentions: Mentions = {}, +): MessageMentionOptions { + return { + parse: mentions.everyone === true ? ['everyone'] : [], + users: [...(mentions.users ?? [])], + roles: [...(mentions.roles ?? [])], + }; +} + +function embed(source: Embed): EmbedBuilder { + const built = new EmbedBuilder(); + + if (source.title !== undefined) { + built.setTitle(source.title.slice(0, 256)); + } + + if (source.description !== undefined && source.description !== '') { + built.setDescription(source.description.slice(0, 4096)); + } + + if (source.url !== undefined) { + built.setURL(source.url); + } + + if (source.color !== undefined) { + built.setColor(source.color); + } + + if (source.footer !== undefined) { + built.setFooter({ text: source.footer }); + } + + return built.addFields( + (source.fields ?? []).map((field) => ({ + name: field.name, + value: field.value.slice(0, 1024), + inline: field.inline ?? false, + })), + ); +} + +function control(source: Control): MessageActionRowComponentBuilder { + if (source.kind === 'button') { + return new ButtonBuilder() + .setCustomId(source.id) + .setLabel(source.label) + .setStyle(buttonStyles[source.style]); + } + + return new StringSelectMenuBuilder() + .setCustomId(source.id) + .setPlaceholder(source.placeholder) + .setMinValues(source.min) + .setMaxValues(source.max) + .addOptions( + source.options.map((option) => ({ + label: option.label.slice(0, 100), + value: option.value, + default: option.default ?? false, + })), + ); +} + +export function render(message: Message) { + return { + content: message.content ?? '', + embeds: (message.embeds ?? []).map((source) => embed(source)), + components: (message.controls ?? []).map((row) => + new ActionRowBuilder().addComponents( + row.map((source) => control(source)), + ), + ), + allowedMentions: allowedMentions(message.mentions), + ...(message.suppressEmbeds === true && { + flags: MessageFlags.SuppressEmbeds as const, + }), + }; +} From b21f4737761cd0ad5ab7d5e78a7a4173425ca55b Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:35:22 +0200 Subject: [PATCH 022/199] refactor(permissions): actor-based authorization service behind ports --- scripts/register-commands.ts | 14 +- src/app.ts | 53 +++++-- src/core/ports/index.ts | 1 + src/core/ports/settings.ts | 4 + src/core/services/authorization.ts | 108 +++++++++++++++ src/core/services/guard.ts | 14 ++ src/core/services/index.ts | 4 + src/core/services/jobs.ts | 27 ++++ src/core/services/settings.ts | 25 ++++ src/features/announcements/index.ts | 20 +-- src/features/events/index.ts | 19 +-- src/features/movies/index.ts | 7 +- src/features/polls/index.ts | 19 +-- src/features/reminders/index.ts | 13 +- src/features/settings/index.ts | 59 -------- src/infra/db/permissions/repo.ts | 11 ++ src/infra/db/settings/repo.ts | 15 ++ src/infra/discord/adapters.ts | 8 +- src/infra/discord/authorizer.ts | 37 ----- src/infra/discord/commands/index.ts | 2 + .../discord/commands/permissions.ts} | 129 +++++------------- src/infra/discord/commands/settings.ts | 46 +++++++ src/infra/discord/index.ts | 2 +- src/infra/discord/module.ts | 15 +- src/infra/discord/router.ts | 5 +- tests/app.test.ts | 3 +- .../authorization.test.ts} | 34 +++-- tests/domain/permission.test.ts | 51 +++++++ tests/{shared => domain}/time.test.ts | 0 .../features/permissions/permissions.test.ts | 55 -------- .../crypto/secret-box.test.ts} | 0 .../{core => infra/discord}/registry.test.ts | 0 tests/{core => infra}/discord/router.test.ts | 14 +- .../redmine/client.test.ts | 0 .../scheduler/scheduler.test.ts | 0 35 files changed, 486 insertions(+), 328 deletions(-) create mode 100644 src/core/ports/settings.ts create mode 100644 src/core/services/authorization.ts create mode 100644 src/core/services/guard.ts create mode 100644 src/core/services/index.ts create mode 100644 src/core/services/jobs.ts create mode 100644 src/core/services/settings.ts delete mode 100644 src/features/settings/index.ts delete mode 100644 src/infra/discord/authorizer.ts create mode 100644 src/infra/discord/commands/index.ts rename src/{features/permissions/index.ts => infra/discord/commands/permissions.ts} (50%) create mode 100644 src/infra/discord/commands/settings.ts rename tests/core/{permissions/authorizer.test.ts => services/authorization.test.ts} (77%) create mode 100644 tests/domain/permission.test.ts rename tests/{shared => domain}/time.test.ts (100%) delete mode 100644 tests/features/permissions/permissions.test.ts rename tests/{shared/crypto.test.ts => infra/crypto/secret-box.test.ts} (100%) rename tests/{core => infra/discord}/registry.test.ts (100%) rename tests/{core => infra}/discord/router.test.ts (92%) rename tests/{integrations => infra}/redmine/client.test.ts (100%) rename tests/{core => infra}/scheduler/scheduler.test.ts (100%) diff --git a/scripts/register-commands.ts b/scripts/register-commands.ts index ffadee0..d091c31 100644 --- a/scripts/register-commands.ts +++ b/scripts/register-commands.ts @@ -1,3 +1,4 @@ +import { createLogger } from '~/infra/logging'; import { createRegistry } from '~/app'; import { loadConfig } from '~/config'; import { registerCommands } from '~/infra/discord'; @@ -8,11 +9,14 @@ if (config.DISCORD_APPLICATION_ID === undefined) { throw new Error('DISCORD_APPLICATION_ID is required to register commands'); } -const count = await registerCommands(createRegistry(config), { - token: config.DISCORD_TOKEN, - applicationId: config.DISCORD_APPLICATION_ID, - guildId: config.DISCORD_GUILD_ID, -}); +const count = await registerCommands( + createRegistry(config, createLogger('warn')), + { + token: config.DISCORD_TOKEN, + applicationId: config.DISCORD_APPLICATION_ID, + guildId: config.DISCORD_GUILD_ID, + }, +); const scope = config.DISCORD_GUILD_ID === undefined ? 'globally' diff --git a/src/app.ts b/src/app.ts index eecaf5a..d8cddb2 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,29 +3,56 @@ import type { Config } from '~/config'; import { createClient, createInteractionHandler, - createAuthorizer, buildRegistry, + createDiscordDirectory, + permissionCommands, + settingsCommands, } from '~/infra/discord'; +import { + createAuthorizer, + createPermissionService, + createSettingsService, +} from '~/core/services'; import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; import { createScheduler } from '~/infra/scheduler'; -import { connectDatabase, runMigrations } from '~/infra/db'; +import { + connectDatabase, + createGrantRepository, + createSettingsRepository, + runMigrations, +} from '~/infra/db'; import { announcementsFeature } from '~/features/announcements'; import { birthdaysFeature } from '~/features/birthdays'; import { eventsFeature } from '~/features/events'; import { moviesFeature } from '~/features/movies'; -import { createPermissionsFeature } from '~/features/permissions'; import { pollsFeature } from '~/features/polls'; import { createRedmineFeature } from '~/features/redmine'; import { remindersFeature } from '~/features/reminders'; import { rolesFeature } from '~/features/roles'; -import { settingsFeature } from '~/features/settings'; -export function createRegistry(config: Config): Registry { +export function compose(config: Config, log: Logger) { + const database = connectDatabase(config.DATABASE_URL); + const client = createClient(); + const grants = createGrantRepository(database.db); + const authz = createAuthorizer(grants); + const directory = createDiscordDirectory(client); + const settings = createSettingsService({ + settings: createSettingsRepository(database.db), + authz, + defaultTimezone: config.DEFAULT_TIMEZONE, + }); + const permissions = createPermissionService({ + grants, + directory, + authz, + log: log.child({ service: 'permissions' }), + known: () => registry.permissions, + }); const features: Feature[] = [ rolesFeature, - createPermissionsFeature(() => registry.permissions), - settingsFeature, + permissionCommands(permissions), + settingsCommands(settings), remindersFeature, announcementsFeature, eventsFeature, @@ -41,7 +68,11 @@ export function createRegistry(config: Config): Registry { const registry = buildRegistry(features); - return registry; + return { database, client, authz, registry }; +} + +export function createRegistry(config: Config, log: Logger): Registry { + return compose(config, log).registry; } function waitForReady(client: Client, token: string): Promise> { @@ -55,9 +86,7 @@ export async function startApp( config: Config, log: Logger, ): Promise<() => Promise> { - const registry = createRegistry(config); - const database = connectDatabase(config.DATABASE_URL); - const client = createClient(); + const { database, client, authz, registry } = compose(config, log); try { await runMigrations(database.db); @@ -72,7 +101,7 @@ export async function startApp( db: database.db, log, config, - authz: createAuthorizer(database.db), + authz, scheduler, }; diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index d2516f8..e15e934 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -4,3 +4,4 @@ export * from './clock'; export type * from './logger'; export type * from './scheduler'; export type * from './secrets'; +export type * from './settings'; diff --git a/src/core/ports/settings.ts b/src/core/ports/settings.ts new file mode 100644 index 0000000..6144359 --- /dev/null +++ b/src/core/ports/settings.ts @@ -0,0 +1,4 @@ +export type SettingsRepository = { + timezone: (guildId: string) => Promise; + setTimezone: (guildId: string, timezone: string) => Promise; +}; diff --git a/src/core/services/authorization.ts b/src/core/services/authorization.ts new file mode 100644 index 0000000..5504249 --- /dev/null +++ b/src/core/services/authorization.ts @@ -0,0 +1,108 @@ +import { + checkDelegation, + managePermissions, + UserError, + type Actor, + type Permission, + type PermissionDefinition, +} from '~/domain'; +import type { + Authorizer, + Directory, + GrantRepository, + Logger, +} from '~/core/ports'; +import { guard } from './guard'; + +export function createAuthorizer(grants: GrantRepository): Authorizer { + const can = async (actor: Actor, permission: Permission) => + actor.administrator || + grants.holds(actor.guildId, actor.roleIds, permission); + + return { + can, + require: async (actor, permission) => { + if (!(await can(actor, permission))) { + throw new UserError( + `You need the "${permission}" permission for this.`, + ); + } + }, + }; +} + +type Deps = { + grants: GrantRepository; + directory: Directory; + authz: Authorizer; + log: Logger; + known: () => ReadonlyMap; +}; + +export function createPermissionService(deps: Deps) { + const { grants, directory, authz, log, known } = deps; + + const definition = (value: string): PermissionDefinition => { + const found = [...known().values()].find((p) => p.id === value); + + if (!found) { + throw new UserError(`Unknown permission "${value}".`); + } + + return found; + }; + + const change = (action: 'grant' | 'revoke') => + guard( + authz, + managePermissions, + async (actor, roleId: string, value: string) => { + const { id: permission } = definition(value); + const role = await directory.role(actor.guildId, roleId); + + if (!role) { + throw new UserError('That role does not exist.'); + } + + checkDelegation({ + actor, + rolePosition: role.position, + permission, + actorHolds: await authz.can(actor, permission), + }); + + const input = { guildId: actor.guildId, roleId, permission }; + const changed = + action === 'grant' + ? await grants.grant({ ...input, grantedBy: actor.userId }) + : await grants.revoke(input); + + log.info( + { ...input, actorId: actor.userId, action, changed }, + 'Permission change', + ); + + return changed; + }, + ); + + return { + catalogue: () => [...known().values()], + grant: change('grant'), + revoke: change('revoke'), + list: guard(authz, managePermissions, (actor, roleId?: string) => + grants.list(actor.guildId, roleId), + ), + check: guard( + authz, + managePermissions, + async (actor, userId: string, value: string) => { + const member = await directory.member(actor.guildId, userId); + + return member !== undefined && authz.can(member, definition(value).id); + }, + ), + }; +} + +export type PermissionService = ReturnType; diff --git a/src/core/services/guard.ts b/src/core/services/guard.ts new file mode 100644 index 0000000..c8b9a08 --- /dev/null +++ b/src/core/services/guard.ts @@ -0,0 +1,14 @@ +import type { Actor, Permission } from '~/domain'; +import type { Authorizer } from '~/core/ports'; + +export function guard( + authz: Authorizer, + permission: Permission, + method: (actor: Actor, ...args: Args) => Promise, +): (actor: Actor, ...args: Args) => Promise { + return async (actor, ...args) => { + await authz.require(actor, permission); + + return method(actor, ...args); + }; +} diff --git a/src/core/services/index.ts b/src/core/services/index.ts new file mode 100644 index 0000000..a7985b9 --- /dev/null +++ b/src/core/services/index.ts @@ -0,0 +1,4 @@ +export * from './authorization'; +export * from './guard'; +export * from './jobs'; +export * from './settings'; diff --git a/src/core/services/jobs.ts b/src/core/services/jobs.ts new file mode 100644 index 0000000..a70f42a --- /dev/null +++ b/src/core/services/jobs.ts @@ -0,0 +1,27 @@ +import type { z } from 'zod'; +import { PermanentError } from '~/domain'; +import type { Job, JobInfo, JobOutcome } from '~/core/ports'; + +export function defineJob(definition: { + type: string; + payload: S; + maxAttempts?: number; + handle: ( + payload: z.infer, + info: JobInfo, + ) => Promise; +}): Job> { + return { + type: definition.type, + maxAttempts: definition.maxAttempts ?? 5, + run: async (raw, info) => { + const parsed = definition.payload.safeParse(raw); + + if (!parsed.success) { + throw new PermanentError(`Invalid payload: ${parsed.error.message}`); + } + + return (await definition.handle(parsed.data, info)) ?? null; + }, + }; +} diff --git a/src/core/services/settings.ts b/src/core/services/settings.ts new file mode 100644 index 0000000..0d8c397 --- /dev/null +++ b/src/core/services/settings.ts @@ -0,0 +1,25 @@ +import { requireZone } from '~/domain'; +import type { Authorizer, SettingsRepository } from '~/core/ports'; +import { guard } from './guard'; + +type Deps = { + settings: SettingsRepository; + authz: Authorizer; + defaultTimezone: string; +}; + +export function createSettingsService({ + settings, + authz, + defaultTimezone, +}: Deps) { + return { + timezone: async (guildId: string) => + (await settings.timezone(guildId)) ?? defaultTimezone, + setTimezone: guard(authz, 'settings:manage', (actor, zone: string) => + settings.setTimezone(actor.guildId, requireZone(zone)), + ), + }; +} + +export type SettingsService = ReturnType; diff --git a/src/features/announcements/index.ts b/src/features/announcements/index.ts index 4da0927..77c6298 100644 --- a/src/features/announcements/index.ts +++ b/src/features/announcements/index.ts @@ -1,3 +1,11 @@ +import { + toActor, + respond, + bySubcommand, + defineJob, + asJobError, + customId, +} from '~/infra/discord'; import { ChannelType, EmbedBuilder, @@ -15,13 +23,6 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { - respond, - bySubcommand, - defineJob, - asJobError, - customId, -} from '~/infra/discord'; import type { AppContext, CommandInteraction, @@ -248,7 +249,10 @@ async function requireEditable( ); if (announcement.authorId !== interaction.user.id) { - await ctx.authz.require(interaction.member, 'announcement:publish'); + await ctx.authz.require( + toActor(interaction.member), + 'announcement:publish', + ); } return announcement; diff --git a/src/features/events/index.ts b/src/features/events/index.ts index 326e7d7..688639d 100644 --- a/src/features/events/index.ts +++ b/src/features/events/index.ts @@ -1,3 +1,12 @@ +import { + toActor, + respond, + bySubcommand, + defineJob, + asJobError, + isUnknownObject, + customId, +} from '~/infra/discord'; import { ActionRowBuilder, ButtonBuilder, @@ -13,14 +22,6 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { - respond, - bySubcommand, - defineJob, - asJobError, - isUnknownObject, - customId, -} from '~/infra/discord'; import type { AppContext, CommandInteraction, @@ -326,7 +327,7 @@ async function requireManageable( ); if (event.organizerId !== interaction.user.id) { - await ctx.authz.require(interaction.member, 'event:manage'); + await ctx.authz.require(toActor(interaction.member), 'event:manage'); } return event; diff --git a/src/features/movies/index.ts b/src/features/movies/index.ts index dbe7c11..f55825f 100644 --- a/src/features/movies/index.ts +++ b/src/features/movies/index.ts @@ -1,3 +1,4 @@ +import { toActor, respond, bySubcommand } from '~/infra/discord'; import { ChannelType, InteractionContextType, @@ -5,7 +6,6 @@ import { SlashCommandBuilder, type SlashCommandIntegerOption, } from 'discord.js'; -import { respond, bySubcommand } from '~/infra/discord'; import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; import { getGuildTimezone } from '~/infra/db'; import { UserError, discordTime, parseFutureWhen, parseWhen } from '~/domain'; @@ -219,7 +219,10 @@ export const moviesFeature: Feature = { ); if (movie.suggestedBy !== interaction.user.id) { - await ctx.authz.require(interaction.member, 'movie:manage'); + await ctx.authz.require( + toActor(interaction.member), + 'movie:manage', + ); } await removeSuggestion(ctx.db, movie.id); diff --git a/src/features/polls/index.ts b/src/features/polls/index.ts index f1ce2e1..d2bad57 100644 --- a/src/features/polls/index.ts +++ b/src/features/polls/index.ts @@ -1,3 +1,11 @@ +import { + toActor, + respond, + bySubcommand, + defineJob, + isUnknownObject, + customId, +} from '~/infra/discord'; import { ActionRowBuilder, ButtonBuilder, @@ -13,13 +21,6 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { - respond, - bySubcommand, - defineJob, - isUnknownObject, - customId, -} from '~/infra/discord'; import type { AppContext, CommandInteraction, @@ -286,7 +287,7 @@ async function requireManageable( ); if (poll.creatorId !== interaction.user.id) { - await ctx.authz.require(interaction.member, 'poll:manage'); + await ctx.authz.require(toActor(interaction.member), 'poll:manage'); } return poll; @@ -376,7 +377,7 @@ async function showResults( ); const manager = poll.creatorId === interaction.user.id || - (await ctx.authz.can(interaction.member, 'poll:manage')); + (await ctx.authz.can(toActor(interaction.member), 'poll:manage')); if (poll.showResults === 'closed' && isOpen(poll) && !manager) { throw new UserError('Results are shown when the poll closes.'); diff --git a/src/features/reminders/index.ts b/src/features/reminders/index.ts index a39b74c..001b5d4 100644 --- a/src/features/reminders/index.ts +++ b/src/features/reminders/index.ts @@ -1,3 +1,10 @@ +import { + toActor, + respond, + bySubcommand, + defineJob, + asJobError, +} from '~/infra/discord'; import { ChannelType, InteractionContextType, @@ -5,7 +12,6 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { z } from 'zod'; -import { respond, bySubcommand, defineJob, asJobError } from '~/infra/discord'; import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; import { getGuildTimezone } from '~/infra/db'; import { @@ -210,7 +216,10 @@ export const remindersFeature: Feature = { ]); if (channel) { - await ctx.authz.require(interaction.member, 'reminder:channel'); + await ctx.authz.require( + toActor(interaction.member), + 'reminder:channel', + ); } const timezone = await zoneFor(interaction, ctx); diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts deleted file mode 100644 index 09fa004..0000000 --- a/src/features/settings/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { - InteractionContextType, - MessageFlags, - SlashCommandBuilder, -} from 'discord.js'; -import { bySubcommand } from '~/infra/discord'; -import type { Feature } from '~/infra/discord'; -import { getGuildTimezone, setGuildTimezone } from '~/infra/db'; -import { requireZone } from '~/domain'; - -const data = new SlashCommandBuilder() - .setName('settings') - .setDescription('Server-wide bot settings') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('timezone') - .setDescription('View or set the server timezone used for schedules') - .addStringOption((o) => - o.setName('zone').setDescription('IANA timezone, e.g. Europe/Tallinn'), - ), - ); - -export const settingsFeature: Feature = { - name: 'settings', - permissions: [ - { id: 'settings:manage', description: 'Change server-wide bot settings' }, - ], - commands: [ - { - data: data.toJSON(), - execute: bySubcommand({ - timezone: async (interaction, ctx) => { - const zone = interaction.options.getString('zone'); - - if (zone !== null) { - await ctx.authz.require(interaction.member, 'settings:manage'); - await setGuildTimezone( - ctx.db, - interaction.guildId, - requireZone(zone), - ); - } - - const current = await getGuildTimezone( - ctx.db, - interaction.guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - - await interaction.reply({ - content: `Server timezone: **${current}**`, - flags: MessageFlags.Ephemeral, - }); - }, - }), - }, - ], -}; diff --git a/src/infra/db/permissions/repo.ts b/src/infra/db/permissions/repo.ts index 6b009d2..848dc23 100644 --- a/src/infra/db/permissions/repo.ts +++ b/src/infra/db/permissions/repo.ts @@ -1,3 +1,4 @@ +import type { GrantRepository } from '~/core/ports'; import { and, eq, inArray } from 'drizzle-orm'; import type { Db } from '../client'; import { rolePermissions } from './model'; @@ -83,3 +84,13 @@ export async function listGrants( .orderBy(rolePermissions.roleId, rolePermissions.permission) .limit(500); } + +export function createGrantRepository(db: Db): GrantRepository { + return { + holds: (guildId, roleIds, permission) => + hasGrant(db, guildId, roleIds, permission), + grant: (change) => grant(db, change), + revoke: (change) => revoke(db, change), + list: (guildId, roleId) => listGrants(db, guildId, roleId), + }; +} diff --git a/src/infra/db/settings/repo.ts b/src/infra/db/settings/repo.ts index 6c2cadb..82c0bea 100644 --- a/src/infra/db/settings/repo.ts +++ b/src/infra/db/settings/repo.ts @@ -1,3 +1,4 @@ +import type { SettingsRepository } from '~/core/ports'; import { eq } from 'drizzle-orm'; import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; import type { Db } from '../client'; @@ -36,3 +37,17 @@ export async function setGuildTimezone( set: { timezone, updatedAt: new Date() }, }); } + +export function createSettingsRepository(db: Db): SettingsRepository { + return { + timezone: async (guildId) => { + const [row] = await db + .select({ timezone: guildSettings.timezone }) + .from(guildSettings) + .where(eq(guildSettings.guildId, guildId)); + + return row?.timezone ?? undefined; + }, + setTimezone: (guildId, timezone) => setGuildTimezone(db, guildId, timezone), + }; +} diff --git a/src/infra/discord/adapters.ts b/src/infra/discord/adapters.ts index e3e7ffc..4889db3 100644 --- a/src/infra/discord/adapters.ts +++ b/src/infra/discord/adapters.ts @@ -39,7 +39,7 @@ async function orFalse(action: () => Promise): Promise { } } -export function createDiscordMessenger(client: Client): Messenger { +export function createDiscordMessenger(client: Client): Messenger { const textChannel = async (id: string): Promise => { const channel = await permanent(() => client.channels.fetch(id)); @@ -86,7 +86,7 @@ export function createDiscordMessenger(client: Client): Messenger { return recent.find( (message) => - message.author.id === client.user.id && message.content === content, + message.author.id === client.user?.id && message.content === content, )?.id; }, ownReactions: async (channelId, messageId) => { @@ -106,7 +106,7 @@ export function createDiscordMessenger(client: Client): Messenger { }; } -export function createDiscordDirectory(client: Client): Directory { +export function createDiscordDirectory(client: Client): Directory { const guild = (id: string): Promise => permanent(() => client.guilds.fetch(id)); @@ -207,7 +207,7 @@ export function createDiscordDirectory(client: Client): Directory { }; } -export function createDiscordCalendar(client: Client): Calendar { +export function createDiscordCalendar(client: Client): Calendar { return { upsert: async (guildId, id, event) => { const guild = await client.guilds.fetch(guildId); diff --git a/src/infra/discord/authorizer.ts b/src/infra/discord/authorizer.ts deleted file mode 100644 index 1cba613..0000000 --- a/src/infra/discord/authorizer.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { PermissionFlagsBits, type GuildMember } from 'discord.js'; -import type { Db } from '~/infra/db'; -import { UserError } from '~/domain'; -import type { Authorizer, Permission } from './module'; -import { hasGrant } from '~/infra/db'; - -export function isAdministrator(member: GuildMember): boolean { - return member.permissions.has(PermissionFlagsBits.Administrator); -} - -export function createAuthorizer(db: Db): Authorizer { - const can = async (member: GuildMember, permission: Permission) => - isAdministrator(member) || - hasGrant(db, member.guild.id, [...member.roles.cache.keys()], permission); - - return { - can, - require: async (member, permission) => { - if (!(await can(member, permission))) { - throw new UserError( - `You need the \`${permission}\` permission for this.`, - ); - } - }, - }; -} - -export function requireCanPost(member: GuildMember, channelId: string): void { - const channel = member.guild.channels.cache.get(channelId); - const allowed = channel - ?.permissionsFor(member) - .has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages]); - - if (allowed !== true) { - throw new UserError(`You cannot post in <#${channelId}> yourself.`); - } -} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts new file mode 100644 index 0000000..fc00e56 --- /dev/null +++ b/src/infra/discord/commands/index.ts @@ -0,0 +1,2 @@ +export * from './permissions'; +export * from './settings'; diff --git a/src/features/permissions/index.ts b/src/infra/discord/commands/permissions.ts similarity index 50% rename from src/features/permissions/index.ts rename to src/infra/discord/commands/permissions.ts index d99c56a..21d017b 100644 --- a/src/features/permissions/index.ts +++ b/src/infra/discord/commands/permissions.ts @@ -1,27 +1,14 @@ import { InteractionContextType, SlashCommandBuilder, - type GuildMember, - type Role, type SlashCommandStringOption, } from 'discord.js'; -import { - respond, - bySubcommand, - deferred, - isAdministrator, -} from '~/infra/discord'; -import type { - AppContext, - CommandInteraction, - Feature, - Permission, - PermissionDefinition, -} from '~/infra/discord'; -import { grant, listGrants, revoke } from '~/infra/db'; -import { UserError } from '~/domain'; - -const managePermission: Permission = 'permissions:manage'; +import type { PermissionService } from '~/core/services'; +import { managePermissions, roleMention, userMention } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred } from '../define'; +import type { Feature } from '../module'; +import { respond } from '../router'; const permissionOption = (o: SlashCommandStringOption) => o @@ -68,97 +55,48 @@ const data = new SlashCommandBuilder() .addStringOption(permissionOption), ); -export async function checkDelegation( - ctx: Pick, - actor: GuildMember, - role: Role, - permission: Permission, -): Promise { - if (isAdministrator(actor)) { - return; - } - - if (permission === managePermission) { - throw new UserError( - 'Only administrators can delegate permission management.', - ); - } - - if (actor.roles.highest.comparePositionTo(role) <= 0) { - throw new UserError(`${role.name} is not below your highest role.`); - } - - if (!(await ctx.authz.can(actor, permission))) { - throw new UserError('You can only grant permissions you hold yourself.'); - } -} - -export function createPermissionsFeature( - known: () => ReadonlyMap, -): Feature { - const readPermission = (interaction: CommandInteraction): Permission => { - const value = interaction.options.getString('permission', true); - const definition = [...known().values()].find((p) => p.id === value); - - if (!definition) { - throw new UserError(`Unknown permission \`${value}\`.`); - } - - return definition.id; - }; - - const change = - (action: 'grant' | 'revoke') => - async (interaction: CommandInteraction, ctx: AppContext) => { +export function permissionCommands(permissions: PermissionService): Feature { + const change = (action: 'grant' | 'revoke') => + deferred(async (interaction) => { const role = interaction.options.getRole('role', true); - const permission = readPermission(interaction); - - await checkDelegation(ctx, interaction.member, role, permission); - const input = { - guildId: interaction.guildId, - roleId: role.id, + const permission = interaction.options.getString('permission', true); + const changed = await permissions[action]( + toActor(interaction.member), + role.id, permission, - }; - const changed = - action === 'grant' - ? await grant(ctx.db, { ...input, grantedBy: interaction.user.id }) - : await revoke(ctx.db, input); - - ctx.log.info( - { ...input, actorId: interaction.user.id, action, changed }, - 'Permission change', ); const verb = action === 'grant' ? 'Granted' : 'Revoked'; await respond( interaction, changed - ? `${verb} \`${permission}\` for ${role.toString()}.` + ? `${verb} "${permission}" for ${roleMention(role.id)}.` : 'Nothing changed.', ); - }; + }); return { name: 'permissions', permissions: [ - { id: managePermission, description: 'Grant and revoke bot permissions' }, + { + id: managePermissions, + description: 'Grant and revoke bot permissions', + }, ], commands: [ { data: data.toJSON(), - permissions: { '*': managePermission }, execute: bySubcommand({ grant: change('grant'), revoke: change('revoke'), - list: async (interaction, ctx) => { + list: async (interaction) => { const role = interaction.options.getRole('role'); - const grants = await listGrants( - ctx.db, - interaction.guildId, - role?.id, + const grants = await permissions.list( + toActor(interaction.member), + ...(role ? [role.id] : []), ); const lines = grants.map( - (g) => `<@&${g.roleId}> — \`${g.permission}\``, + (g) => `${roleMention(g.roleId)} — "${g.permission}"`, ); await respond( @@ -168,15 +106,21 @@ export function createPermissionsFeature( : lines.join('\n').slice(0, 2000), ); }, - check: deferred(async (interaction, ctx) => { + check: deferred(async (interaction) => { const user = interaction.options.getUser('member', true); - const member = await interaction.guild.members.fetch(user.id); - const permission = readPermission(interaction); - const allowed = await ctx.authz.can(member, permission); + const permission = interaction.options.getString( + 'permission', + true, + ); + const holds = await permissions.check( + toActor(interaction.member), + user.id, + permission, + ); await respond( interaction, - `${member.toString()} ${allowed ? 'holds' : 'does not hold'} \`${permission}\`.`, + `${userMention(user.id)} ${holds ? 'holds' : 'does not hold'} "${permission}".`, ); }), }), @@ -184,7 +128,8 @@ export function createPermissionsFeature( const query = interaction.options.getFocused().toLowerCase(); await interaction.respond( - [...known().values()] + permissions + .catalogue() .filter( (p) => p.id.includes(query) || diff --git a/src/infra/discord/commands/settings.ts b/src/infra/discord/commands/settings.ts new file mode 100644 index 0000000..d90d934 --- /dev/null +++ b/src/infra/discord/commands/settings.ts @@ -0,0 +1,46 @@ +import { InteractionContextType, SlashCommandBuilder } from 'discord.js'; +import type { SettingsService } from '~/core/services'; +import { toActor } from '../actor'; +import { bySubcommand } from '../define'; +import type { Feature } from '../module'; +import { respond } from '../router'; + +const data = new SlashCommandBuilder() + .setName('settings') + .setDescription('Server-wide bot settings') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('timezone') + .setDescription('View or set the server timezone used for schedules') + .addStringOption((o) => + o.setName('zone').setDescription('IANA timezone, e.g. Europe/Tallinn'), + ), + ); + +export function settingsCommands(settings: SettingsService): Feature { + return { + name: 'settings', + permissions: [ + { id: 'settings:manage', description: 'Change server-wide bot settings' }, + ], + commands: [ + { + data: data.toJSON(), + execute: bySubcommand({ + timezone: async (interaction) => { + const zone = interaction.options.getString('zone'); + + if (zone !== null) { + await settings.setTimezone(toActor(interaction.member), zone); + } + + const current = await settings.timezone(interaction.guildId); + + await respond(interaction, `Server timezone: **${current}**`); + }, + }), + }, + ], + }; +} diff --git a/src/infra/discord/index.ts b/src/infra/discord/index.ts index f3c49ae..19583c9 100644 --- a/src/infra/discord/index.ts +++ b/src/infra/discord/index.ts @@ -5,7 +5,7 @@ export * from './registration'; export type * from './module'; export * from './define'; export * from './registry'; -export * from './authorizer'; export * from './actor'; export * from './adapters'; export * from './render'; +export * from './commands'; diff --git a/src/infra/discord/module.ts b/src/infra/discord/module.ts index e1a0a2f..83ec038 100644 --- a/src/infra/discord/module.ts +++ b/src/infra/discord/module.ts @@ -5,25 +5,16 @@ import type { ChatInputCommandInteraction, Client, ClientEvents, - GuildMember, ModalSubmitInteraction, RESTPostAPIChatInputApplicationCommandsJSONBody, } from 'discord.js'; import type { Db } from '~/infra/db'; import type { Config } from '~/config'; import type { Logger } from '~/infra/logging'; +import type { Authorizer } from '~/core/ports'; +import type { Permission, PermissionDefinition } from '~/domain'; -export type Permission = `${string}:${string}`; - -export type PermissionDefinition = { - id: Permission; - description: string; -}; - -export type Authorizer = { - can: (member: GuildMember, permission: Permission) => Promise; - require: (member: GuildMember, permission: Permission) => Promise; -}; +export type { Permission, PermissionDefinition } from '~/domain'; export type ScheduleOptions = { runAt: Date; diff --git a/src/infra/discord/router.ts b/src/infra/discord/router.ts index c29d6b3..ddc80ae 100644 --- a/src/infra/discord/router.ts +++ b/src/infra/discord/router.ts @@ -11,6 +11,7 @@ import type { CommandInteraction, ComponentInteraction, } from './module'; +import { toActor } from './actor'; import { parseCustomId, type Registry } from './registry'; type Repliable = CommandInteraction | ComponentInteraction; @@ -57,7 +58,7 @@ async function runCommand( const required = permissions['*'] ?? permissions[subcommandPath(interaction)]; if (required !== undefined) { - await ctx.authz.require(interaction.member, required); + await ctx.authz.require(toActor(interaction.member), required); } await command.execute(interaction, ctx); @@ -76,7 +77,7 @@ async function runComponent( } if (handler.permission !== undefined) { - await ctx.authz.require(interaction.member, handler.permission); + await ctx.authz.require(toActor(interaction.member), handler.permission); } await handler.execute(interaction, parsed.args, ctx); diff --git a/tests/app.test.ts b/tests/app.test.ts index e40d567..d682592 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -2,6 +2,7 @@ import type { APIApplicationCommandOption, RESTPostAPIChatInputApplicationCommandsJSONBody, } from 'discord.js'; +import { pino } from 'pino'; import { describe, expect, it } from 'vitest'; import { createRegistry } from '~/app'; import type { Config } from '~/config'; @@ -49,7 +50,7 @@ function problems( } describe('composition root', () => { - const registry = createRegistry(config); + const registry = createRegistry(config, pino({ level: 'silent' })); it('builds without duplicate handlers', () => { expect(registry.features.map((f) => f.name)).toContain('roles'); diff --git a/tests/core/permissions/authorizer.test.ts b/tests/core/services/authorization.test.ts similarity index 77% rename from tests/core/permissions/authorizer.test.ts rename to tests/core/services/authorization.test.ts index 37cc455..8247ef9 100644 --- a/tests/core/permissions/authorizer.test.ts +++ b/tests/core/services/authorization.test.ts @@ -1,20 +1,24 @@ -import type { GuildMember } from 'discord.js'; import { beforeAll, describe, expect, it } from 'vitest'; import { noDatabase, snowflake, testDb } from '../../db'; import { UserError } from '~/domain'; -import { createAuthorizer } from '~/infra/discord'; -import { grant, listGrants, revoke } from '~/infra/db'; +import { createAuthorizer } from '~/core/services'; +import type { Actor } from '~/domain'; +import { createGrantRepository, grant, listGrants, revoke } from '~/infra/db'; function member( guildId: string, roleIds: string[], - admin = false, -): GuildMember { + administrator = false, +): Actor { return { - guild: { id: guildId }, - permissions: { has: () => admin }, - roles: { cache: new Map(roleIds.map((id) => [id, {}])) }, - } as unknown as GuildMember; + guildId, + userId: 'u', + roleIds, + administrator, + owner: false, + mentionEveryone: false, + highestRolePosition: 1, + }; } describe.skipIf(noDatabase)('authorizer', () => { @@ -41,7 +45,7 @@ describe.skipIf(noDatabase)('authorizer', () => { }); it('denies by default and allows granted roles', async () => { - const authz = createAuthorizer(testDb()); + const authz = createAuthorizer(createGrantRepository(testDb())); expect(await authz.can(member(guildId, []), 'event:create')).toBe(false); expect(await authz.can(member(guildId, [organizers]), 'event:create')).toBe( @@ -53,7 +57,7 @@ describe.skipIf(noDatabase)('authorizer', () => { }); it('combines grants from all roles of a member', async () => { - const authz = createAuthorizer(testDb()); + const authz = createAuthorizer(createGrantRepository(testDb())); const both = member(guildId, [organizers, helpers]); expect(await authz.can(both, 'event:create')).toBe(true); @@ -61,7 +65,7 @@ describe.skipIf(noDatabase)('authorizer', () => { }); it('isolates grants per guild', async () => { - const authz = createAuthorizer(testDb()); + const authz = createAuthorizer(createGrantRepository(testDb())); expect( await authz.can(member(otherGuild, [organizers]), 'event:create'), @@ -69,7 +73,7 @@ describe.skipIf(noDatabase)('authorizer', () => { }); it('lets Discord administrators do everything', async () => { - const authz = createAuthorizer(testDb()); + const authz = createAuthorizer(createGrantRepository(testDb())); expect( await authz.can(member(guildId, [], true), 'permissions:manage'), @@ -78,7 +82,7 @@ describe.skipIf(noDatabase)('authorizer', () => { it('stops allowing after revocation', async () => { const db = testDb(); - const authz = createAuthorizer(db); + const authz = createAuthorizer(createGrantRepository(db)); const role = snowflake(); expect( @@ -109,7 +113,7 @@ describe.skipIf(noDatabase)('authorizer', () => { }); it('require throws a user-facing error', async () => { - const authz = createAuthorizer(testDb()); + const authz = createAuthorizer(createGrantRepository(testDb())); await expect( authz.require(member(guildId, []), 'event:create'), diff --git a/tests/domain/permission.test.ts b/tests/domain/permission.test.ts new file mode 100644 index 0000000..74c02d8 --- /dev/null +++ b/tests/domain/permission.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import { checkDelegation, type Actor } from '~/domain'; + +const actor = (overrides: Partial = {}): Actor => ({ + guildId: 'g', + userId: 'u', + roleIds: [], + administrator: false, + owner: false, + mentionEveryone: false, + highestRolePosition: 5, + ...overrides, +}); + +describe('checkDelegation', () => { + it('lets administrators grant anything', () => { + expect(() => + checkDelegation({ + actor: actor({ administrator: true }), + rolePosition: 99, + permission: 'permissions:manage', + actorHolds: false, + }), + ).not.toThrow(); + }); + + it('never lets managers hand out permission management', () => { + expect(() => + checkDelegation({ + actor: actor(), + rolePosition: 1, + permission: 'permissions:manage', + actorHolds: true, + }), + ).toThrow('Only administrators'); + }); + + it('only allows held permissions, for roles below the manager', () => { + const grant = (rolePosition: number, actorHolds: boolean) => () => + checkDelegation({ + actor: actor(), + rolePosition, + permission: 'event:create', + actorHolds, + }); + + expect(grant(1, true)).not.toThrow(); + expect(grant(1, false)).toThrow('hold yourself'); + expect(grant(5, true)).toThrow('below'); + }); +}); diff --git a/tests/shared/time.test.ts b/tests/domain/time.test.ts similarity index 100% rename from tests/shared/time.test.ts rename to tests/domain/time.test.ts diff --git a/tests/features/permissions/permissions.test.ts b/tests/features/permissions/permissions.test.ts deleted file mode 100644 index 0fb9c2f..0000000 --- a/tests/features/permissions/permissions.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { GuildMember, Role } from 'discord.js'; -import { describe, expect, it } from 'vitest'; -import type { Authorizer } from '~/infra/discord'; -import { checkDelegation } from '~/features/permissions'; - -const role = {} as Role; -const actor = (options: { admin?: boolean; above?: boolean }) => - ({ - permissions: { has: () => options.admin ?? false }, - roles: { - highest: { comparePositionTo: () => (options.above === false ? 0 : 1) }, - }, - }) as unknown as GuildMember; -const authz = (holds: boolean) => ({ - authz: { - can: async () => holds, - require: async () => undefined, - } as Authorizer, -}); - -describe('permission delegation', () => { - it('lets administrators grant anything', async () => { - await expect( - checkDelegation( - authz(false), - actor({ admin: true }), - role, - 'permissions:manage', - ), - ).resolves.toBeUndefined(); - }); - - it('never lets managers hand out permission management', async () => { - await expect( - checkDelegation(authz(true), actor({}), role, 'permissions:manage'), - ).rejects.toThrow('Only administrators'); - }); - - it('only allows permissions the manager holds, for roles below them', async () => { - await expect( - checkDelegation(authz(true), actor({}), role, 'event:create'), - ).resolves.toBeUndefined(); - await expect( - checkDelegation(authz(false), actor({}), role, 'event:create'), - ).rejects.toThrow('hold yourself'); - await expect( - checkDelegation( - authz(true), - actor({ above: false }), - role, - 'event:create', - ), - ).rejects.toThrow('below'); - }); -}); diff --git a/tests/shared/crypto.test.ts b/tests/infra/crypto/secret-box.test.ts similarity index 100% rename from tests/shared/crypto.test.ts rename to tests/infra/crypto/secret-box.test.ts diff --git a/tests/core/registry.test.ts b/tests/infra/discord/registry.test.ts similarity index 100% rename from tests/core/registry.test.ts rename to tests/infra/discord/registry.test.ts diff --git a/tests/core/discord/router.test.ts b/tests/infra/discord/router.test.ts similarity index 92% rename from tests/core/discord/router.test.ts rename to tests/infra/discord/router.test.ts index 221c877..728a104 100644 --- a/tests/core/discord/router.test.ts +++ b/tests/infra/discord/router.test.ts @@ -28,7 +28,12 @@ function commandInteraction(commandName: string, subcommand: string | null) { commandName, guildId: 'g', user: { id: 'u' }, - member: { id: 'u' }, + member: { + id: 'u', + guild: { id: 'g', ownerId: 'o' }, + permissions: { has: () => false }, + roles: { cache: new Map(), highest: { position: 1 } }, + }, options: { getSubcommandGroup: () => null, getSubcommand: () => subcommand, @@ -92,7 +97,10 @@ describe('interaction router', () => { const interaction = commandInteraction('demo', 'manage'); await createInteractionHandler(registry, ctx)(interaction as never); - expect(require).toHaveBeenCalledWith(interaction.member, 'demo:manage'); + expect(require).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'u', guildId: 'g' }), + 'demo:manage', + ); expect(execute).not.toHaveBeenCalled(); expect(interaction.reply).toHaveBeenCalledWith( expect.objectContaining({ content: 'denied' }), @@ -107,7 +115,7 @@ describe('interaction router', () => { await createInteractionHandler(registry, allowed.ctx)(interaction as never); expect(allowed.require).toHaveBeenCalledWith( - interaction.member, + expect.objectContaining({ userId: 'u' }), 'demo:manage', ); expect(execute).toHaveBeenCalledWith(interaction, ['42', 'x'], allowed.ctx); diff --git a/tests/integrations/redmine/client.test.ts b/tests/infra/redmine/client.test.ts similarity index 100% rename from tests/integrations/redmine/client.test.ts rename to tests/infra/redmine/client.test.ts diff --git a/tests/core/scheduler/scheduler.test.ts b/tests/infra/scheduler/scheduler.test.ts similarity index 100% rename from tests/core/scheduler/scheduler.test.ts rename to tests/infra/scheduler/scheduler.test.ts From e3f8fa95a0f8179e14451e7f5d00e8fa8f8357c3 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 14:58:00 +0200 Subject: [PATCH 023/199] refactor(roles): role service behind chat ports with a thin Discord adapter --- src/app.ts | 35 +- src/core/ports/index.ts | 1 + src/core/ports/roles.ts | 55 +++ src/core/services/index.ts | 1 + src/core/services/roles.ts | 439 ++++++++++++++++++ src/features/roles/guards.ts | 61 --- src/features/roles/index.ts | 389 ---------------- src/features/roles/legacy.ts | 191 -------- src/features/roles/panels.ts | 182 -------- src/infra/db/index.ts | 2 + .../schema.ts => infra/db/roles/model.ts} | 0 .../service.ts => infra/db/roles/repo.ts} | 33 +- src/infra/discord/commands/index.ts | 1 + src/infra/discord/commands/roles.ts | 380 +++++++++++++++ src/infra/discord/router.ts | 23 + tests/core/services/roles.test.ts | 157 +++++++ tests/domain/role.test.ts | 33 ++ tests/fakes.ts | 107 +++++ tests/features/roles/roles.test.ts | 179 ------- 19 files changed, 1257 insertions(+), 1012 deletions(-) create mode 100644 src/core/ports/roles.ts create mode 100644 src/core/services/roles.ts delete mode 100644 src/features/roles/guards.ts delete mode 100644 src/features/roles/index.ts delete mode 100644 src/features/roles/legacy.ts delete mode 100644 src/features/roles/panels.ts rename src/{features/roles/schema.ts => infra/db/roles/model.ts} (100%) rename src/{features/roles/service.ts => infra/db/roles/repo.ts} (84%) create mode 100644 src/infra/discord/commands/roles.ts create mode 100644 tests/core/services/roles.test.ts create mode 100644 tests/domain/role.test.ts create mode 100644 tests/fakes.ts delete mode 100644 tests/features/roles/roles.test.ts diff --git a/src/app.ts b/src/app.ts index d8cddb2..2178d58 100644 --- a/src/app.ts +++ b/src/app.ts @@ -5,13 +5,17 @@ import { createInteractionHandler, buildRegistry, createDiscordDirectory, + createDiscordMessenger, + roleCommands, permissionCommands, settingsCommands, } from '~/infra/discord'; import { createAuthorizer, createPermissionService, + createRoleService, createSettingsService, + type LegacyPanel, } from '~/core/services'; import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; @@ -19,6 +23,7 @@ import { createScheduler } from '~/infra/scheduler'; import { connectDatabase, createGrantRepository, + createRolePanelRepository, createSettingsRepository, runMigrations, } from '~/infra/db'; @@ -29,7 +34,24 @@ import { moviesFeature } from '~/features/movies'; import { pollsFeature } from '~/features/polls'; import { createRedmineFeature } from '~/features/redmine'; import { remindersFeature } from '~/features/reminders'; -import { rolesFeature } from '~/features/roles'; + +function legacyPanel(config: Config): LegacyPanel | undefined { + const channelId = config.ROLE_SELECTION_CHANNEL_ID; + + if (channelId === undefined) { + return undefined; + } + + const roles = [ + { emoji: '1️⃣', roleId: config.TARKVARA_ROLE_ID, label: 'Tarkvara' }, + { emoji: '2️⃣', roleId: config.HELPDESK_ROLE_ID, label: 'Helpdesk' }, + { emoji: '3️⃣', roleId: config.KULTUUR_ROLE_ID, label: 'Kultuur' }, + ].flatMap(({ roleId, ...rest }) => + roleId === undefined ? [] : [{ roleId, ...rest }], + ); + + return { channelId, roles }; +} export function compose(config: Config, log: Logger) { const database = connectDatabase(config.DATABASE_URL); @@ -37,6 +59,15 @@ export function compose(config: Config, log: Logger) { const grants = createGrantRepository(database.db); const authz = createAuthorizer(grants); const directory = createDiscordDirectory(client); + const messenger = createDiscordMessenger(client); + const roles = createRoleService({ + panels: createRolePanelRepository(database.db), + directory, + messenger, + authz, + log: log.child({ service: 'roles' }), + legacy: legacyPanel(config), + }); const settings = createSettingsService({ settings: createSettingsRepository(database.db), authz, @@ -50,7 +81,7 @@ export function compose(config: Config, log: Logger) { known: () => registry.permissions, }); const features: Feature[] = [ - rolesFeature, + roleCommands(roles), permissionCommands(permissions), settingsCommands(settings), remindersFeature, diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index e15e934..2e3baaf 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -5,3 +5,4 @@ export type * from './logger'; export type * from './scheduler'; export type * from './secrets'; export type * from './settings'; +export type * from './roles'; diff --git a/src/core/ports/roles.ts b/src/core/ports/roles.ts new file mode 100644 index 0000000..4a23d97 --- /dev/null +++ b/src/core/ports/roles.ts @@ -0,0 +1,55 @@ +export type PanelKind = 'reaction' | 'select'; + +export type PanelRole = { + roleId: string; + label: string; + emoji: string | null; +}; + +export type RolePanel = { + id: number; + guildId: string; + channelId: string; + messageId: string | null; + kind: PanelKind; + title: string; + roles: PanelRole[]; +}; + +export type PanelSummary = Pick< + RolePanel, + 'id' | 'title' | 'kind' | 'channelId' +>; + +export type NewPanel = { + guildId: string; + channelId: string; + kind: PanelKind; + title: string; + createdBy: string; +}; + +export type ReactionKey = { + guildId: string; + channelId: string; + messageId: string; + emoji: string; +}; + +export type RolePanelRepository = { + reactionRole: (key: ReactionKey) => Promise; + find: (guildId: string, id: number) => Promise; + list: (guildId: string) => Promise; + selfAssignable: (guildId: string) => Promise; + create: (panel: NewPanel) => Promise; + reactionPanel: ( + guildId: string, + channelId: string, + ) => Promise<{ id: number; messageId: string | null } | undefined>; + setMessage: (id: number, messageId: string | null) => Promise; + setTitle: (id: number, title: string) => Promise; + replaceRoles: (id: number, roles: readonly PanelRole[]) => Promise; + addRole: (id: number, role: PanelRole) => Promise; + removeRole: (id: number, roleId: string) => Promise; + remove: (id: number) => Promise; +}; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index a7985b9..7359b81 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -2,3 +2,4 @@ export * from './authorization'; export * from './guard'; export * from './jobs'; export * from './settings'; +export * from './roles'; diff --git a/src/core/services/roles.ts b/src/core/services/roles.ts new file mode 100644 index 0000000..93d7c9c --- /dev/null +++ b/src/core/services/roles.ts @@ -0,0 +1,439 @@ +import { + channelMention, + controlId, + requireAbove, + requireManageable, + requireSelfAssignable, + roleMention, + selfAssignProblem, + UserError, + type Actor, + type Message, + type RoleInfo, +} from '~/domain'; +import type { + Authorizer, + Directory, + Logger, + Messenger, + NewRole, + PanelRole, + RolePanel, + RolePanelRepository, +} from '~/core/ports'; +import { sequential } from '~/lib'; +import { guard } from './guard'; + +export const legacyMessage = + 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur'; + +export type LegacyPanel = { + channelId: string; + roles: ReadonlyArray<{ emoji: string; roleId: string; label: string }>; +}; + +export type Reaction = { + guildId: string; + channelId: string; + messageId: string; + emoji: string; + userId: string; +}; + +type Deps = { + panels: RolePanelRepository; + directory: Directory; + messenger: Messenger; + authz: Authorizer; + log: Logger; + legacy?: LegacyPanel | undefined; +}; + +export function panelView(panel: RolePanel): Message { + return { + embeds: [ + { + title: panel.title, + description: + panel.roles.length === 0 + ? 'No roles yet.' + : panel.roles + .map((role) => `• ${roleMention(role.roleId)}`) + .join('\n'), + }, + ], + controls: + panel.roles.length === 0 + ? [] + : [ + [ + { + kind: 'button', + id: controlId('roles:open', panel.id), + label: 'Choose roles', + style: 'primary', + }, + ], + ], + }; +} + +export function choiceView(actor: Actor, panel: RolePanel): Message { + return { + content: + 'Pick the roles you want. Unselected roles from this panel are removed.', + controls: [ + [ + { + kind: 'select', + id: controlId('roles:choose', panel.id), + placeholder: 'Select your roles', + min: 0, + max: panel.roles.length, + options: panel.roles.map((role) => ({ + label: role.label, + value: role.roleId, + default: actor.roleIds.includes(role.roleId), + })), + }, + ], + ], + }; +} + +export function createRoleService(deps: Deps) { + const { panels, directory, messenger, authz, log, legacy } = deps; + + const requirePanel = async (guildId: string, id: number) => { + const panel = await panels.find(guildId, id); + + if (!panel) { + throw new UserError(`Role panel #${id} does not exist.`); + } + + return panel; + }; + + const requireRole = async (guildId: string, roleId: string) => { + const role = await directory.role(guildId, roleId); + + if (!role) { + throw new UserError('That role no longer exists.'); + } + + return role; + }; + + const publish = async (panel: RolePanel) => { + const view = panelView(panel); + const edited = + panel.messageId !== null && + (await messenger.edit(panel.channelId, panel.messageId, view)); + + if (!edited) { + const sent = await messenger.send(panel.channelId, view); + + await panels.setMessage(panel.id, sent.messageId); + } + }; + + const assignable = (actor: Actor, role: RoleInfo) => { + requireAbove(actor, role); + requireManageable(role); + + if (role.administrator && !actor.administrator) { + throw new UserError( + 'Only administrators can hand out administrator roles.', + ); + } + }; + + const postLegacy = async (channelId: string) => { + log.info({ channelId }, 'Posting role selection message'); + + const sent = await messenger.send(channelId, { content: legacyMessage }); + + return sent.messageId; + }; + + const syncLegacyPanel = async () => { + if (!legacy) { + return; + } + + const guildId = await directory.guildOf(legacy.channelId); + + if (guildId === undefined) { + log.error( + { channelId: legacy.channelId }, + 'ROLE_SELECTION_CHANNEL_ID is not a server text channel', + ); + + return; + } + + const roles = await Promise.all( + legacy.roles.map(async (entry) => ({ + entry, + role: await directory.role(guildId, entry.roleId), + })), + ); + + for (const { entry, role } of roles) { + const problem = role ? selfAssignProblem(role) : 'does not exist'; + + if (problem !== undefined) { + log.error({ ...entry, problem }, 'Legacy panel role is not assignable'); + } + } + + const existing = await panels.reactionPanel(guildId, legacy.channelId); + const panel = existing ?? { + id: await panels.create({ + guildId, + channelId: legacy.channelId, + kind: 'reaction', + title: 'Role selection', + createdBy: 'bot', + }), + messageId: null, + }; + + await panels.replaceRoles(panel.id, legacy.roles); + + const stored = + panel.messageId !== null && + (await messenger.exists(legacy.channelId, panel.messageId)) + ? panel.messageId + : undefined; + const located = + stored ?? (await messenger.findOwn(legacy.channelId, legacyMessage)); + const messageId = located ?? (await postLegacy(legacy.channelId)); + + if (messageId !== panel.messageId) { + await panels.setMessage(panel.id, messageId); + } + + const present = new Set( + await messenger.ownReactions(legacy.channelId, messageId), + ); + const missing = legacy.roles.filter(({ emoji }) => !present.has(emoji)); + + await sequential(missing, ({ emoji }) => + messenger.react(legacy.channelId, messageId, emoji), + ); + }; + + const reacted = async (reaction: Reaction, added: boolean) => { + const roleId = await panels.reactionRole(reaction); + + if (roleId === undefined) { + return; + } + + const role = await directory.role(reaction.guildId, roleId); + const problem = role ? selfAssignProblem(role) : 'does not exist'; + + if (problem !== undefined) { + log.warn({ roleId, problem }, 'Skipping reaction role change'); + + return; + } + + const member = { guildId: reaction.guildId, userId: reaction.userId }; + + await (added + ? directory.addRoles(member, [roleId], 'Role selection reaction') + : directory.removeRoles( + member, + [roleId], + 'Role selection reaction removed', + )); + log.info( + { ...member, roleId, added }, + added ? 'Assigned role' : 'Removed role', + ); + }; + + return { + syncLegacyPanel, + reacted, + panels: (guildId: string) => panels.list(guildId), + overview: async (guildId: string) => ({ + roles: await panels.selfAssignable(guildId), + panels: await panels.list(guildId), + }), + open: async (actor: Actor, panelId: number) => { + const panel = await requirePanel(actor.guildId, panelId); + + if (panel.roles.length === 0) { + throw new UserError('This panel has no roles yet.'); + } + + return choiceView(actor, panel); + }, + choose: async ( + actor: Actor, + panelId: number, + wanted: readonly string[], + ) => { + const panel = await requirePanel(actor.guildId, panelId); + const selected = new Set(wanted); + const roles = await directory.roles(actor.guildId); + const byId = new Map(roles.map((role) => [role.id, role])); + const usable = panel.roles.filter((entry) => { + const role = byId.get(entry.roleId); + + return role !== undefined && selfAssignProblem(role) === undefined; + }); + const skipped = panel.roles.filter((entry) => !usable.includes(entry)); + const has = (roleId: string) => actor.roleIds.includes(roleId); + const toAdd = usable + .filter((entry) => selected.has(entry.roleId) && !has(entry.roleId)) + .map((entry) => entry.roleId); + const toRemove = usable + .filter((entry) => !selected.has(entry.roleId) && has(entry.roleId)) + .map((entry) => entry.roleId); + const member = { guildId: actor.guildId, userId: actor.userId }; + + if (toAdd.length > 0) { + await directory.addRoles(member, toAdd, 'Role panel selection'); + } + + if (toRemove.length > 0) { + await directory.removeRoles(member, toRemove, 'Role panel selection'); + } + + log.info({ ...member, toAdd, toRemove }, 'Updated roles from panel'); + + return { + changed: toAdd.length + toRemove.length, + skipped: skipped.map((s) => s.label), + }; + }, + createPanel: guard( + authz, + 'role:manage', + async (actor, channelId: string, title: string) => { + if (!(await directory.canPost(actor, channelId))) { + throw new UserError( + `You cannot post in ${channelMention(channelId)} yourself.`, + ); + } + + const id = await panels.create({ + guildId: actor.guildId, + channelId, + kind: 'select', + title, + createdBy: actor.userId, + }); + + await publish(await requirePanel(actor.guildId, id)); + + return id; + }, + ), + updatePanel: guard( + authz, + 'role:manage', + async ( + actor, + panelId: number, + changes: { add?: PanelRole; remove?: string; title?: string }, + ) => { + const panel = await requirePanel(actor.guildId, panelId); + + if (panel.kind === 'reaction') { + throw new UserError( + 'The legacy reaction panel is configured through environment variables.', + ); + } + + if (changes.add) { + const role = await requireRole(actor.guildId, changes.add.roleId); + + requireSelfAssignable(role); + requireAbove(actor, role); + await panels.addRole(panel.id, changes.add); + } + + if ( + changes.remove !== undefined && + !(await panels.removeRole(panel.id, changes.remove)) + ) { + throw new UserError('That role is not on this panel.'); + } + + if (changes.title !== undefined) { + await panels.setTitle(panel.id, changes.title); + } + + await publish(await requirePanel(actor.guildId, panel.id)); + }, + ), + removePanel: guard(authz, 'role:manage', async (actor, panelId: number) => { + const panel = await requirePanel(actor.guildId, panelId); + + if (panel.kind === 'reaction' && !actor.administrator) { + throw new UserError( + 'Only an administrator can remove the original role message.', + ); + } + + if (panel.messageId !== null) { + await messenger.remove(panel.channelId, panel.messageId); + } + + await panels.remove(panel.id); + log.info( + { panelId, actorId: actor.userId, kind: panel.kind }, + 'Role panel removed', + ); + + return panel; + }), + createRole: guard(authz, 'role:create', (actor, role: NewRole) => + directory.createRole(actor.guildId, role, `Requested by ${actor.userId}`), + ), + deleteRole: guard(authz, 'role:manage', async (actor, roleId: string) => { + const role = await requireRole(actor.guildId, roleId); + + requireAbove(actor, role); + requireManageable(role); + await directory.deleteRole( + actor.guildId, + roleId, + `Requested by ${actor.userId}`, + ); + + return role; + }), + assign: guard( + authz, + 'role:assign', + async (actor, userId: string, roleId: string) => { + assignable(actor, await requireRole(actor.guildId, roleId)); + await directory.addRoles( + { guildId: actor.guildId, userId }, + [roleId], + `Assigned by ${actor.userId}`, + ); + }, + ), + unassign: guard( + authz, + 'role:assign', + async (actor, userId: string, roleId: string) => { + assignable(actor, await requireRole(actor.guildId, roleId)); + await directory.removeRoles( + { guildId: actor.guildId, userId }, + [roleId], + `Removed by ${actor.userId}`, + ); + }, + ), + }; +} + +export type RoleService = ReturnType; diff --git a/src/features/roles/guards.ts b/src/features/roles/guards.ts deleted file mode 100644 index 96ee20c..0000000 --- a/src/features/roles/guards.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { PermissionFlagsBits, type GuildMember, type Role } from 'discord.js'; -import { UserError } from '~/domain'; - -const moderatorPermissions = [ - PermissionFlagsBits.Administrator, - PermissionFlagsBits.ManageGuild, - PermissionFlagsBits.ManageRoles, - PermissionFlagsBits.ManageChannels, - PermissionFlagsBits.ManageMessages, - PermissionFlagsBits.ManageWebhooks, - PermissionFlagsBits.BanMembers, - PermissionFlagsBits.KickMembers, - PermissionFlagsBits.ModerateMembers, - PermissionFlagsBits.MentionEveryone, -]; - -export function selfAssignProblem(role: Role): string | undefined { - if (role.id === role.guild.id) { - return 'is the @everyone role'; - } - - if (role.managed) { - return 'is managed by an integration'; - } - - if (moderatorPermissions.some((flag) => role.permissions.has(flag))) { - return 'grants moderator permissions'; - } - - if (!role.editable) { - return 'is above my highest role, or I lack Manage Roles'; - } - - return undefined; -} - -export function requireSelfAssignable(role: Role): void { - const problem = selfAssignProblem(role); - - if (problem !== undefined) { - throw new UserError(`${role.name} cannot be self-assigned: it ${problem}.`); - } -} - -export function requireAbove(actor: GuildMember, role: Role): void { - if (actor.id === actor.guild.ownerId) { - return; - } - - if (actor.roles.highest.comparePositionTo(role) <= 0) { - throw new UserError(`${role.name} is not below your highest role.`); - } -} - -export function requireEditable(role: Role): void { - if (role.managed || !role.editable) { - throw new UserError( - `I cannot manage ${role.name}: it is managed or above my highest role.`, - ); - } -} diff --git a/src/features/roles/index.ts b/src/features/roles/index.ts deleted file mode 100644 index 5b08a1c..0000000 --- a/src/features/roles/index.ts +++ /dev/null @@ -1,389 +0,0 @@ -import { - ChannelType, - Events, - InteractionContextType, - SlashCommandBuilder, - type GuildMember, - type Role, -} from 'discord.js'; -import { - respond, - bySubcommand, - deferred, - defineListener, -} from '~/infra/discord'; -import type { - CommandInteraction, - Feature, - SlashCommand, -} from '~/infra/discord'; -import { UserError } from '~/domain'; -import { requireAbove, requireEditable, requireSelfAssignable } from './guards'; -import { handleReaction, syncLegacyPanel } from './legacy'; -import { panelComponents, publishPanel } from './panels'; -import { - addPanelRole, - createPanel, - deletePanel, - listPanels, - listSelfAssignableRoles, - removePanelRole, - requirePanel, - setPanelTitle, -} from './service'; - -const data = new SlashCommandBuilder() - .setName('role') - .setDescription('Manage roles and role panels') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Create a role without permissions') - .addStringOption((o) => - o - .setName('name') - .setDescription('Role name') - .setRequired(true) - .setMaxLength(100), - ) - .addStringOption((o) => - o.setName('color').setDescription('Hex color, e.g. #FFAC1C'), - ) - .addBooleanOption((o) => - o.setName('mentionable').setDescription('Allow anyone to mention it'), - ), - ) - .addSubcommand((sub) => - sub - .setName('delete') - .setDescription('Delete a role') - .addRoleOption((o) => - o.setName('role').setDescription('Role').setRequired(true), - ), - ) - .addSubcommand((sub) => - sub - .setName('assign') - .setDescription('Give a member a role') - .addUserOption((o) => - o.setName('member').setDescription('Member').setRequired(true), - ) - .addRoleOption((o) => - o.setName('role').setDescription('Role').setRequired(true), - ), - ) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription('Take a role from a member') - .addUserOption((o) => - o.setName('member').setDescription('Member').setRequired(true), - ) - .addRoleOption((o) => - o.setName('role').setDescription('Role').setRequired(true), - ), - ) - .addSubcommand((sub) => - sub.setName('list').setDescription('List self-assignable roles and panels'), - ) - .addSubcommandGroup((group) => - group - .setName('panel') - .setDescription('Role selection panels') - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Post a new role panel') - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Channel') - .setRequired(true) - .addChannelTypes(ChannelType.GuildText), - ) - .addStringOption((o) => - o - .setName('title') - .setDescription('Panel title') - .setRequired(true) - .setMaxLength(200), - ), - ) - .addSubcommand((sub) => - sub - .setName('update') - .setDescription('Add or remove roles, or rename a panel') - .addIntegerOption((o) => - o - .setName('panel') - .setDescription('Panel') - .setRequired(true) - .setAutocomplete(true), - ) - .addRoleOption((o) => o.setName('add').setDescription('Role to add')) - .addStringOption((o) => - o - .setName('label') - .setDescription('Label for the added role') - .setMaxLength(100), - ) - .addRoleOption((o) => - o.setName('remove').setDescription('Role to remove'), - ) - .addStringOption((o) => - o.setName('title').setDescription('New title').setMaxLength(200), - ), - ) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription( - 'Delete a panel and its message (including the legacy reaction panel)', - ) - .addIntegerOption((o) => - o - .setName('panel') - .setDescription('Panel') - .setRequired(true) - .setAutocomplete(true), - ), - ), - ); - -function parseColor(value: string | null): number | undefined { - if (value === null) { - return undefined; - } - - const match = /^#?([\da-f]{6})$/i.exec(value); - - if (match?.[1] === undefined) { - throw new UserError('Color must be a hex value like #FFAC1C.'); - } - - return Number.parseInt(match[1], 16); -} - -async function memberAndRole( - interaction: CommandInteraction, -): Promise<{ role: Role; member: GuildMember }> { - const role = interaction.options.getRole('role', true); - const user = interaction.options.getUser('member', true); - - requireAbove(interaction.member, role); - requireEditable(role); - if ( - role.permissions.has('Administrator') && - !interaction.member.permissions.has('Administrator') - ) { - throw new UserError( - 'Only administrators can hand out administrator roles.', - ); - } - - return { role, member: await interaction.guild.members.fetch(user.id) }; -} - -const command = { - data: data.toJSON(), - permissions: { - create: 'role:create', - delete: 'role:manage', - assign: 'role:assign', - remove: 'role:assign', - 'panel create': 'role:manage', - 'panel update': 'role:manage', - 'panel remove': 'role:manage', - }, - execute: bySubcommand({ - create: deferred(async (interaction) => { - const role = await interaction.guild.roles.create({ - name: interaction.options.getString('name', true), - permissions: [], - mentionable: interaction.options.getBoolean('mentionable') ?? false, - reason: `Requested by ${interaction.user.tag}`, - ...(() => { - const color = parseColor(interaction.options.getString('color')); - - return color === undefined ? {} : { colors: { primaryColor: color } }; - })(), - }); - - await respond(interaction, `Created ${role.toString()}.`); - }), - delete: deferred(async (interaction) => { - const role = interaction.options.getRole('role', true); - - requireAbove(interaction.member, role); - requireEditable(role); - await role.delete(`Requested by ${interaction.user.tag}`); - await respond(interaction, `Deleted ${role.name}.`); - }), - assign: deferred(async (interaction) => { - const { role, member } = await memberAndRole(interaction); - - await member.roles.add(role, `Assigned by ${interaction.user.tag}`); - await respond( - interaction, - `Gave ${role.toString()} to ${member.toString()}.`, - ); - }), - remove: deferred(async (interaction) => { - const { role, member } = await memberAndRole(interaction); - - await member.roles.remove(role, `Removed by ${interaction.user.tag}`); - await respond( - interaction, - `Removed ${role.toString()} from ${member.toString()}.`, - ); - }), - list: async (interaction, ctx) => { - const [roles, panels] = await Promise.all([ - listSelfAssignableRoles(ctx.db, interaction.guildId), - listPanels(ctx.db, interaction.guildId), - ]); - const lines = [ - '**Self-assignable roles**', - ...(roles.length === 0 - ? ['None yet.'] - : roles.map((r) => `• <@&${r.roleId}>`)), - '', - '**Panels**', - ...(panels.length === 0 - ? ['None yet.'] - : panels.map( - (p) => `• #${p.id} ${p.title} (${p.kind}) in <#${p.channelId}>`, - )), - ]; - - await respond(interaction, lines.join('\n')); - }, - 'panel create': deferred(async (interaction, ctx) => { - const channel = interaction.options.getChannel('channel', true, [ - ChannelType.GuildText, - ]); - const id = await createPanel(ctx.db, { - guildId: interaction.guildId, - channelId: channel.id, - kind: 'select', - title: interaction.options.getString('title', true), - createdBy: interaction.user.id, - }); - - await publishPanel( - ctx, - await requirePanel(ctx.db, interaction.guildId, id), - ); - await respond( - interaction, - `Created panel #${id}. Add roles with \`/role panel update panel:${id} add:\`.`, - ); - }), - 'panel update': deferred(async (interaction, ctx) => { - const panel = await requirePanel( - ctx.db, - interaction.guildId, - interaction.options.getInteger('panel', true), - ); - - if (panel.kind === 'reaction') { - throw new UserError( - 'The legacy reaction panel is configured through environment variables.', - ); - } - - const add = interaction.options.getRole('add'); - const remove = interaction.options.getRole('remove'); - const title = interaction.options.getString('title'); - - if (add) { - requireSelfAssignable(add); - requireAbove(interaction.member, add); - const label = interaction.options.getString('label') ?? add.name; - - await addPanelRole(ctx.db, panel.id, { - roleId: add.id, - label, - emoji: null, - }); - } - - if (remove && !(await removePanelRole(ctx.db, panel.id, remove.id))) { - throw new UserError(`${remove.name} is not on this panel.`); - } - - if (title !== null) { - await setPanelTitle(ctx.db, panel.id, title); - } - - await publishPanel( - ctx, - await requirePanel(ctx.db, interaction.guildId, panel.id), - ); - await respond(interaction, `Panel #${panel.id} updated.`); - }), - 'panel remove': deferred(async (interaction, ctx) => { - const panel = await requirePanel( - ctx.db, - interaction.guildId, - interaction.options.getInteger('panel', true), - ); - - if (panel.messageId !== null) { - const channel = await ctx.client.channels - .fetch(panel.channelId) - .catch(() => null); - - if (channel?.isTextBased() === true) { - await channel.messages.delete(panel.messageId).catch(() => null); - } - } - - await deletePanel(ctx.db, panel.id); - const note = - panel.kind === 'reaction' - ? ' Unset ROLE_SELECTION_CHANNEL_ID, or it will be posted again on the next start.' - : ''; - - await respond(interaction, `Removed panel #${panel.id}.${note}`); - }), - }), - autocomplete: async (interaction, ctx) => { - const query = interaction.options.getFocused().toLowerCase(); - const panels = await listPanels(ctx.db, interaction.guildId); - - await interaction.respond( - panels - .filter( - (p) => - p.title.toLowerCase().includes(query) || String(p.id) === query, - ) - .slice(0, 25) - .map((p) => ({ - name: `#${p.id} ${p.title}`.slice(0, 100), - value: p.id, - })), - ); - }, -} satisfies SlashCommand; - -export const rolesFeature: Feature = { - name: 'roles', - permissions: [ - { id: 'role:create', description: 'Create roles' }, - { id: 'role:manage', description: 'Delete roles and manage role panels' }, - { id: 'role:assign', description: 'Assign roles to other members' }, - ], - commands: [command], - components: panelComponents, - events: [ - defineListener(Events.MessageReactionAdd, (ctx, reaction, user) => - handleReaction(ctx, reaction, user, true), - ), - defineListener(Events.MessageReactionRemove, (ctx, reaction, user) => - handleReaction(ctx, reaction, user, false), - ), - ], - start: syncLegacyPanel, -}; diff --git a/src/features/roles/legacy.ts b/src/features/roles/legacy.ts deleted file mode 100644 index 298c6f7..0000000 --- a/src/features/roles/legacy.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { - ChannelType, - type Message, - type MessageReaction, - type PartialMessageReaction, - type PartialUser, - type TextChannel, - type User, -} from 'discord.js'; -import type { AppContext } from '~/infra/discord'; -import { sequential } from '~/lib'; -import { - createPanel, - findReactionPanel, - findReactionRole, - replacePanelRoles, - setPanelMessage, -} from './service'; -import { selfAssignProblem } from './guards'; - -export const legacyMessage = - 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur'; - -export function legacyRoles(ctx: Pick) { - const { config } = ctx; - - return [ - { emoji: '1️⃣', roleId: config.TARKVARA_ROLE_ID, label: 'Tarkvara' }, - { emoji: '2️⃣', roleId: config.HELPDESK_ROLE_ID, label: 'Helpdesk' }, - { emoji: '3️⃣', roleId: config.KULTUUR_ROLE_ID, label: 'Kultuur' }, - ].flatMap(({ roleId, ...rest }) => - roleId === undefined ? [] : [{ roleId, ...rest }], - ); -} - -async function findOrPostMessage( - ctx: AppContext, - channel: TextChannel, - storedId: string | null, - post: () => Promise, -): Promise { - if (storedId !== null) { - try { - return await channel.messages.fetch(storedId); - } catch (error) { - ctx.log.warn( - { err: error, messageId: storedId }, - 'Stored role panel message is gone', - ); - } - } - - const recent = await channel.messages.fetch({ limit: 50 }); - const existing = recent.find( - (message) => - message.author.id === ctx.client.user.id && - message.content === legacyMessage, - ); - - return existing ?? post(); -} - -export async function syncLegacyPanel(ctx: AppContext): Promise { - const channelId = ctx.config.ROLE_SELECTION_CHANNEL_ID; - - if (channelId === undefined) { - return; - } - - const channel = await ctx.client.channels.fetch(channelId); - - if (channel?.type !== ChannelType.GuildText) { - ctx.log.error( - { channelId }, - 'ROLE_SELECTION_CHANNEL_ID is not a server text channel', - ); - - return; - } - - const roles = legacyRoles(ctx); - - const fetched = await Promise.all( - roles.map(async ({ roleId, label }) => ({ - roleId, - label, - role: await channel.guild.roles.fetch(roleId), - })), - ); - - for (const { roleId, label, role } of fetched) { - const problem = role ? selfAssignProblem(role) : 'does not exist'; - - if (problem !== undefined) { - ctx.log.error( - { roleId, label, problem }, - 'Legacy panel role is not assignable', - ); - } - } - - const panel = (await findReactionPanel( - ctx.db, - channel.guildId, - channelId, - )) ?? { - id: await createPanel(ctx.db, { - guildId: channel.guildId, - channelId, - kind: 'reaction', - title: 'Role selection', - createdBy: ctx.client.user.id, - }), - messageId: null, - }; - - await replacePanelRoles(ctx.db, panel.id, roles); - - const message = await findOrPostMessage( - ctx, - channel, - panel.messageId, - async () => { - ctx.log.info({ channelId }, 'Posting role selection message'); - - return channel.send(legacyMessage); - }, - ); - - if (message.id !== panel.messageId) { - await setPanelMessage(ctx.db, panel.id, message.id); - } - - const missing = roles.filter( - ({ emoji }) => message.reactions.cache.get(emoji)?.me !== true, - ); - - await sequential(missing, ({ emoji }) => message.react(emoji)); -} - -export async function handleReaction( - ctx: AppContext, - reaction: MessageReaction | PartialMessageReaction, - user: User | PartialUser, - add: boolean, -): Promise { - const { message } = reaction; - const emoji = reaction.emoji.name; - - if (user.bot || message.guildId === null || emoji === null) { - return; - } - - const roleId = await findReactionRole(ctx.db, { - guildId: message.guildId, - channelId: message.channelId, - messageId: message.id, - emoji, - }); - - if (roleId === undefined) { - return; - } - - const guild = await ctx.client.guilds.fetch(message.guildId); - const role = await guild.roles.fetch(roleId); - const problem = role ? selfAssignProblem(role) : 'does not exist'; - - if (!role || problem !== undefined) { - ctx.log.warn({ roleId, problem }, 'Skipping reaction role change'); - - return; - } - - const member = await guild.members.fetch(user.id); - - if (member.user.bot) { - return; - } - - if (add) { - await member.roles.add(role, 'Role selection reaction'); - } else { - await member.roles.remove(role, 'Role selection reaction removed'); - } - - ctx.log.info( - { guildId: guild.id, userId: user.id, role: role.name, add }, - add ? 'Assigned role' : 'Removed role', - ); -} diff --git a/src/features/roles/panels.ts b/src/features/roles/panels.ts deleted file mode 100644 index 22abec8..0000000 --- a/src/features/roles/panels.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { - ActionRowBuilder, - ButtonBuilder, - ButtonStyle, - ChannelType, - EmbedBuilder, - MessageFlags, - StringSelectMenuBuilder, - type BaseMessageOptions, -} from 'discord.js'; -import { customId } from '~/infra/discord'; -import type { AppContext, ComponentHandler } from '~/infra/discord'; -import { UserError } from '~/domain'; -import { selfAssignProblem } from './guards'; -import { requirePanel, setPanelMessage, type Panel } from './service'; - -export function renderPanel(panel: Panel): BaseMessageOptions { - const embed = new EmbedBuilder() - .setTitle(panel.title) - .setDescription( - panel.roles.length === 0 - ? 'No roles yet.' - : panel.roles.map((role) => `• <@&${role.roleId}>`).join('\n'), - ); - const open = new ButtonBuilder() - .setCustomId(customId('roles:open', panel.id)) - .setLabel('Choose roles') - .setStyle(ButtonStyle.Primary); - - return { - embeds: [embed], - components: - panel.roles.length === 0 - ? [] - : [new ActionRowBuilder().addComponents(open)], - }; -} - -export async function publishPanel( - ctx: AppContext, - panel: Panel, -): Promise { - const channel = await ctx.client.channels - .fetch(panel.channelId) - .catch(() => null); - - if (channel?.type !== ChannelType.GuildText) { - throw new UserError(`I can no longer access <#${panel.channelId}>.`); - } - - const content = renderPanel(panel); - - if (panel.messageId !== null) { - const existing = await channel.messages - .fetch(panel.messageId) - .catch(() => null); - - if (existing) { - await existing.edit(content); - - return; - } - } - - const message = await channel.send(content); - - await setPanelMessage(ctx.db, panel.id, message.id); -} - -function parsePanelId(args: readonly string[]): number { - const id = Number(args[0]); - - if (!Number.isSafeInteger(id)) { - throw new UserError('This role panel is invalid.'); - } - - return id; -} - -const openHandler: ComponentHandler = { - prefix: 'roles:open', - execute: async (interaction, args, ctx) => { - const panel = await requirePanel( - ctx.db, - interaction.guildId, - parsePanelId(args), - ); - - if (panel.roles.length === 0) { - throw new UserError('This panel has no roles yet.'); - } - - const select = new StringSelectMenuBuilder() - .setCustomId(customId('roles:choose', panel.id)) - .setPlaceholder('Select your roles') - .setMinValues(0) - .setMaxValues(panel.roles.length) - .addOptions( - panel.roles.map((role) => ({ - label: role.label, - value: role.roleId, - default: interaction.member.roles.cache.has(role.roleId), - })), - ); - - await interaction.reply({ - content: - 'Pick the roles you want. Unselected roles from this panel are removed.', - components: [ - new ActionRowBuilder().addComponents(select), - ], - flags: MessageFlags.Ephemeral, - }); - }, -}; - -const chooseHandler: ComponentHandler = { - prefix: 'roles:choose', - execute: async (interaction, args, ctx) => { - if (!interaction.isStringSelectMenu()) { - return; - } - - await interaction.deferUpdate(); - const panel = await requirePanel( - ctx.db, - interaction.guildId, - parsePanelId(args), - ); - const wanted = new Set(interaction.values); - const toAdd: string[] = []; - const toRemove: string[] = []; - const skipped: string[] = []; - - for (const { roleId, label } of panel.roles) { - const role = interaction.guild.roles.cache.get(roleId); - - if (!role || selfAssignProblem(role) !== undefined) { - skipped.push(label); - continue; - } - - const has = interaction.member.roles.cache.has(roleId); - - if (wanted.has(roleId) && !has) { - toAdd.push(roleId); - } else if (!wanted.has(roleId) && has) { - toRemove.push(roleId); - } - } - - if (toAdd.length > 0) { - await interaction.member.roles.add(toAdd, 'Role panel selection'); - } - - if (toRemove.length > 0) { - await interaction.member.roles.remove(toRemove, 'Role panel selection'); - } - - ctx.log.info( - { - guildId: interaction.guildId, - userId: interaction.user.id, - toAdd, - toRemove, - }, - 'Updated roles from panel', - ); - const lines = [ - toAdd.length + toRemove.length === 0 - ? 'No changes.' - : 'Your roles are updated.', - ...(skipped.length > 0 - ? [`Unavailable right now: ${skipped.join(', ')}`] - : []), - ]; - - await interaction.editReply({ content: lines.join('\n'), components: [] }); - }, -}; - -export const panelComponents = [openHandler, chooseHandler]; diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index f607b5f..640cb99 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -4,3 +4,5 @@ export * from './jobs/repo'; export * from './permissions/model'; export * from './permissions/repo'; export * from './settings/repo'; +export * from './roles/model'; +export * from './roles/repo'; diff --git a/src/features/roles/schema.ts b/src/infra/db/roles/model.ts similarity index 100% rename from src/features/roles/schema.ts rename to src/infra/db/roles/model.ts diff --git a/src/features/roles/service.ts b/src/infra/db/roles/repo.ts similarity index 84% rename from src/features/roles/service.ts rename to src/infra/db/roles/repo.ts index 5c5aa23..c47e14d 100644 --- a/src/features/roles/service.ts +++ b/src/infra/db/roles/repo.ts @@ -1,16 +1,11 @@ import { and, asc, count, eq, max } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; +import type { PanelRole, RolePanelRepository } from '~/core/ports'; +import type { Db } from '../client'; import { UserError } from '~/domain'; -import { rolePanelRoles, rolePanels } from './schema'; +import { rolePanelRoles, rolePanels } from './model'; export const maxPanelRoles = 25; -export type PanelRole = { - roleId: string; - label: string; - emoji: string | null; -}; - export type Panel = typeof rolePanels.$inferSelect & { roles: PanelRole[] }; export async function findReactionRole( @@ -241,3 +236,25 @@ export async function removePanelRole( export async function deletePanel(db: Db, panelId: number): Promise { await db.delete(rolePanels).where(eq(rolePanels.id, panelId)); } + +export function createRolePanelRepository(db: Db): RolePanelRepository { + return { + reactionRole: (key) => findReactionRole(db, key), + find: (guildId, id) => getPanel(db, guildId, id), + list: (guildId) => listPanels(db, guildId), + selfAssignable: async (guildId) => { + const rows = await listSelfAssignableRoles(db, guildId); + + return rows.map((row) => row.roleId); + }, + create: (panel) => createPanel(db, panel), + reactionPanel: (guildId, channelId) => + findReactionPanel(db, guildId, channelId), + setMessage: (id, messageId) => setPanelMessage(db, id, messageId), + setTitle: (id, title) => setPanelTitle(db, id, title), + replaceRoles: (id, roles) => replacePanelRoles(db, id, roles), + addRole: (id, role) => addPanelRole(db, id, role), + removeRole: (id, roleId) => removePanelRole(db, id, roleId), + remove: (id) => deletePanel(db, id), + }; +} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index fc00e56..84adbca 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -1,2 +1,3 @@ export * from './permissions'; export * from './settings'; +export * from './roles'; diff --git a/src/infra/discord/commands/roles.ts b/src/infra/discord/commands/roles.ts new file mode 100644 index 0000000..6a5011b --- /dev/null +++ b/src/infra/discord/commands/roles.ts @@ -0,0 +1,380 @@ +import { + ChannelType, + Events, + InteractionContextType, + SlashCommandBuilder, + type MessageReaction, + type PartialMessageReaction, + type PartialUser, + type User, +} from 'discord.js'; +import type { RoleService } from '~/core/services'; +import { channelMention, roleMention, userMention, UserError } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred, defineListener } from '../define'; +import type { ComponentHandler, Feature, SlashCommand } from '../module'; +import { respond, respondView } from '../router'; + +const data = new SlashCommandBuilder() + .setName('role') + .setDescription('Manage roles and role panels') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Create a role without permissions') + .addStringOption((o) => + o + .setName('name') + .setDescription('Role name') + .setRequired(true) + .setMaxLength(100), + ) + .addStringOption((o) => + o.setName('color').setDescription('Hex color, e.g. #FFAC1C'), + ) + .addBooleanOption((o) => + o.setName('mentionable').setDescription('Allow anyone to mention it'), + ), + ) + .addSubcommand((sub) => + sub + .setName('delete') + .setDescription('Delete a role') + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('assign') + .setDescription('Give a member a role') + .addUserOption((o) => + o.setName('member').setDescription('Member').setRequired(true), + ) + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription('Take a role from a member') + .addUserOption((o) => + o.setName('member').setDescription('Member').setRequired(true), + ) + .addRoleOption((o) => + o.setName('role').setDescription('Role').setRequired(true), + ), + ) + .addSubcommand((sub) => + sub.setName('list').setDescription('List self-assignable roles and panels'), + ) + .addSubcommandGroup((group) => + group + .setName('panel') + .setDescription('Role selection panels') + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Post a new role panel') + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Channel') + .setRequired(true) + .addChannelTypes(ChannelType.GuildText), + ) + .addStringOption((o) => + o + .setName('title') + .setDescription('Panel title') + .setRequired(true) + .setMaxLength(200), + ), + ) + .addSubcommand((sub) => + sub + .setName('update') + .setDescription('Add or remove roles, or rename a panel') + .addIntegerOption((o) => + o + .setName('panel') + .setDescription('Panel') + .setRequired(true) + .setAutocomplete(true), + ) + .addRoleOption((o) => o.setName('add').setDescription('Role to add')) + .addStringOption((o) => + o + .setName('label') + .setDescription('Label for the added role') + .setMaxLength(100), + ) + .addRoleOption((o) => + o.setName('remove').setDescription('Role to remove'), + ) + .addStringOption((o) => + o.setName('title').setDescription('New title').setMaxLength(200), + ), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription( + 'Delete a panel and its message (including the legacy reaction panel)', + ) + .addIntegerOption((o) => + o + .setName('panel') + .setDescription('Panel') + .setRequired(true) + .setAutocomplete(true), + ), + ), + ); + +function parseColor(value: string | null): number | undefined { + if (value === null) { + return undefined; + } + + const match = /^#?([\da-f]{6})$/i.exec(value); + + if (match?.[1] === undefined) { + throw new UserError('Color must be a hex value like #FFAC1C.'); + } + + return Number.parseInt(match[1], 16); +} + +function panelId(args: readonly string[]): number { + const id = Number(args[0]); + + if (!Number.isSafeInteger(id)) { + throw new UserError('This role panel is invalid.'); + } + + return id; +} + +function reactionOf( + reaction: MessageReaction | PartialMessageReaction, + user: User | PartialUser, +) { + const { message } = reaction; + const emoji = reaction.emoji.name; + + if (user.bot || message.guildId === null || emoji === null) { + return null; + } + + return { + guildId: message.guildId, + channelId: message.channelId, + messageId: message.id, + emoji, + userId: user.id, + }; +} + +export function roleCommands(roles: RoleService): Feature { + const command: SlashCommand = { + data: data.toJSON(), + execute: bySubcommand({ + create: deferred(async (interaction) => { + const color = parseColor(interaction.options.getString('color')); + const role = await roles.createRole(toActor(interaction.member), { + name: interaction.options.getString('name', true), + mentionable: interaction.options.getBoolean('mentionable') ?? false, + ...(color !== undefined && { color }), + }); + + await respond(interaction, `Created ${roleMention(role.id)}.`); + }), + delete: deferred(async (interaction) => { + const role = interaction.options.getRole('role', true); + const deleted = await roles.deleteRole( + toActor(interaction.member), + role.id, + ); + + await respond(interaction, `Deleted ${deleted.name}.`); + }), + assign: deferred(async (interaction) => { + const role = interaction.options.getRole('role', true); + const user = interaction.options.getUser('member', true); + + await roles.assign(toActor(interaction.member), user.id, role.id); + await respond( + interaction, + `Gave ${roleMention(role.id)} to ${userMention(user.id)}.`, + ); + }), + remove: deferred(async (interaction) => { + const role = interaction.options.getRole('role', true); + const user = interaction.options.getUser('member', true); + + await roles.unassign(toActor(interaction.member), user.id, role.id); + await respond( + interaction, + `Removed ${roleMention(role.id)} from ${userMention(user.id)}.`, + ); + }), + list: async (interaction) => { + const overview = await roles.overview(interaction.guildId); + const lines = [ + '**Self-assignable roles**', + ...(overview.roles.length === 0 + ? ['None yet.'] + : overview.roles.map((id) => `• ${roleMention(id)}`)), + '', + '**Panels**', + ...(overview.panels.length === 0 + ? ['None yet.'] + : overview.panels.map( + (p) => + `• #${p.id} ${p.title} (${p.kind}) in ${channelMention(p.channelId)}`, + )), + ]; + + await respond(interaction, lines.join('\n')); + }, + 'panel create': deferred(async (interaction) => { + const channel = interaction.options.getChannel('channel', true, [ + ChannelType.GuildText, + ]); + const id = await roles.createPanel( + toActor(interaction.member), + channel.id, + interaction.options.getString('title', true), + ); + + await respond( + interaction, + `Created panel #${id}. Add roles with "/role panel update panel:${id} add:".`, + ); + }), + 'panel update': deferred(async (interaction) => { + const add = interaction.options.getRole('add'); + const remove = interaction.options.getRole('remove'); + const title = interaction.options.getString('title'); + const id = interaction.options.getInteger('panel', true); + + await roles.updatePanel(toActor(interaction.member), id, { + ...(add && { + add: { + roleId: add.id, + label: interaction.options.getString('label') ?? add.name, + emoji: null, + }, + }), + ...(remove && { remove: remove.id }), + ...(title !== null && { title }), + }); + await respond(interaction, `Panel #${id} updated.`); + }), + 'panel remove': deferred(async (interaction) => { + const panel = await roles.removePanel( + toActor(interaction.member), + interaction.options.getInteger('panel', true), + ); + const note = + panel.kind === 'reaction' + ? ' Unset ROLE_SELECTION_CHANNEL_ID, or it will be posted again on the next start.' + : ''; + + await respond(interaction, `Removed panel #${panel.id}.${note}`); + }), + }), + autocomplete: async (interaction) => { + const query = interaction.options.getFocused().toLowerCase(); + const panels = await roles.panels(interaction.guildId); + + await interaction.respond( + panels + .filter( + (p) => + p.title.toLowerCase().includes(query) || String(p.id) === query, + ) + .slice(0, 25) + .map((p) => ({ + name: `#${p.id} ${p.title}`.slice(0, 100), + value: p.id, + })), + ); + }, + }; + + const open: ComponentHandler = { + prefix: 'roles:open', + execute: async (interaction, args) => { + await respondView( + interaction, + await roles.open(toActor(interaction.member), panelId(args)), + ); + }, + }; + + const choose: ComponentHandler = { + prefix: 'roles:choose', + execute: async (interaction, args) => { + if (!interaction.isStringSelectMenu()) { + return; + } + + await interaction.deferUpdate(); + + const result = await roles.choose( + toActor(interaction.member), + panelId(args), + interaction.values, + ); + const lines = [ + result.changed === 0 ? 'No changes.' : 'Your roles are updated.', + ...(result.skipped.length > 0 + ? [`Unavailable right now: ${result.skipped.join(', ')}`] + : []), + ]; + + await interaction.editReply({ + content: lines.join('\n'), + components: [], + }); + }, + }; + + const added = defineListener( + Events.MessageReactionAdd, + async (_ctx, reaction, user) => { + const key = reactionOf(reaction, user); + + if (key) { + await roles.reacted(key, true); + } + }, + ); + const removed = defineListener( + Events.MessageReactionRemove, + async (_ctx, reaction, user) => { + const key = reactionOf(reaction, user); + + if (key) { + await roles.reacted(key, false); + } + }, + ); + + return { + name: 'roles', + permissions: [ + { id: 'role:create', description: 'Create roles' }, + { id: 'role:manage', description: 'Delete roles and manage role panels' }, + { id: 'role:assign', description: 'Assign roles to other members' }, + ], + commands: [command], + components: [open, choose], + events: [added, removed], + start: () => roles.syncLegacyPanel(), + }; +} diff --git a/src/infra/discord/router.ts b/src/infra/discord/router.ts index ddc80ae..900f2b8 100644 --- a/src/infra/discord/router.ts +++ b/src/infra/discord/router.ts @@ -11,7 +11,9 @@ import type { CommandInteraction, ComponentInteraction, } from './module'; +import type { Message as DomainMessage } from '~/domain'; import { toActor } from './actor'; +import { render } from './render'; import { parseCustomId, type Registry } from './registry'; type Repliable = CommandInteraction | ComponentInteraction; @@ -34,6 +36,27 @@ export async function respond( } } +export async function respondView( + interaction: Repliable, + view: DomainMessage, +): Promise { + const { content, embeds, components } = render(view); + const message = { + content, + embeds, + components, + allowedMentions: { parse: [] }, + }; + + if (interaction.replied) { + await interaction.followUp({ ...message, flags: MessageFlags.Ephemeral }); + } else if (interaction.deferred) { + await interaction.editReply(message); + } else { + await interaction.reply({ ...message, flags: MessageFlags.Ephemeral }); + } +} + export function subcommandPath(interaction: CommandInteraction): string { return [ interaction.options.getSubcommandGroup(false), diff --git a/tests/core/services/roles.test.ts b/tests/core/services/roles.test.ts new file mode 100644 index 0000000..8621695 --- /dev/null +++ b/tests/core/services/roles.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from 'vitest'; +import { createRoleService, legacyMessage } from '~/core/services'; +import { createRolePanelRepository } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + fakeDirectory, + fakeMessenger, + role, + silentLog, +} from '../../fakes'; + +describe.skipIf(noDatabase)('role service', () => { + const setup = ( + roles = [role({ id: 'tarkvara' }), role({ id: 'helpdesk' })], + canPost = true, + ) => { + const guildId = snowflake(); + const channelId = snowflake(); + const { messenger, sent } = fakeMessenger(); + const directory = fakeDirectory(roles, { canPost, guildId }); + const service = createRoleService({ + panels: createRolePanelRepository(testDb()), + directory, + messenger, + authz: allowAll, + log: silentLog, + legacy: { + channelId, + roles: [ + { emoji: '1️⃣', roleId: 'tarkvara', label: 'Tarkvara' }, + { emoji: '2️⃣', roleId: 'helpdesk', label: 'Helpdesk' }, + ], + }, + }); + + return { guildId, channelId, messenger, directory, service, sent }; + }; + + it('posts the legacy message once and reuses it after restarts', async () => { + const { service, messenger } = setup(); + + await service.syncLegacyPanel(); + await service.syncLegacyPanel(); + + expect(messenger.send).toHaveBeenCalledOnce(); + expect(messenger.send).toHaveBeenCalledWith(expect.any(String), { + content: legacyMessage, + }); + expect(messenger.react).toHaveBeenCalledTimes(4); + }); + + it('assigns and removes mapped roles, ignoring other messages and emoji', async () => { + const { service, sent, directory, guildId, channelId } = setup(); + + await service.syncLegacyPanel(); + + const messageId = sent[0] ?? ''; + const reaction = { + guildId, + channelId, + messageId, + emoji: '1️⃣', + userId: 'member', + }; + + await service.reacted(reaction, true); + await service.reacted(reaction, false); + await service.reacted({ ...reaction, messageId: 'other' }, true); + await service.reacted({ ...reaction, emoji: '🎉' }, true); + + expect(directory.addRoles).toHaveBeenCalledExactlyOnceWith( + { guildId, userId: 'member' }, + ['tarkvara'], + expect.any(String), + ); + expect(directory.removeRoles).toHaveBeenCalledOnce(); + }); + + it('skips roles that are gone or no longer assignable', async () => { + const { service, sent, directory, guildId, channelId } = setup([ + role({ id: 'tarkvara', moderator: true }), + ]); + + await service.syncLegacyPanel(); + + const messageId = sent[0] ?? ''; + + await service.reacted( + { guildId, channelId, messageId, emoji: '1️⃣', userId: 'u' }, + true, + ); + await service.reacted( + { guildId, channelId, messageId, emoji: '2️⃣', userId: 'u' }, + true, + ); + expect(directory.addRoles).not.toHaveBeenCalled(); + }); + + it('only lets administrators remove the legacy panel', async () => { + const { service, guildId } = setup(); + + await service.syncLegacyPanel(); + + const [legacy] = await service.panels(guildId); + + await expect( + service.removePanel(actor({ guildId }), legacy?.id ?? 0), + ).rejects.toThrow('administrator'); + await expect( + service.removePanel( + actor({ guildId, administrator: true }), + legacy?.id ?? 0, + ), + ).resolves.toBeDefined(); + }); + + it('applies select-menu choices and ignores forged role IDs', async () => { + const { service, directory, guildId, channelId } = setup(); + const id = await service.createPanel( + actor({ guildId }), + channelId, + 'Teams', + ); + + await service.updatePanel(actor({ guildId }), id, { + add: { roleId: 'tarkvara', label: 'Tarkvara', emoji: null }, + }); + await service.updatePanel(actor({ guildId }), id, { + add: { roleId: 'helpdesk', label: 'Helpdesk', emoji: null }, + }); + + const member = actor({ guildId, roleIds: ['helpdesk'] }); + const result = await service.choose(member, id, ['tarkvara', 'admin']); + + expect(result.changed).toBe(2); + expect(directory.addRoles).toHaveBeenCalledWith( + expect.anything(), + ['tarkvara'], + expect.any(String), + ); + expect(directory.removeRoles).toHaveBeenCalledWith( + expect.anything(), + ['helpdesk'], + expect.any(String), + ); + }); + + it('refuses panels in channels the member cannot post in', async () => { + const { service, guildId, channelId } = setup(undefined, false); + + await expect( + service.createPanel(actor({ guildId }), channelId, 'x'), + ).rejects.toThrow('cannot post'); + }); +}); diff --git a/tests/domain/role.test.ts b/tests/domain/role.test.ts new file mode 100644 index 0000000..07cbf66 --- /dev/null +++ b/tests/domain/role.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { requireAbove, selfAssignProblem } from '~/domain'; +import { actor, role } from '../fakes'; + +describe('role rules', () => { + it('accepts ordinary assignable roles', () => { + expect(selfAssignProblem(role())).toBeUndefined(); + }); + + it.each([ + ['everyone', role({ everyone: true })], + ['managed', role({ managed: true })], + ['moderator', role({ moderator: true })], + ['above the bot', role({ botCanAssign: false })], + ])('rejects %s roles', (_name, candidate) => { + expect(selfAssignProblem(candidate)).toBeDefined(); + }); + + it('only lets members manage roles below their highest role', () => { + expect(() => + requireAbove(actor({ highestRolePosition: 2 }), role({ position: 1 })), + ).not.toThrow(); + expect(() => + requireAbove(actor({ highestRolePosition: 1 }), role({ position: 1 })), + ).toThrow('not below'); + expect(() => + requireAbove( + actor({ highestRolePosition: 1, owner: true }), + role({ position: 5 }), + ), + ).not.toThrow(); + }); +}); diff --git a/tests/fakes.ts b/tests/fakes.ts new file mode 100644 index 0000000..d351314 --- /dev/null +++ b/tests/fakes.ts @@ -0,0 +1,107 @@ +import { randomUUID } from 'node:crypto'; +import { pino } from 'pino'; +import { vi } from 'vitest'; +import type { Directory, Messenger } from '~/core/ports'; +import { UserError, type Actor, type RoleInfo } from '~/domain'; + +export const silentLog = pino({ level: 'silent' }); + +export function actor(overrides: Partial = {}): Actor { + return { + guildId: 'g', + userId: 'u', + roleIds: [], + administrator: false, + owner: false, + mentionEveryone: false, + highestRolePosition: 10, + ...overrides, + }; +} + +export function role(overrides: Partial = {}): RoleInfo { + return { + id: 'r', + name: 'Role', + position: 1, + everyone: false, + managed: false, + mentionable: true, + moderator: false, + administrator: false, + botCanAssign: true, + ...overrides, + }; +} + +export const allowAll = { + can: async () => true, + require: async () => undefined, +}; + +export const denyAll = { + can: async () => false, + require: async () => { + throw new UserError('denied'); + }, +}; + +export function fakeMessenger() { + const sent: string[] = []; + const messages = new Map(); + const messenger = { + send: vi.fn(async (channelId, message) => { + const messageId = randomUUID(); + + sent.push(messageId); + + messages.set(messageId, { channelId, content: message.content ?? '' }); + + return { channelId, messageId }; + }), + edit: vi.fn(async (_c, messageId) => + messages.has(messageId), + ), + remove: vi.fn(async (_c, messageId) => + messages.delete(messageId), + ), + direct: vi.fn(async () => undefined), + exists: vi.fn(async (_c, messageId) => + messages.has(messageId), + ), + findOwn: vi.fn( + async (channelId, content) => + [...messages].find( + ([, m]) => m.channelId === channelId && m.content === content, + )?.[0], + ), + ownReactions: vi.fn(async () => []), + react: vi.fn(async () => undefined), + } satisfies Messenger; + + return { messenger, messages, sent }; +} + +export function fakeDirectory( + roles: RoleInfo[] = [], + options: { canPost?: boolean; guildId?: string } = {}, +) { + const directory = { + guildOf: vi.fn(async () => options.guildId ?? 'g'), + channels: vi.fn(async () => []), + roles: vi.fn(async () => roles), + role: vi.fn(async (_g, id) => + roles.find((r) => r.id === id), + ), + member: vi.fn(async () => undefined), + canPost: vi.fn(async () => options.canPost ?? true), + addRoles: vi.fn(async () => undefined), + removeRoles: vi.fn(async () => undefined), + createRole: vi.fn(async (_g, r) => + role({ name: r.name }), + ), + deleteRole: vi.fn(async () => undefined), + } satisfies Directory; + + return directory; +} diff --git a/tests/features/roles/roles.test.ts b/tests/features/roles/roles.test.ts deleted file mode 100644 index 2d3dbfd..0000000 --- a/tests/features/roles/roles.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { - PermissionFlagsBits, - PermissionsBitField, - type Role, -} from 'discord.js'; -import { pino } from 'pino'; -import { beforeAll, describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { requireAbove, selfAssignProblem } from '~/features/roles/guards'; -import { - handleReaction, - legacyMessage, - legacyRoles, -} from '~/features/roles/legacy'; -import { - addPanelRole, - createPanel, - replacePanelRoles, - setPanelMessage, -} from '~/features/roles/service'; - -function role( - overrides: Partial<{ - id: string; - managed: boolean; - editable: boolean; - permissions: bigint[]; - }> = {}, -) { - return { - id: overrides.id ?? 'r1', - name: 'Role', - guild: { id: 'guild' }, - managed: overrides.managed ?? false, - editable: overrides.editable ?? true, - permissions: new PermissionsBitField(overrides.permissions ?? []), - } as unknown as Role; -} - -describe('legacy role mapping', () => { - it('keeps the original message and emoji mapping', () => { - expect(legacyMessage).toBe( - 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur', - ); - const config = { - TARKVARA_ROLE_ID: 't', - HELPDESK_ROLE_ID: 'h', - KULTUUR_ROLE_ID: 'k', - }; - - expect(legacyRoles({ config } as never)).toEqual([ - { emoji: '1️⃣', roleId: 't', label: 'Tarkvara' }, - { emoji: '2️⃣', roleId: 'h', label: 'Helpdesk' }, - { emoji: '3️⃣', roleId: 'k', label: 'Kultuur' }, - ]); - }); - - it('skips roles that are not configured', () => { - expect( - legacyRoles({ config: { HELPDESK_ROLE_ID: 'h' } } as never).map( - (r) => r.label, - ), - ).toEqual(['Helpdesk']); - }); -}); - -describe('role guards', () => { - it('accepts ordinary editable roles', () => { - expect(selfAssignProblem(role())).toBeUndefined(); - }); - - it.each([ - ['everyone', role({ id: 'guild' })], - ['managed', role({ managed: true })], - ['moderator', role({ permissions: [PermissionFlagsBits.BanMembers] })], - ['above the bot', role({ editable: false })], - ])('rejects %s roles', (_name, candidate) => { - expect(selfAssignProblem(candidate)).toBeDefined(); - }); - - it('only lets members manage roles below their highest role', () => { - const actor = (position: number) => - ({ - id: 'a', - guild: { ownerId: 'owner' }, - roles: { highest: { comparePositionTo: () => position } }, - }) as never; - - expect(() => requireAbove(actor(1), role())).not.toThrow(); - expect(() => requireAbove(actor(0), role())).toThrow( - 'not below your highest role', - ); - }); -}); - -describe.skipIf(noDatabase)('reaction role handling', () => { - const guildId = snowflake(); - const channelId = snowflake(); - const messageId = snowflake(); - const roleId = snowflake(); - const add = vi.fn(async () => undefined); - const remove = vi.fn(async () => undefined); - const assignable = role({ id: roleId }); - const guild = { - id: guildId, - roles: { - fetch: vi.fn(async (id: string) => (id === roleId ? assignable : null)), - }, - members: { - fetch: vi.fn(async () => ({ - user: { bot: false }, - roles: { add, remove }, - })), - }, - }; - const ctx = { - db: noDatabase ? undefined : testDb(), - log: pino({ level: 'silent' }), - client: { guilds: { fetch: async () => guild } }, - } as unknown as AppContext; - const reaction = (emoji: string, message = messageId) => - ({ - emoji: { name: emoji }, - message: { id: message, guildId, channelId }, - }) as never; - const user = (bot = false) => ({ id: 'u', bot }) as never; - - beforeAll(async () => { - const panelId = await createPanel(ctx.db, { - guildId, - channelId, - kind: 'reaction', - title: 'Legacy', - createdBy: 'bot', - }); - - await setPanelMessage(ctx.db, panelId, messageId); - await replacePanelRoles(ctx.db, panelId, [ - { roleId, label: 'Tarkvara', emoji: '1️⃣' }, - ]); - }); - - it('assigns and removes the mapped role', async () => { - await handleReaction(ctx, reaction('1️⃣'), user(), true); - expect(add).toHaveBeenCalledWith(assignable, expect.any(String)); - await handleReaction(ctx, reaction('1️⃣'), user(), false); - expect(remove).toHaveBeenCalledWith(assignable, expect.any(String)); - }); - - it('ignores reactions on unrelated messages, other emoji and bots', async () => { - add.mockClear(); - guild.members.fetch.mockClear(); - await handleReaction(ctx, reaction('1️⃣', snowflake()), user(), true); - await handleReaction(ctx, reaction('🎉'), user(), true); - await handleReaction(ctx, reaction('1️⃣'), user(true), true); - expect(add).not.toHaveBeenCalled(); - expect(guild.members.fetch).not.toHaveBeenCalled(); - }); - - it('skips roles that no longer exist', async () => { - const panelId = await createPanel(ctx.db, { - guildId, - channelId: snowflake(), - kind: 'select', - title: 'x', - createdBy: 'u', - }); - - await addPanelRole(ctx.db, panelId, { - roleId: 'gone', - label: 'Gone', - emoji: '4️⃣', - }); - add.mockClear(); - await handleReaction(ctx, reaction('4️⃣'), user(), true); - expect(add).not.toHaveBeenCalled(); - }); -}); From 036684d26d06a989a2ec81ac19a6d2896a83e5ec Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 19:38:39 +0200 Subject: [PATCH 024/199] refactor(reminders): reminder service with job queue port and Discord adapter --- src/app.ts | 37 +- src/core/ports/index.ts | 1 + src/core/ports/reminders.ts | 28 ++ src/core/services/index.ts | 1 + src/core/services/reminders.ts | 200 +++++++++++ src/features/redmine/index.ts | 9 +- src/features/reminders/index.ts | 328 ------------------ src/infra/db/index.ts | 2 + .../schema.ts => infra/db/reminders/model.ts} | 0 .../service.ts => infra/db/reminders/repo.ts} | 40 +-- src/infra/discord/commands/index.ts | 1 + src/infra/discord/commands/reminders.ts | 168 +++++++++ src/infra/scheduler/index.ts | 1 + src/infra/scheduler/queue.ts | 17 + tests/core/services/reminders.test.ts | 154 ++++++++ tests/features/redmine/redmine.test.ts | 21 +- tests/features/reminders/reminders.test.ts | 133 ------- 17 files changed, 634 insertions(+), 507 deletions(-) create mode 100644 src/core/ports/reminders.ts create mode 100644 src/core/services/reminders.ts delete mode 100644 src/features/reminders/index.ts rename src/{features/reminders/schema.ts => infra/db/reminders/model.ts} (100%) rename src/{features/reminders/service.ts => infra/db/reminders/repo.ts} (72%) create mode 100644 src/infra/discord/commands/reminders.ts create mode 100644 src/infra/scheduler/queue.ts create mode 100644 tests/core/services/reminders.test.ts delete mode 100644 tests/features/reminders/reminders.test.ts diff --git a/src/app.ts b/src/app.ts index 2178d58..feac805 100644 --- a/src/app.ts +++ b/src/app.ts @@ -6,6 +6,7 @@ import { buildRegistry, createDiscordDirectory, createDiscordMessenger, + reminderCommands, roleCommands, permissionCommands, settingsCommands, @@ -13,16 +14,19 @@ import { import { createAuthorizer, createPermissionService, + createReminderService, createRoleService, createSettingsService, type LegacyPanel, } from '~/core/services'; import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; -import { createScheduler } from '~/infra/scheduler'; +import { createJobQueue, createScheduler } from '~/infra/scheduler'; +import type { Job } from '~/core/ports'; import { connectDatabase, createGrantRepository, + createReminderRepository, createRolePanelRepository, createSettingsRepository, runMigrations, @@ -33,7 +37,6 @@ import { eventsFeature } from '~/features/events'; import { moviesFeature } from '~/features/movies'; import { pollsFeature } from '~/features/polls'; import { createRedmineFeature } from '~/features/redmine'; -import { remindersFeature } from '~/features/reminders'; function legacyPanel(config: Config): LegacyPanel | undefined { const channelId = config.ROLE_SELECTION_CHANNEL_ID; @@ -73,6 +76,16 @@ export function compose(config: Config, log: Logger) { authz, defaultTimezone: config.DEFAULT_TIMEZONE, }); + const scheduler = createJobQueue(database.db); + const reminders = createReminderService({ + reminders: createReminderRepository(database.db), + scheduler, + messenger, + directory, + authz, + timezone: (guildId) => settings.timezone(guildId), + }); + const jobs: Array> = [...reminders.jobs]; const permissions = createPermissionService({ grants, directory, @@ -84,14 +97,14 @@ export function compose(config: Config, log: Logger) { roleCommands(roles), permissionCommands(permissions), settingsCommands(settings), - remindersFeature, + reminderCommands(reminders), announcementsFeature, eventsFeature, birthdaysFeature, pollsFeature, moviesFeature, ]; - const redmine = createRedmineFeature(config); + const redmine = createRedmineFeature(config, reminders); if (redmine) { features.push(redmine); @@ -99,7 +112,17 @@ export function compose(config: Config, log: Logger) { const registry = buildRegistry(features); - return { database, client, authz, registry }; + const runnerJobs = new Map(registry.jobs); + + for (const job of jobs) { + if (runnerJobs.has(job.type)) { + throw new Error(`Duplicate job type "${job.type}"`); + } + + runnerJobs.set(job.type, job); + } + + return { database, client, authz, registry, jobs: runnerJobs }; } export function createRegistry(config: Config, log: Logger): Registry { @@ -117,13 +140,13 @@ export async function startApp( config: Config, log: Logger, ): Promise<() => Promise> { - const { database, client, authz, registry } = compose(config, log); + const { database, client, authz, registry, jobs } = compose(config, log); try { await runMigrations(database.db); const scheduler = createScheduler( database.db, - registry.jobs, + jobs, log.child({ component: 'scheduler' }), ); const ready = await waitForReady(client, config.DISCORD_TOKEN); diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 2e3baaf..2f96ad9 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -6,3 +6,4 @@ export type * from './scheduler'; export type * from './secrets'; export type * from './settings'; export type * from './roles'; +export type * from './reminders'; diff --git a/src/core/ports/reminders.ts b/src/core/ports/reminders.ts new file mode 100644 index 0000000..4b558f9 --- /dev/null +++ b/src/core/ports/reminders.ts @@ -0,0 +1,28 @@ +import type { Recurrence } from '~/domain'; + +export type ReminderStatus = 'active' | 'done' | 'cancelled' | 'failed'; + +export type Reminder = { + id: number; + guildId: string; + userId: string; + channelId: string | null; + message: string; + runAt: Date; + recurrence: Recurrence | null; + timezone: string; + status: ReminderStatus; +}; + +export type NewReminder = Omit; + +export type ReminderChanges = Partial< + Pick & { failure: string } +>; + +export type ReminderRepository = { + insert: (reminder: NewReminder) => Promise; + find: (id: number) => Promise; + active: (guildId: string, userId: string) => Promise; + update: (id: number, changes: ReminderChanges) => Promise; +}; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index 7359b81..d1ff110 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -3,3 +3,4 @@ export * from './guard'; export * from './jobs'; export * from './settings'; export * from './roles'; +export * from './reminders'; diff --git a/src/core/services/reminders.ts b/src/core/services/reminders.ts new file mode 100644 index 0000000..db212c7 --- /dev/null +++ b/src/core/services/reminders.ts @@ -0,0 +1,200 @@ +import { z } from 'zod'; +import { + channelMention, + nextFutureOccurrence, + parseFutureWhen, + PermanentError, + recurrences, + requireZone, + UserError, + userMention, + type Actor, + type Recurrence, +} from '~/domain'; +import type { + Authorizer, + Directory, + Messenger, + NewReminder, + Reminder, + ReminderRepository, + Scheduler, +} from '~/core/ports'; +import { defineJob } from './jobs'; + +const jobKey = (id: number) => `reminder:${id}`; + +export type ReminderRequest = { + when: string; + message: string; + channelId?: string; + repeat?: string; + timezone?: string; +}; + +type Deps = { + reminders: ReminderRepository; + scheduler: Scheduler; + messenger: Messenger; + directory: Directory; + authz: Authorizer; + timezone: (guildId: string) => Promise; +}; + +export function createReminderService(deps: Deps) { + const { reminders, scheduler, messenger, directory, authz, timezone } = deps; + + const deliver = async (reminder: Reminder) => { + const text = `⏰ **Reminder:** ${reminder.message}`; + + if (reminder.channelId === null) { + await messenger.direct(reminder.userId, { content: text }); + + return; + } + + await messenger.send(reminder.channelId, { + content: `${userMention(reminder.userId)} ${text}`, + mentions: { users: [reminder.userId] }, + }); + }; + + const deliverJob = defineJob({ + type: 'reminders:deliver', + payload: z.object({ reminderId: z.number().int() }), + handle: async ({ reminderId }) => { + const reminder = await reminders.find(reminderId); + + if (reminder?.status !== 'active') { + return null; + } + + try { + await deliver(reminder); + } catch (error) { + if (error instanceof PermanentError) { + await reminders.update(reminder.id, { + status: 'failed', + failure: error.message, + }); + } + + throw error; + } + + if (reminder.recurrence === null) { + await reminders.update(reminder.id, { status: 'done' }); + + return null; + } + + const next = nextFutureOccurrence( + reminder.runAt, + reminder.recurrence, + reminder.timezone, + ); + + await reminders.update(reminder.id, { runAt: next }); + + return { rescheduleAt: next }; + }, + }); + + const queue = (reminder: Reminder) => + scheduler.schedule( + deliverJob, + { reminderId: reminder.id }, + { runAt: reminder.runAt, key: jobKey(reminder.id) }, + ); + + const schedule = async (input: NewReminder) => { + const reminder = await reminders.insert(input); + + await queue(reminder); + + return reminder; + }; + + const own = async (actor: Actor, id: number) => { + const reminder = await reminders.find(id); + + if ( + reminder?.guildId !== actor.guildId || + reminder.userId !== actor.userId || + reminder.status !== 'active' + ) { + throw new UserError(`You have no active reminder #${id}.`); + } + + return reminder; + }; + + return { + jobs: [deliverJob], + schedule, + create: async (actor: Actor, request: ReminderRequest) => { + if (request.channelId !== undefined) { + await authz.require(actor, 'reminder:channel'); + + if (!(await directory.canPost(actor, request.channelId))) { + throw new UserError( + `You cannot post in ${channelMention(request.channelId)} yourself.`, + ); + } + } + + const zone = + request.timezone === undefined + ? await timezone(actor.guildId) + : requireZone(request.timezone); + const recurrence: Recurrence | null = + recurrences.find((r) => r === request.repeat) ?? null; + + return schedule({ + guildId: actor.guildId, + userId: actor.userId, + channelId: request.channelId ?? null, + message: request.message, + runAt: parseFutureWhen(request.when, zone), + recurrence, + timezone: zone, + }); + }, + list: (actor: Actor) => reminders.active(actor.guildId, actor.userId), + edit: async ( + actor: Actor, + id: number, + changes: { when?: string; message?: string }, + ) => { + const reminder = await own(actor, id); + + if (changes.when === undefined && changes.message === undefined) { + throw new UserError('Give a new time or message.'); + } + + const updated = { + ...reminder, + message: changes.message ?? reminder.message, + runAt: + changes.when === undefined + ? reminder.runAt + : parseFutureWhen(changes.when, reminder.timezone), + }; + + await reminders.update(id, { + message: updated.message, + runAt: updated.runAt, + }); + await queue(updated); + + return updated; + }, + cancel: async (actor: Actor, id: number) => { + await own(actor, id); + await reminders.update(id, { status: 'cancelled' }); + await scheduler.cancel(jobKey(id)); + }, + }; +} + +export type ReminderService = ReturnType; diff --git a/src/features/redmine/index.ts b/src/features/redmine/index.ts index f8d9319..0f22d66 100644 --- a/src/features/redmine/index.ts +++ b/src/features/redmine/index.ts @@ -33,7 +33,7 @@ import { parseCalendarDay, zonedTime, } from '~/domain'; -import { createReminder } from '~/features/reminders'; +import type { ReminderService } from '~/core/services'; import { createNotificationJobs } from './notifications'; import { addSubscription, @@ -252,7 +252,10 @@ function issueEmbed(baseUrl: string, issue: RedmineIssue): EmbedBuilder { ); } -export function createRedmineFeature(config: Config): Feature | undefined { +export function createRedmineFeature( + config: Config, + reminders: ReminderService, +): Feature | undefined { const base = config.REDMINE_BASE_URL; if (base === undefined) { @@ -500,7 +503,7 @@ export function createRedmineFeature(config: Config): Feature | undefined { throw new UserError('That reminder time has already passed.'); } - const reminder = await createReminder(ctx, { + const reminder = await reminders.schedule({ guildId: interaction.guildId, userId: interaction.user.id, channelId: null, diff --git a/src/features/reminders/index.ts b/src/features/reminders/index.ts deleted file mode 100644 index 001b5d4..0000000 --- a/src/features/reminders/index.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { - toActor, - respond, - bySubcommand, - defineJob, - asJobError, -} from '~/infra/discord'; -import { - ChannelType, - InteractionContextType, - SlashCommandBuilder, - type SlashCommandIntegerOption, -} from 'discord.js'; -import { z } from 'zod'; -import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { - PermanentError, - UserError, - discordTime, - nextFutureOccurrence, - parseFutureWhen, - recurrences, - requireZone, -} from '~/domain'; -import type { Reminder } from './schema'; -import { - getReminder, - insertReminder, - listActiveReminders, - requireOwnReminder, - updateReminder, - type NewReminder, -} from './service'; - -const jobKey = (id: number) => `reminder:${id}`; - -async function deliver(ctx: AppContext, reminder: Reminder): Promise { - const text = `⏰ **Reminder:** ${reminder.message}`; - - if (reminder.channelId === null) { - const user = await ctx.client.users.fetch(reminder.userId); - - await user.send({ content: text }); - - return; - } - - const channel = await ctx.client.channels.fetch(reminder.channelId); - - if (channel?.isSendable() !== true) { - throw new PermanentError('Reminder channel is not a text channel'); - } - - await channel.send({ - content: `<@${reminder.userId}> ${text}`, - allowedMentions: { users: [reminder.userId] }, - }); -} - -export const deliverJob = defineJob({ - type: 'reminders:deliver', - payload: z.object({ reminderId: z.number().int() }), - handle: async ({ reminderId }, _info, ctx) => { - const reminder = await getReminder(ctx.db, reminderId); - - if (reminder?.status !== 'active') { - return null; - } - - try { - await deliver(ctx, reminder); - } catch (error) { - const jobError = asJobError(error); - - if (jobError instanceof PermanentError) { - await updateReminder(ctx.db, reminder.id, { - status: 'failed', - failure: jobError.message, - }); - } - - throw jobError; - } - - if (reminder.recurrence === null) { - await updateReminder(ctx.db, reminder.id, { status: 'done' }); - - return null; - } - - const next = nextFutureOccurrence( - reminder.runAt, - reminder.recurrence, - reminder.timezone, - ); - - await updateReminder(ctx.db, reminder.id, { runAt: next }); - - return { rescheduleAt: next }; - }, -}); - -export async function createReminder( - ctx: AppContext, - input: NewReminder, -): Promise { - const reminder = await insertReminder(ctx.db, input); - - await ctx.scheduler.schedule( - deliverJob, - { reminderId: reminder.id }, - { - runAt: reminder.runAt, - key: jobKey(reminder.id), - }, - ); - - return reminder; -} - -export function describeReminder(reminder: Reminder): string { - const where = reminder.channelId === null ? 'DM' : `<#${reminder.channelId}>`; - const repeat = reminder.recurrence === null ? '' : `, ${reminder.recurrence}`; - - return `#${reminder.id} ${discordTime(reminder.runAt, 'f')} (${where}${repeat}) — ${reminder.message.slice(0, 80)}`; -} - -const remindme = new SlashCommandBuilder() - .setName('remindme') - .setDescription('Set a reminder') - .setContexts(InteractionContextType.Guild) - .addStringOption((o) => - o - .setName('when') - .setDescription('e.g. 30m, 2h, 1d, 18:30, 2026-11-20 18:00') - .setRequired(true), - ) - .addStringOption((o) => - o - .setName('message') - .setDescription('What to remind about') - .setRequired(true) - .setMaxLength(1000), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Post in a channel instead of DM') - .addChannelTypes(ChannelType.GuildText), - ) - .addStringOption((o) => - o - .setName('repeat') - .setDescription('Repeat the reminder') - .addChoices(recurrences.map((r) => ({ name: r, value: r }))), - ) - .addStringOption((o) => - o.setName('timezone').setDescription('IANA timezone for absolute times'), - ); - -const idOption = (o: SlashCommandIntegerOption) => - o - .setName('id') - .setDescription('Reminder') - .setRequired(true) - .setAutocomplete(true); - -const manage = new SlashCommandBuilder() - .setName('reminders') - .setDescription('Manage your reminders') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub.setName('list').setDescription('List your active reminders'), - ) - .addSubcommand((sub) => - sub - .setName('edit') - .setDescription('Change a reminder') - .addIntegerOption(idOption) - .addStringOption((o) => o.setName('when').setDescription('New time')) - .addStringOption((o) => - o.setName('message').setDescription('New message').setMaxLength(1000), - ), - ) - .addSubcommand((sub) => - sub - .setName('cancel') - .setDescription('Cancel a reminder') - .addIntegerOption(idOption), - ); - -async function zoneFor( - interaction: CommandInteraction, - ctx: AppContext, -): Promise { - const explicit = interaction.options.getString('timezone'); - - return explicit === null - ? getGuildTimezone(ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE) - : requireZone(explicit); -} - -export const remindersFeature: Feature = { - name: 'reminders', - permissions: [ - { id: 'reminder:channel', description: 'Post reminders in channels' }, - ], - jobs: [deliverJob], - commands: [ - { - data: remindme.toJSON(), - execute: async (interaction, ctx) => { - const channel = interaction.options.getChannel('channel', false, [ - ChannelType.GuildText, - ]); - - if (channel) { - await ctx.authz.require( - toActor(interaction.member), - 'reminder:channel', - ); - } - - const timezone = await zoneFor(interaction, ctx); - const reminder = await createReminder(ctx, { - guildId: interaction.guildId, - userId: interaction.user.id, - channelId: channel?.id ?? null, - message: interaction.options.getString('message', true), - runAt: parseFutureWhen( - interaction.options.getString('when', true), - timezone, - ), - recurrence: - recurrences.find( - (r) => r === interaction.options.getString('repeat'), - ) ?? null, - timezone, - }); - const note = channel - ? '' - : ' Make sure you allow DMs from server members.'; - - await respond( - interaction, - `Reminder set: ${describeReminder(reminder)}.${note}`, - ); - }, - }, - { - data: manage.toJSON(), - execute: bySubcommand({ - list: async (interaction, ctx) => { - const active = await listActiveReminders( - ctx.db, - interaction.guildId, - interaction.user.id, - ); - - await respond( - interaction, - active.length === 0 - ? 'You have no active reminders.' - : active.map((reminder) => describeReminder(reminder)).join('\n'), - ); - }, - edit: async (interaction, ctx) => { - const reminder = await requireOwnReminder( - ctx.db, - interaction.guildId, - interaction.user.id, - interaction.options.getInteger('id', true), - ); - const when = interaction.options.getString('when'); - const message = - interaction.options.getString('message') ?? reminder.message; - - if (when === null && message === reminder.message) { - throw new UserError('Give a new time or message.'); - } - - const runAt = - when === null - ? reminder.runAt - : parseFutureWhen(when, reminder.timezone); - - await updateReminder(ctx.db, reminder.id, { message, runAt }); - await ctx.scheduler.schedule( - deliverJob, - { reminderId: reminder.id }, - { runAt, key: jobKey(reminder.id) }, - ); - await respond( - interaction, - `Updated: ${describeReminder({ ...reminder, message, runAt })}`, - ); - }, - cancel: async (interaction, ctx) => { - const reminder = await requireOwnReminder( - ctx.db, - interaction.guildId, - interaction.user.id, - interaction.options.getInteger('id', true), - ); - - await updateReminder(ctx.db, reminder.id, { status: 'cancelled' }); - await ctx.scheduler.cancel(jobKey(reminder.id)); - await respond(interaction, `Cancelled reminder #${reminder.id}.`); - }, - }), - autocomplete: async (interaction, ctx) => { - const active = await listActiveReminders( - ctx.db, - interaction.guildId, - interaction.user.id, - ); - - await interaction.respond( - active.map((r) => ({ - name: `#${r.id} ${r.message}`.slice(0, 100), - value: r.id, - })), - ); - }, - }, - ], -}; diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index 640cb99..8270b66 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -6,3 +6,5 @@ export * from './permissions/repo'; export * from './settings/repo'; export * from './roles/model'; export * from './roles/repo'; +export * from './reminders/model'; +export * from './reminders/repo'; diff --git a/src/features/reminders/schema.ts b/src/infra/db/reminders/model.ts similarity index 100% rename from src/features/reminders/schema.ts rename to src/infra/db/reminders/model.ts diff --git a/src/features/reminders/service.ts b/src/infra/db/reminders/repo.ts similarity index 72% rename from src/features/reminders/service.ts rename to src/infra/db/reminders/repo.ts index 0f93349..26295a6 100644 --- a/src/features/reminders/service.ts +++ b/src/infra/db/reminders/repo.ts @@ -1,22 +1,12 @@ import { and, asc, count, eq } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; +import type { Db } from '../client'; import { UserError } from '~/domain'; -import type { Recurrence } from '~/domain'; -import { reminders, type Reminder } from './schema'; +import type { NewReminder, ReminderRepository } from '~/core/ports'; +import { reminders, type Reminder } from './model'; export const maxActivePerUser = 25; export const maxMessageLength = 1000; -export type NewReminder = { - guildId: string; - userId: string; - channelId: string | null; - message: string; - runAt: Date; - recurrence: Recurrence | null; - timezone: string; -}; - export async function insertReminder( db: Db, input: NewReminder, @@ -91,21 +81,11 @@ export async function updateReminder( await db.update(reminders).set(changes).where(eq(reminders.id, id)); } -export async function requireOwnReminder( - db: Db, - guildId: string, - userId: string, - id: number, -): Promise { - const reminder = await getReminder(db, id); - - if ( - reminder?.guildId !== guildId || - reminder.userId !== userId || - reminder.status !== 'active' - ) { - throw new UserError(`You have no active reminder #${id}.`); - } - - return reminder; +export function createReminderRepository(db: Db): ReminderRepository { + return { + insert: (reminder) => insertReminder(db, reminder), + find: (id) => getReminder(db, id), + active: (guildId, userId) => listActiveReminders(db, guildId, userId), + update: (id, changes) => updateReminder(db, id, changes), + }; } diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index 84adbca..47c2f99 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -1,3 +1,4 @@ export * from './permissions'; export * from './settings'; export * from './roles'; +export * from './reminders'; diff --git a/src/infra/discord/commands/reminders.ts b/src/infra/discord/commands/reminders.ts new file mode 100644 index 0000000..1dd4d30 --- /dev/null +++ b/src/infra/discord/commands/reminders.ts @@ -0,0 +1,168 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, + type SlashCommandIntegerOption, +} from 'discord.js'; +import type { Reminder } from '~/core/ports'; +import type { ReminderService } from '~/core/services'; +import { channelMention, discordTime, recurrences } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand } from '../define'; +import type { Feature } from '../module'; +import { respond } from '../router'; + +export function describeReminder(reminder: Reminder): string { + const where = + reminder.channelId === null ? 'DM' : channelMention(reminder.channelId); + const repeat = reminder.recurrence === null ? '' : `, ${reminder.recurrence}`; + + return `#${reminder.id} ${discordTime(reminder.runAt, 'f')} (${where}${repeat}) — ${reminder.message.slice(0, 80)}`; +} + +const remindme = new SlashCommandBuilder() + .setName('remindme') + .setDescription('Set a reminder') + .setContexts(InteractionContextType.Guild) + .addStringOption((o) => + o + .setName('when') + .setDescription('e.g. 30m, 2h, 1d, 18:30, 2026-11-20 18:00') + .setRequired(true), + ) + .addStringOption((o) => + o + .setName('message') + .setDescription('What to remind about') + .setRequired(true) + .setMaxLength(1000), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Post in a channel instead of DM') + .addChannelTypes(ChannelType.GuildText), + ) + .addStringOption((o) => + o + .setName('repeat') + .setDescription('Repeat the reminder') + .addChoices(recurrences.map((r) => ({ name: r, value: r }))), + ) + .addStringOption((o) => + o.setName('timezone').setDescription('IANA timezone for absolute times'), + ); + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Reminder') + .setRequired(true) + .setAutocomplete(true); + +const manage = new SlashCommandBuilder() + .setName('reminders') + .setDescription('Manage your reminders') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub.setName('list').setDescription('List your active reminders'), + ) + .addSubcommand((sub) => + sub + .setName('edit') + .setDescription('Change a reminder') + .addIntegerOption(idOption) + .addStringOption((o) => o.setName('when').setDescription('New time')) + .addStringOption((o) => + o.setName('message').setDescription('New message').setMaxLength(1000), + ), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel a reminder') + .addIntegerOption(idOption), + ); + +export function reminderCommands(reminders: ReminderService): Feature { + return { + name: 'reminders', + permissions: [ + { id: 'reminder:channel', description: 'Post reminders in channels' }, + ], + commands: [ + { + data: remindme.toJSON(), + execute: async (interaction) => { + const channel = interaction.options.getChannel('channel', false, [ + ChannelType.GuildText, + ]); + const repeat = interaction.options.getString('repeat'); + const timezone = interaction.options.getString('timezone'); + const reminder = await reminders.create(toActor(interaction.member), { + when: interaction.options.getString('when', true), + message: interaction.options.getString('message', true), + ...(channel && { channelId: channel.id }), + ...(repeat !== null && { repeat }), + ...(timezone !== null && { timezone }), + }); + const note = channel + ? '' + : ' Make sure you allow DMs from server members.'; + + await respond( + interaction, + `Reminder set: ${describeReminder(reminder)}.${note}`, + ); + }, + }, + { + data: manage.toJSON(), + execute: bySubcommand({ + list: async (interaction) => { + const active = await reminders.list(toActor(interaction.member)); + + await respond( + interaction, + active.length === 0 + ? 'You have no active reminders.' + : active + .map((reminder) => describeReminder(reminder)) + .join('\n'), + ); + }, + edit: async (interaction) => { + const when = interaction.options.getString('when'); + const message = interaction.options.getString('message'); + const updated = await reminders.edit( + toActor(interaction.member), + interaction.options.getInteger('id', true), + { + ...(when !== null && { when }), + ...(message !== null && { message }), + }, + ); + + await respond(interaction, `Updated: ${describeReminder(updated)}`); + }, + cancel: async (interaction) => { + const id = interaction.options.getInteger('id', true); + + await reminders.cancel(toActor(interaction.member), id); + await respond(interaction, `Cancelled reminder #${id}.`); + }, + }), + autocomplete: async (interaction) => { + const active = await reminders.list(toActor(interaction.member)); + + await interaction.respond( + active.map((r) => ({ + name: `#${r.id} ${r.message}`.slice(0, 100), + value: r.id, + })), + ); + }, + }, + ], + }; +} diff --git a/src/infra/scheduler/index.ts b/src/infra/scheduler/index.ts index 3521c5c..252b474 100644 --- a/src/infra/scheduler/index.ts +++ b/src/infra/scheduler/index.ts @@ -1 +1,2 @@ export * from './scheduler'; +export * from './queue'; diff --git a/src/infra/scheduler/queue.ts b/src/infra/scheduler/queue.ts new file mode 100644 index 0000000..0226b40 --- /dev/null +++ b/src/infra/scheduler/queue.ts @@ -0,0 +1,17 @@ +import type { Scheduler } from '~/core/ports'; +import { cancelJob, upsertJob, type Db } from '~/infra/db'; + +export function createJobQueue(db: Db): Scheduler { + return { + schedule: async (job, payload, options) => { + await upsertJob(db, { + type: job.type, + payload, + runAt: options.runAt, + key: options.key, + maxAttempts: options.maxAttempts ?? job.maxAttempts, + }); + }, + cancel: (key) => cancelJob(db, key), + }; +} diff --git a/tests/core/services/reminders.test.ts b/tests/core/services/reminders.test.ts new file mode 100644 index 0000000..a7a4961 --- /dev/null +++ b/tests/core/services/reminders.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Scheduler } from '~/core/ports'; +import { createReminderService } from '~/core/services'; +import { PermanentError, UserError } from '~/domain'; +import { createReminderRepository, maxActivePerUser } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + denyAll, + fakeDirectory, + fakeMessenger, +} from '../../fakes'; + +const info = { id: 1, runAt: new Date(), attempt: 1 }; + +describe.skipIf(noDatabase)('reminder service', () => { + const setup = (authz = allowAll) => { + const { messenger } = fakeMessenger(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const repository = createReminderRepository(testDb()); + const service = createReminderService({ + reminders: repository, + scheduler, + messenger, + directory: fakeDirectory(), + authz, + timezone: async () => 'Europe/Tallinn', + }); + const [deliver] = service.jobs; + + return { + service, + messenger, + scheduler, + repository, + deliver, + member: actor({ guildId: snowflake(), userId: snowflake() }), + }; + }; + + it('schedules a job keyed to the reminder', async () => { + const { service, scheduler, member } = setup(); + const reminder = await service.create(member, { + when: '10m', + message: 'stand-up', + }); + + expect(scheduler.schedule).toHaveBeenCalledWith( + expect.objectContaining({ type: 'reminders:deliver' }), + { reminderId: reminder.id }, + { + runAt: reminder.runAt, + key: `reminder:${reminder.id}`, + }, + ); + }); + + it('delivers one-off reminders by DM and completes them', async () => { + const { service, messenger, repository, deliver, member } = setup(); + const reminder = await service.create(member, { + when: '10m', + message: 'stand-up', + }); + + expect(await deliver?.run({ reminderId: reminder.id }, info)).toBeNull(); + expect(messenger.direct).toHaveBeenCalledWith(member.userId, { + content: '⏰ **Reminder:** stand-up', + }); + expect((await repository.find(reminder.id))?.status).toBe('done'); + }); + + it('reschedules recurring reminders into the future', async () => { + const { service, repository, deliver, member } = setup(); + const reminder = await service.schedule({ + guildId: member.guildId, + userId: member.userId, + channelId: null, + message: 'daily', + runAt: new Date(Date.now() - 3 * 86_400_000), + recurrence: 'daily', + timezone: 'Europe/Tallinn', + }); + const outcome = await deliver?.run({ reminderId: reminder.id }, info); + + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); + expect(outcome?.rescheduleAt.getTime()).toBeLessThanOrEqual( + Date.now() + 86_400_000, + ); + expect((await repository.find(reminder.id))?.status).toBe('active'); + }); + + it('fails permanently when DMs are closed', async () => { + const { service, messenger, repository, deliver, member } = setup(); + + messenger.direct.mockRejectedValue( + new PermanentError('Cannot send messages to this user'), + ); + + const reminder = await service.create(member, { + when: '10m', + message: 'x', + }); + + await expect( + deliver?.run({ reminderId: reminder.id }, info), + ).rejects.toBeInstanceOf(PermanentError); + expect((await repository.find(reminder.id))?.status).toBe('failed'); + }); + + it('skips cancelled reminders and only lets owners manage them', async () => { + const { service, messenger, deliver, member } = setup(); + const reminder = await service.create(member, { + when: '10m', + message: 'x', + }); + + await expect( + service.cancel(actor({ guildId: member.guildId }), reminder.id), + ).rejects.toBeInstanceOf(UserError); + await service.cancel(member, reminder.id); + await deliver?.run({ reminderId: reminder.id }, info); + expect(messenger.direct).not.toHaveBeenCalled(); + }); + + it('requires permission for channel reminders', async () => { + const { service, member } = setup(denyAll); + + await expect( + service.create(member, { when: '10m', message: 'x', channelId: 'c' }), + ).rejects.toThrow('denied'); + }); + + it('limits active reminders per user and message length', async () => { + const { service, member } = setup(); + + for (let n = 0; n < maxActivePerUser; n++) { + await service.create(member, { when: '1h', message: 'x' }); + } + + await expect( + service.create(member, { when: '1h', message: 'x' }), + ).rejects.toBeInstanceOf(UserError); + await expect( + service.create(actor({ guildId: snowflake() }), { + when: '1h', + message: 'x'.repeat(1001), + }), + ).rejects.toThrow('at most'); + }); +}); diff --git a/tests/features/redmine/redmine.test.ts b/tests/features/redmine/redmine.test.ts index 7e206c4..8460588 100644 --- a/tests/features/redmine/redmine.test.ts +++ b/tests/features/redmine/redmine.test.ts @@ -1,3 +1,4 @@ +import type { ReminderService } from '~/core/services'; import { randomBytes } from 'node:crypto'; import { pino } from 'pino'; import { describe, expect, it, vi } from 'vitest'; @@ -105,14 +106,22 @@ describe('issueNotifications', () => { describe('createRedmineFeature', () => { it('is disabled without a base URL and requires an encryption key with one', () => { - expect(createRedmineFeature({} as Config)).toBeUndefined(); + expect( + createRedmineFeature({} as Config, {} as ReminderService), + ).toBeUndefined(); expect(() => - createRedmineFeature({ REDMINE_BASE_URL: 'https://r' } as Config), + createRedmineFeature( + { REDMINE_BASE_URL: 'https://r' } as Config, + {} as ReminderService, + ), ).toThrow('CREDENTIAL_ENCRYPTION_KEY'); - const feature = createRedmineFeature({ - REDMINE_BASE_URL: 'https://r', - CREDENTIAL_ENCRYPTION_KEY: randomBytes(32).toString('base64'), - } as Config); + const feature = createRedmineFeature( + { + REDMINE_BASE_URL: 'https://r', + CREDENTIAL_ENCRYPTION_KEY: randomBytes(32).toString('base64'), + } as Config, + {} as ReminderService, + ); expect(feature?.jobs).toEqual([]); }); diff --git a/tests/features/reminders/reminders.test.ts b/tests/features/reminders/reminders.test.ts deleted file mode 100644 index 34095de..0000000 --- a/tests/features/reminders/reminders.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; -import { pino } from 'pino'; -import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { PermanentError, UserError } from '~/domain'; -import { createReminder, deliverJob } from '~/features/reminders'; -import { - getReminder, - insertReminder, - maxActivePerUser, -} from '~/features/reminders/service'; - -const cannotDm = new DiscordAPIError( - { - code: RESTJSONErrorCodes.CannotSendMessagesToThisUser, - message: 'Cannot send messages to this user', - }, - RESTJSONErrorCodes.CannotSendMessagesToThisUser, - 403, - 'POST', - '/channels/x/messages', - {}, -); - -function context() { - const send = vi.fn(async () => undefined); - const schedule = vi.fn(async () => undefined); - const ctx = { - db: noDatabase ? undefined : testDb(), - log: pino({ level: 'silent' }), - client: { users: { fetch: async () => ({ send }) } }, - scheduler: { schedule, cancel: vi.fn() }, - } as unknown as AppContext; - - return { ctx, send, schedule }; -} - -const info = { id: 1, runAt: new Date(), attempt: 1 }; -const base = () => ({ - guildId: snowflake(), - userId: snowflake(), - channelId: null, - message: 'stand-up', - runAt: new Date(Date.now() + 60_000), - recurrence: null, - timezone: 'Europe/Tallinn', -}); - -describe.skipIf(noDatabase)('reminders', () => { - it('schedules a job keyed to the reminder', async () => { - const { ctx, schedule } = context(); - const reminder = await createReminder(ctx, base()); - - expect(schedule).toHaveBeenCalledWith( - deliverJob, - { reminderId: reminder.id }, - { - runAt: reminder.runAt, - key: `reminder:${reminder.id}`, - }, - ); - }); - - it('delivers one-off reminders by DM and completes them', async () => { - const { ctx, send } = context(); - const reminder = await insertReminder(ctx.db, base()); - - expect( - await deliverJob.run({ reminderId: reminder.id }, info, ctx), - ).toBeNull(); - expect(send).toHaveBeenCalledWith({ content: '⏰ **Reminder:** stand-up' }); - expect((await getReminder(ctx.db, reminder.id))?.status).toBe('done'); - }); - - it('reschedules recurring reminders into the future', async () => { - const { ctx } = context(); - const reminder = await insertReminder(ctx.db, { - ...base(), - runAt: new Date(Date.now() - 3 * 86_400_000), - recurrence: 'daily', - }); - const outcome = await deliverJob.run( - { reminderId: reminder.id }, - info, - ctx, - ); - - expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); - expect(outcome?.rescheduleAt.getTime()).toBeLessThanOrEqual( - Date.now() + 86_400_000, - ); - expect((await getReminder(ctx.db, reminder.id))?.status).toBe('active'); - }); - - it('fails permanently when DMs are closed', async () => { - const { ctx, send } = context(); - - send.mockRejectedValue(cannotDm); - const reminder = await insertReminder(ctx.db, base()); - - await expect( - deliverJob.run({ reminderId: reminder.id }, info, ctx), - ).rejects.toBeInstanceOf(PermanentError); - expect((await getReminder(ctx.db, reminder.id))?.status).toBe('failed'); - }); - - it('skips cancelled reminders', async () => { - const { ctx, send } = context(); - const reminder = await insertReminder(ctx.db, base()); - const { updateReminder } = await import('~/features/reminders/service'); - - await updateReminder(ctx.db, reminder.id, { status: 'cancelled' }); - await deliverJob.run({ reminderId: reminder.id }, info, ctx); - expect(send).not.toHaveBeenCalled(); - }); - - it('limits active reminders per user and message length', async () => { - const { ctx } = context(); - const input = base(); - - for (let n = 0; n < maxActivePerUser; n++) { - await insertReminder(ctx.db, input); - } - - await expect(insertReminder(ctx.db, input)).rejects.toBeInstanceOf( - UserError, - ); - await expect( - insertReminder(ctx.db, { ...base(), message: 'x'.repeat(1001) }), - ).rejects.toThrow('at most'); - }); -}); From d44318cf9047877fbd49fc4a84c4e8441d69e571 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 19:43:32 +0200 Subject: [PATCH 025/199] refactor(announcements): announcement service with multi-role mentions --- drizzle/0001_announcement_mentions.sql | 5 + drizzle/meta/0001_snapshot.json | 1749 +++++++++++++++++ drizzle/meta/_journal.json | 9 +- src/app.ts | 20 +- src/core/ports/announcements.ts | 61 + src/core/ports/index.ts | 1 + src/core/services/announcements.ts | 350 ++++ src/core/services/index.ts | 1 + src/features/announcements/index.ts | 568 ------ .../db/announcements/model.ts} | 3 +- .../db/announcements/repo.ts} | 74 +- src/infra/db/index.ts | 2 + src/infra/discord/commands/announcements.ts | 305 +++ src/infra/discord/commands/index.ts | 1 + tests/core/services/announcements.test.ts | 182 ++ .../announcements/announcements.test.ts | 133 -- 16 files changed, 2711 insertions(+), 753 deletions(-) create mode 100644 drizzle/0001_announcement_mentions.sql create mode 100644 drizzle/meta/0001_snapshot.json create mode 100644 src/core/ports/announcements.ts create mode 100644 src/core/services/announcements.ts delete mode 100644 src/features/announcements/index.ts rename src/{features/announcements/schema.ts => infra/db/announcements/model.ts} (88%) rename src/{features/announcements/service.ts => infra/db/announcements/repo.ts} (51%) create mode 100644 src/infra/discord/commands/announcements.ts create mode 100644 tests/core/services/announcements.test.ts delete mode 100644 tests/features/announcements/announcements.test.ts diff --git a/drizzle/0001_announcement_mentions.sql b/drizzle/0001_announcement_mentions.sql new file mode 100644 index 0000000..9cbe912 --- /dev/null +++ b/drizzle/0001_announcement_mentions.sql @@ -0,0 +1,5 @@ +ALTER TABLE "announcements" ADD COLUMN "mention_role_ids" text[] DEFAULT '{}' NOT NULL;--> statement-breakpoint +ALTER TABLE "announcements" ADD COLUMN "mention_everyone" boolean DEFAULT false NOT NULL;--> statement-breakpoint +UPDATE "announcements" SET "mention_everyone" = true WHERE "mention_role_id" = "guild_id";--> statement-breakpoint +UPDATE "announcements" SET "mention_role_ids" = ARRAY["mention_role_id"] WHERE "mention_role_id" IS NOT NULL AND "mention_role_id" <> "guild_id";--> statement-breakpoint +ALTER TABLE "announcements" DROP COLUMN "mention_role_id"; \ No newline at end of file diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json new file mode 100644 index 0000000..2b7b7b2 --- /dev/null +++ b/drizzle/meta/0001_snapshot.json @@ -0,0 +1,1749 @@ +{ + "id": "cf5229cd-07d2-448d-b523-395d91e5660c", + "prevId": "80864efc-f688-4b13-b99f-0388ac6e9a92", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embed": { + "name": "embed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_jobs": { + "name": "scheduled_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "job_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "scheduled_jobs_due_idx": { + "name": "scheduled_jobs_due_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_jobs_lease_idx": { + "name": "scheduled_jobs_lease_idx", + "columns": [ + { + "expression": "locked_until", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "scheduled_jobs_key_unique": { + "name": "scheduled_jobs_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guild_settings": { + "name": "guild_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_links": { + "name": "redmine_links", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "redmine_user_id": { + "name": "redmine_user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redmine_login": { + "name": "redmine_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "linked_at": { + "name": "linked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "publishing", + "published", + "cancelled", + "failed" + ] + }, + "public.job_status": { + "name": "job_status", + "schema": "public", + "values": [ + "pending", + "running", + "done", + "failed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 62af31b..9121daa 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1794742755691, "tag": "0000_init", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1794764495086, + "tag": "0001_announcement_mentions", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index feac805..eebd089 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,6 +1,7 @@ import { Events, type Client } from 'discord.js'; import type { Config } from '~/config'; import { + announcementCommands, createClient, createInteractionHandler, buildRegistry, @@ -12,6 +13,7 @@ import { settingsCommands, } from '~/infra/discord'; import { + createAnnouncementService, createAuthorizer, createPermissionService, createReminderService, @@ -22,16 +24,16 @@ import { import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; import { createJobQueue, createScheduler } from '~/infra/scheduler'; -import type { Job } from '~/core/ports'; +import { systemClock, type Job } from '~/core/ports'; import { connectDatabase, + createAnnouncementRepository, createGrantRepository, createReminderRepository, createRolePanelRepository, createSettingsRepository, runMigrations, } from '~/infra/db'; -import { announcementsFeature } from '~/features/announcements'; import { birthdaysFeature } from '~/features/birthdays'; import { eventsFeature } from '~/features/events'; import { moviesFeature } from '~/features/movies'; @@ -85,7 +87,17 @@ export function compose(config: Config, log: Logger) { authz, timezone: (guildId) => settings.timezone(guildId), }); - const jobs: Array> = [...reminders.jobs]; + const announcements = createAnnouncementService({ + announcements: createAnnouncementRepository(database.db), + scheduler, + messenger, + directory, + authz, + log: log.child({ service: 'announcements' }), + clock: systemClock, + timezone: (guildId) => settings.timezone(guildId), + }); + const jobs: Array> = [...reminders.jobs, ...announcements.jobs]; const permissions = createPermissionService({ grants, directory, @@ -98,7 +110,7 @@ export function compose(config: Config, log: Logger) { permissionCommands(permissions), settingsCommands(settings), reminderCommands(reminders), - announcementsFeature, + announcementCommands(announcements), eventsFeature, birthdaysFeature, pollsFeature, diff --git a/src/core/ports/announcements.ts b/src/core/ports/announcements.ts new file mode 100644 index 0000000..f96506f --- /dev/null +++ b/src/core/ports/announcements.ts @@ -0,0 +1,61 @@ +export type AnnouncementStatus = + 'draft' | 'scheduled' | 'publishing' | 'published' | 'cancelled' | 'failed'; + +export type Announcement = { + id: number; + guildId: string; + authorId: string; + channelId: string; + title: string | null; + content: string; + embed: boolean; + mentionRoleIds: string[]; + mentionEveryone: boolean; + status: AnnouncementStatus; + scheduledAt: Date | null; + publishedAt: Date | null; + messageId: string | null; + failure: string | null; + createdAt: Date; +}; + +export type NewAnnouncement = Pick< + Announcement, + | 'guildId' + | 'authorId' + | 'channelId' + | 'title' + | 'content' + | 'embed' + | 'mentionRoleIds' + | 'mentionEveryone' +>; + +export type AnnouncementChanges = Partial< + Omit +> & { status: AnnouncementStatus }; + +export type AnnouncementRepository = { + insert: (announcement: NewAnnouncement) => Promise; + find: (id: number) => Promise; + list: (guildId: string, limit?: number) => Promise; + transition: ( + id: number, + from: readonly AnnouncementStatus[], + changes: AnnouncementChanges, + ) => Promise; + update: ( + id: number, + changes: Partial< + Pick< + Announcement, + | 'title' + | 'content' + | 'channelId' + | 'embed' + | 'mentionRoleIds' + | 'mentionEveryone' + > + >, + ) => Promise; +}; diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 2f96ad9..9943dee 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -7,3 +7,4 @@ export type * from './secrets'; export type * from './settings'; export type * from './roles'; export type * from './reminders'; +export type * from './announcements'; diff --git a/src/core/services/announcements.ts b/src/core/services/announcements.ts new file mode 100644 index 0000000..42affce --- /dev/null +++ b/src/core/services/announcements.ts @@ -0,0 +1,350 @@ +import { z } from 'zod'; +import { + channelMention, + maxContentLength, + parseFutureWhen, + PermanentError, + requireMentionable, + roleMention, + UserError, + type Actor, + type Message, +} from '~/domain'; +import type { + Announcement, + AnnouncementRepository, + AnnouncementStatus, + Authorizer, + Clock, + Directory, + Logger, + Messenger, + Scheduler, +} from '~/core/ports'; +import { guard } from './guard'; +import { defineJob } from './jobs'; + +const jobKey = (id: number) => `announcement:${id}`; +const maxLatenessMs = 60 * 60 * 1000; +const accent = 0xff_ac_1c; +const reopenable: AnnouncementStatus[] = ['draft', 'scheduled', 'failed']; + +export const maxAnnouncementLength = 4000; + +export type AnnouncementDraft = { + channelId: string; + title?: string; + content: string; + embed?: boolean; + mentionRoleIds?: readonly string[]; + mentionEveryone?: boolean; +}; + +export function announcementView(announcement: Announcement): Message { + const pings = [ + ...(announcement.mentionEveryone ? ['@everyone'] : []), + ...announcement.mentionRoleIds.map((id) => roleMention(id)), + ].join(' '); + const mentions = { + everyone: announcement.mentionEveryone, + roles: announcement.mentionRoleIds, + }; + + if (announcement.embed) { + return { + ...(pings !== '' && { content: pings }), + embeds: [ + { + ...(announcement.title !== null && { title: announcement.title }), + description: announcement.content, + color: accent, + }, + ], + mentions, + }; + } + + const heading = + announcement.title === null ? '' : `**${announcement.title}**\n`; + const content = [pings, `${heading}${announcement.content}`] + .filter(Boolean) + .join('\n'); + + if (content.length > maxContentLength) { + throw new UserError( + 'Plain announcements are limited to 2000 characters; use an embed.', + ); + } + + return { content, mentions }; +} + +type Deps = { + announcements: AnnouncementRepository; + scheduler: Scheduler; + messenger: Messenger; + directory: Directory; + authz: Authorizer; + log: Logger; + clock: Clock; + timezone: (guildId: string) => Promise; +}; + +export function createAnnouncementService(deps: Deps) { + const { announcements, scheduler, messenger, directory, authz, log, clock } = + deps; + + const requireOwnGuild = async (actor: Actor, id: number) => { + const announcement = await announcements.find(id); + + if (announcement?.guildId !== actor.guildId) { + throw new UserError(`Announcement #${id} does not exist.`); + } + + return announcement; + }; + + const requireEditable = async (actor: Actor, id: number) => { + const announcement = await requireOwnGuild(actor, id); + + if (announcement.authorId !== actor.userId) { + await authz.require(actor, 'announcement:publish'); + } + + return announcement; + }; + + const checkTargets = async ( + actor: Actor, + draft: Pick< + AnnouncementDraft, + 'channelId' | 'mentionRoleIds' | 'mentionEveryone' + >, + ) => { + if (!(await directory.canPost(actor, draft.channelId))) { + throw new UserError( + `You cannot post in ${channelMention(draft.channelId)} yourself.`, + ); + } + + if (draft.mentionEveryone === true && !actor.mentionEveryone) { + throw new UserError('You may not mention everyone.'); + } + + const roles = await Promise.all( + (draft.mentionRoleIds ?? []).map((id) => + directory.role(actor.guildId, id), + ), + ); + + for (const role of roles) { + if (!role) { + throw new UserError('One of the mentioned roles no longer exists.'); + } + + requireMentionable(actor, role); + } + }; + + const publish = async (id: number, from: readonly AnnouncementStatus[]) => { + const claimed = await announcements.transition(id, from, { + status: 'publishing', + }); + + if (!claimed) { + throw new UserError( + `Announcement #${id} cannot be published in its current state.`, + ); + } + + try { + const sent = await messenger.send( + claimed.channelId, + announcementView(claimed), + ); + const published = await announcements.transition(id, ['publishing'], { + status: 'published', + publishedAt: clock.now(), + messageId: sent.messageId, + failure: null, + }); + + log.info( + { announcementId: id, messageId: sent.messageId }, + 'Announcement published', + ); + + return published ?? claimed; + } catch (error) { + const permanent = + error instanceof PermanentError || error instanceof UserError; + const message = error instanceof Error ? error.message : String(error); + + await announcements.transition(id, ['publishing'], { + status: permanent ? 'failed' : (from[0] ?? 'draft'), + failure: message, + }); + + throw error; + } + }; + + const publishJob = defineJob({ + type: 'announcements:publish', + payload: z.object({ announcementId: z.number().int() }), + handle: async ({ announcementId }) => { + const announcement = await announcements.find(announcementId); + + if (announcement?.status !== 'scheduled') { + return; + } + + const due = announcement.scheduledAt ?? announcement.createdAt; + + if (clock.now().getTime() - due.getTime() > maxLatenessMs) { + await announcements.transition(announcementId, ['scheduled'], { + status: 'failed', + failure: + 'Skipped: the scheduled time passed while the bot was offline', + }); + log.warn({ announcementId }, 'Skipped stale scheduled announcement'); + + return; + } + + await publish(announcementId, ['scheduled']); + }, + }); + + const validate = (draft: AnnouncementDraft) => { + if ( + draft.content.trim() === '' || + draft.content.length > maxAnnouncementLength + ) { + throw new UserError(`Write 1–${maxAnnouncementLength} characters.`); + } + }; + + return { + jobs: [publishJob], + view: announcementView, + list: (guildId: string) => announcements.list(guildId), + get: requireOwnGuild, + draft: guard( + authz, + 'announcement:create', + async (actor, draft: AnnouncementDraft) => { + validate(draft); + await checkTargets(actor, draft); + + const title = draft.title?.trim() ?? ''; + const created = await announcements.insert({ + guildId: actor.guildId, + authorId: actor.userId, + channelId: draft.channelId, + title: title === '' ? null : title, + content: draft.content, + embed: draft.embed ?? true, + mentionRoleIds: [...(draft.mentionRoleIds ?? [])], + mentionEveryone: draft.mentionEveryone ?? false, + }); + + announcementView(created); + + return created; + }, + ), + edit: async ( + actor: Actor, + id: number, + changes: { title?: string; content: string }, + ) => { + const announcement = await requireEditable(actor, id); + + validate({ channelId: announcement.channelId, content: changes.content }); + + const title = changes.title?.trim() ?? ''; + const updated = { + ...announcement, + title: title === '' ? null : title, + content: changes.content, + }; + + announcementView(updated); + await announcements.update(id, { + title: updated.title, + content: updated.content, + }); + + if ( + announcement.status === 'published' && + announcement.messageId !== null + ) { + await messenger.edit(announcement.channelId, announcement.messageId, { + ...announcementView(updated), + mentions: {}, + }); + } + + return updated; + }, + publish: guard(authz, 'announcement:publish', async (actor, id: number) => { + await requireOwnGuild(actor, id); + await scheduler.cancel(jobKey(id)); + + return publish(id, reopenable); + }), + schedule: guard( + authz, + 'announcement:schedule', + async (actor, id: number, when: string) => { + const announcement = await requireOwnGuild(actor, id); + const runAt = parseFutureWhen( + when, + await deps.timezone(actor.guildId), + clock.now(), + ); + + await checkTargets(actor, announcement); + + const scheduled = await announcements.transition(id, reopenable, { + status: 'scheduled', + scheduledAt: runAt, + failure: null, + }); + + if (!scheduled) { + throw new UserError( + `Announcement #${id} cannot be scheduled in its current state.`, + ); + } + + await scheduler.schedule( + publishJob, + { announcementId: id }, + { runAt, key: jobKey(id) }, + ); + + return scheduled; + }, + ), + cancel: async (actor: Actor, id: number) => { + const announcement = await requireEditable(actor, id); + const cancelled = await announcements.transition(id, reopenable, { + status: 'cancelled', + }); + + if (!cancelled) { + throw new UserError( + `Announcement #${id} is already ${announcement.status}.`, + ); + } + + await scheduler.cancel(jobKey(id)); + + return cancelled; + }, + }; +} + +export type AnnouncementService = ReturnType; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index d1ff110..4f6a9ad 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -4,3 +4,4 @@ export * from './jobs'; export * from './settings'; export * from './roles'; export * from './reminders'; +export * from './announcements'; diff --git a/src/features/announcements/index.ts b/src/features/announcements/index.ts deleted file mode 100644 index 77c6298..0000000 --- a/src/features/announcements/index.ts +++ /dev/null @@ -1,568 +0,0 @@ -import { - toActor, - respond, - bySubcommand, - defineJob, - asJobError, - customId, -} from '~/infra/discord'; -import { - ChannelType, - EmbedBuilder, - InteractionContextType, - LabelBuilder, - MessageFlags, - ModalBuilder, - PermissionFlagsBits, - SlashCommandBuilder, - TextInputBuilder, - TextInputStyle, - type BaseMessageOptions, - type GuildMember, - type MessageMentionOptions, - type SlashCommandIntegerOption, -} from 'discord.js'; -import { z } from 'zod'; -import type { - AppContext, - CommandInteraction, - ComponentHandler, - Feature, -} from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { - PermanentError, - UserError, - discordTime, - parseFutureWhen, -} from '~/domain'; -import type { Announcement } from './schema'; -import { - getAnnouncement, - insertAnnouncement, - listAnnouncements, - requireAnnouncement, - transition, - updateContent, -} from './service'; - -const jobKey = (id: number) => `announcement:${id}`; -const maxLatenessMs = 60 * 60 * 1000; -const maxContent = 4000; - -function mentions(announcement: Announcement): { - prefix: string; - allowed: MessageMentionOptions; -} { - const role = announcement.mentionRoleId; - - if (role === null) { - return { prefix: '', allowed: { parse: [] } }; - } - - if (role === announcement.guildId) { - return { prefix: '@everyone ', allowed: { parse: ['everyone'] } }; - } - - return { prefix: `<@&${role}> `, allowed: { roles: [role] } }; -} - -export function render(announcement: Announcement): BaseMessageOptions { - const { prefix, allowed } = mentions(announcement); - - if (announcement.embed) { - const embed = new EmbedBuilder() - .setDescription(announcement.content) - .setColor(0xff_ac_1c); - - if (announcement.title !== null) { - embed.setTitle(announcement.title); - } - - return { - ...(prefix === '' ? {} : { content: prefix.trim() }), - embeds: [embed], - allowedMentions: allowed, - }; - } - - const heading = - announcement.title === null ? '' : `**${announcement.title}**\n`; - const content = `${prefix}${heading}${announcement.content}`; - - if (content.length > 2000) { - throw new UserError( - 'Plain announcements are limited to 2000 characters; use an embed.', - ); - } - - return { content, allowedMentions: allowed }; -} - -function preview(announcement: Announcement, note: string) { - const rendered = render(announcement); - - return { - content: [note, rendered.content].filter(Boolean).join('\n\n'), - embeds: rendered.embeds ?? [], - allowedMentions: { parse: [] }, - flags: MessageFlags.Ephemeral, - } as const; -} - -async function publish( - ctx: AppContext, - id: number, - from: Array, -): Promise { - const claimed = await transition(ctx.db, id, from, { status: 'publishing' }); - - if (!claimed) { - throw new UserError( - `Announcement #${id} cannot be published in its current state.`, - ); - } - - try { - const channel = await ctx.client.channels.fetch(claimed.channelId); - - if (channel?.isSendable() !== true) { - throw new PermanentError('Destination channel is not available'); - } - - const message = await channel.send(render(claimed)); - const published = await transition(ctx.db, id, ['publishing'], { - status: 'published', - publishedAt: new Date(), - messageId: message.id, - failure: null, - }); - - ctx.log.info( - { announcementId: id, messageId: message.id }, - 'Announcement published', - ); - - return published ?? claimed; - } catch (error) { - const jobError = asJobError(error); - const permanent = - jobError instanceof PermanentError || error instanceof UserError; - const message = error instanceof Error ? error.message : String(error); - - await transition(ctx.db, id, ['publishing'], { - status: permanent ? 'failed' : (from[0] ?? 'draft'), - failure: message, - }); - throw jobError; - } -} - -const publishJob = defineJob({ - type: 'announcements:publish', - payload: z.object({ announcementId: z.number().int() }), - handle: async ({ announcementId }, _info, ctx) => { - const announcement = await getAnnouncement(ctx.db, announcementId); - - if (announcement?.status !== 'scheduled') { - return; - } - - const due = announcement.scheduledAt ?? announcement.createdAt; - - if (Date.now() - due.getTime() > maxLatenessMs) { - await transition(ctx.db, announcementId, ['scheduled'], { - status: 'failed', - failure: 'Skipped: the scheduled time passed while the bot was offline', - }); - ctx.log.warn({ announcementId }, 'Skipped stale scheduled announcement'); - - return; - } - - await publish(ctx, announcementId, ['scheduled']); - }, -}); - -function checkMention(member: GuildMember, roleId: string | null): void { - if (roleId === null) { - return; - } - - const canPingAll = member.permissions.has( - PermissionFlagsBits.MentionEveryone, - ); - const role = member.guild.roles.cache.get(roleId); - - if ( - roleId === member.guild.id - ? !canPingAll - : role?.mentionable !== true && !canPingAll - ) { - throw new UserError('You may not mention that role.'); - } -} - -function contentModal( - id: string, - title: string, - current?: Announcement, -): ModalBuilder { - const titleInput = new TextInputBuilder() - .setCustomId('title') - .setStyle(TextInputStyle.Short) - .setRequired(false) - .setMaxLength(256); - const contentInput = new TextInputBuilder() - .setCustomId('content') - .setStyle(TextInputStyle.Paragraph) - .setMaxLength(maxContent); - - if (current?.title !== null && current?.title !== undefined) { - titleInput.setValue(current.title); - } - - if (current) { - contentInput.setValue(current.content); - } - - return new ModalBuilder() - .setCustomId(id) - .setTitle(title) - .addLabelComponents( - new LabelBuilder().setLabel('Title').setTextInputComponent(titleInput), - new LabelBuilder() - .setLabel('Content') - .setTextInputComponent(contentInput), - ); -} - -async function requireEditable( - interaction: CommandInteraction | Parameters[0], - ctx: AppContext, - id: number, -): Promise { - const announcement = await requireAnnouncement( - ctx.db, - interaction.guildId, - id, - ); - - if (announcement.authorId !== interaction.user.id) { - await ctx.authz.require( - toActor(interaction.member), - 'announcement:publish', - ); - } - - return announcement; -} - -const createModal: ComponentHandler = { - prefix: 'announcements:create', - permission: 'announcement:create', - execute: async (interaction, args, ctx) => { - if (!interaction.isModalSubmit()) { - return; - } - - const [channelId = '', embed, role] = args; - const mentionRoleId = role === undefined || role === '-' ? null : role; - - checkMention(interaction.member, mentionRoleId); - const title = interaction.fields.getTextInputValue('title').trim(); - const announcement = await insertAnnouncement(ctx.db, { - guildId: interaction.guildId, - authorId: interaction.user.id, - channelId, - title: title === '' ? null : title, - content: interaction.fields.getTextInputValue('content'), - embed: embed === '1', - mentionRoleId, - }); - - await interaction.reply( - preview( - announcement, - `Draft #${announcement.id} for <#${channelId}>. Publish with \`/announce publish\` or \`/announce schedule\`.`, - ), - ); - }, -}; - -const editModal: ComponentHandler = { - prefix: 'announcements:edit', - execute: async (interaction, args, ctx) => { - if (!interaction.isModalSubmit()) { - return; - } - - const announcement = await requireEditable( - interaction, - ctx, - Number(args[0]), - ); - const title = interaction.fields.getTextInputValue('title').trim(); - const updated = { - ...announcement, - title: title === '' ? null : title, - content: interaction.fields.getTextInputValue('content'), - }; - - render(updated); - await updateContent(ctx.db, announcement.id, updated); - if ( - announcement.status === 'published' && - announcement.messageId !== null - ) { - const channel = await ctx.client.channels.fetch(announcement.channelId); - - if (channel?.isTextBased() === true) { - await channel.messages.edit(announcement.messageId, { - ...render(updated), - allowedMentions: { parse: [] }, - }); - } - } - - await interaction.reply({ - content: `Announcement #${announcement.id} updated.`, - flags: MessageFlags.Ephemeral, - }); - }, -}; - -const idOption = (o: SlashCommandIntegerOption) => - o - .setName('id') - .setDescription('Announcement') - .setRequired(true) - .setAutocomplete(true); - -const data = new SlashCommandBuilder() - .setName('announce') - .setDescription('Create and publish announcements') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Draft an announcement') - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Where to post it') - .setRequired(true) - .addChannelTypes( - ChannelType.GuildText, - ChannelType.GuildAnnouncement, - ), - ) - .addBooleanOption((o) => - o.setName('embed').setDescription('Post as an embed (default yes)'), - ) - .addRoleOption((o) => - o.setName('mention').setDescription('Role to mention'), - ), - ) - .addSubcommand((sub) => - sub - .setName('preview') - .setDescription('Preview privately') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('publish') - .setDescription('Publish now') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('schedule') - .setDescription('Publish later') - .addIntegerOption(idOption) - .addStringOption((o) => - o - .setName('when') - .setDescription('e.g. 2h, 2026-11-20 18:00') - .setRequired(true), - ), - ) - .addSubcommand((sub) => - sub - .setName('edit') - .setDescription('Edit the text') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('cancel') - .setDescription('Cancel a draft or schedule') - .addIntegerOption(idOption), - ); - -export const announcementsFeature: Feature = { - name: 'announcements', - permissions: [ - { id: 'announcement:create', description: 'Draft announcements' }, - { - id: 'announcement:publish', - description: 'Publish and edit any announcement', - }, - { id: 'announcement:schedule', description: 'Schedule announcements' }, - ], - jobs: [publishJob], - components: [createModal, editModal], - commands: [ - { - data: data.toJSON(), - permissions: { - create: 'announcement:create', - publish: 'announcement:publish', - schedule: 'announcement:schedule', - }, - execute: bySubcommand({ - create: async (interaction) => { - const channel = interaction.options.getChannel('channel', true); - const role = interaction.options.getRole('mention'); - - checkMention(interaction.member, role?.id ?? null); - const embed = interaction.options.getBoolean('embed') ?? true; - const id = customId( - 'announcements:create', - channel.id, - embed ? 1 : 0, - role?.id ?? '-', - ); - - await interaction.showModal(contentModal(id, 'New announcement')); - }, - preview: async (interaction, ctx) => { - const announcement = await requireEditable( - interaction, - ctx, - interaction.options.getInteger('id', true), - ); - - await interaction.reply( - preview( - announcement, - `Preview of #${announcement.id} (${announcement.status}):`, - ), - ); - }, - publish: async (interaction, ctx) => { - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const id = interaction.options.getInteger('id', true); - - await requireAnnouncement(ctx.db, interaction.guildId, id); - await ctx.scheduler.cancel(jobKey(id)); - const published = await publish(ctx, id, [ - 'draft', - 'scheduled', - 'failed', - ]); - - await interaction.editReply( - `Published #${id} in <#${published.channelId}>.`, - ); - }, - schedule: async (interaction, ctx) => { - const id = interaction.options.getInteger('id', true); - - await requireAnnouncement(ctx.db, interaction.guildId, id); - const zone = await getGuildTimezone( - ctx.db, - interaction.guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - const runAt = parseFutureWhen( - interaction.options.getString('when', true), - zone, - ); - const scheduled = await transition( - ctx.db, - id, - ['draft', 'scheduled', 'failed'], - { - status: 'scheduled', - scheduledAt: runAt, - failure: null, - }, - ); - - if (!scheduled) { - throw new UserError( - `Announcement #${id} cannot be scheduled in its current state.`, - ); - } - - await ctx.scheduler.schedule( - publishJob, - { announcementId: id }, - { runAt, key: jobKey(id) }, - ); - await respond( - interaction, - `Announcement #${id} will be published ${discordTime(runAt)}.`, - ); - }, - edit: async (interaction, ctx) => { - const announcement = await requireEditable( - interaction, - ctx, - interaction.options.getInteger('id', true), - ); - - await interaction.showModal( - contentModal( - customId('announcements:edit', announcement.id), - `Edit announcement #${announcement.id}`, - announcement, - ), - ); - }, - cancel: async (interaction, ctx) => { - const announcement = await requireEditable( - interaction, - ctx, - interaction.options.getInteger('id', true), - ); - const cancelled = await transition( - ctx.db, - announcement.id, - ['draft', 'scheduled', 'failed'], - { - status: 'cancelled', - }, - ); - - if (!cancelled) { - throw new UserError( - `Announcement #${announcement.id} is already ${announcement.status}.`, - ); - } - - await ctx.scheduler.cancel(jobKey(announcement.id)); - await respond( - interaction, - `Cancelled announcement #${announcement.id}.`, - ); - }, - }), - autocomplete: async (interaction, ctx) => { - const rows = await listAnnouncements(ctx.db, interaction.guildId); - - await interaction.respond( - rows.map((row) => ({ - name: `#${row.id} [${row.status}] ${row.title ?? row.content}`.slice( - 0, - 100, - ), - value: row.id, - })), - ); - }, - }, - ], -}; diff --git a/src/features/announcements/schema.ts b/src/infra/db/announcements/model.ts similarity index 88% rename from src/features/announcements/schema.ts rename to src/infra/db/announcements/model.ts index 7ed9c32..2137fac 100644 --- a/src/features/announcements/schema.ts +++ b/src/infra/db/announcements/model.ts @@ -27,7 +27,8 @@ export const announcements = pgTable( title: text('title'), content: text('content').notNull(), embed: boolean('embed').notNull().default(true), - mentionRoleId: text('mention_role_id'), + mentionRoleIds: text('mention_role_ids').array().notNull().default([]), + mentionEveryone: boolean('mention_everyone').notNull().default(false), status: announcementStatus('status').notNull().default('draft'), scheduledAt: timestamp('scheduled_at', { withTimezone: true }), publishedAt: timestamp('published_at', { withTimezone: true }), diff --git a/src/features/announcements/service.ts b/src/infra/db/announcements/repo.ts similarity index 51% rename from src/features/announcements/service.ts rename to src/infra/db/announcements/repo.ts index 09c1b90..ced242f 100644 --- a/src/features/announcements/service.ts +++ b/src/infra/db/announcements/repo.ts @@ -1,22 +1,17 @@ import { and, desc, eq, inArray } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; -import { UserError } from '~/domain'; -import { announcements, type Announcement } from './schema'; +import type { + AnnouncementChanges, + AnnouncementRepository, + NewAnnouncement, +} from '~/core/ports'; +import type { Db } from '../client'; +import { announcements, type Announcement } from './model'; type Status = Announcement['status']; export async function insertAnnouncement( db: Db, - input: Pick< - Announcement, - | 'guildId' - | 'authorId' - | 'channelId' - | 'title' - | 'content' - | 'embed' - | 'mentionRoleId' - >, + input: NewAnnouncement, ): Promise { const [row] = await db.insert(announcements).values(input).returning(); @@ -27,23 +22,6 @@ export async function insertAnnouncement( return row; } -export async function requireAnnouncement( - db: Db, - guildId: string, - id: number, -): Promise { - const [row] = await db - .select() - .from(announcements) - .where(and(eq(announcements.id, id), eq(announcements.guildId, guildId))); - - if (!row) { - throw new UserError(`Announcement #${id} does not exist.`); - } - - return row; -} - export async function getAnnouncement( db: Db, id: number, @@ -56,30 +34,24 @@ export async function getAnnouncement( return row; } -export async function listAnnouncements(db: Db, guildId: string) { +export async function listAnnouncements( + db: Db, + guildId: string, + limit = 50, +): Promise { return db - .select({ - id: announcements.id, - title: announcements.title, - content: announcements.content, - status: announcements.status, - }) + .select() .from(announcements) - .where( - and( - eq(announcements.guildId, guildId), - inArray(announcements.status, ['draft', 'scheduled']), - ), - ) + .where(eq(announcements.guildId, guildId)) .orderBy(desc(announcements.id)) - .limit(25); + .limit(limit); } export async function transition( db: Db, id: number, from: readonly Status[], - changes: Partial & { status: Status }, + changes: AnnouncementChanges, ): Promise { const [row] = await db .update(announcements) @@ -95,7 +67,17 @@ export async function transition( export async function updateContent( db: Db, id: number, - changes: Pick, + changes: Parameters[1], ): Promise { await db.update(announcements).set(changes).where(eq(announcements.id, id)); } + +export function createAnnouncementRepository(db: Db): AnnouncementRepository { + return { + insert: (announcement) => insertAnnouncement(db, announcement), + find: (id) => getAnnouncement(db, id), + list: (guildId, limit) => listAnnouncements(db, guildId, limit), + transition: (id, from, changes) => transition(db, id, from, changes), + update: (id, changes) => updateContent(db, id, changes), + }; +} diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index 8270b66..f562265 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -8,3 +8,5 @@ export * from './roles/model'; export * from './roles/repo'; export * from './reminders/model'; export * from './reminders/repo'; +export * from './announcements/model'; +export * from './announcements/repo'; diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts new file mode 100644 index 0000000..81c9328 --- /dev/null +++ b/src/infra/discord/commands/announcements.ts @@ -0,0 +1,305 @@ +import { + ChannelType, + InteractionContextType, + LabelBuilder, + ModalBuilder, + SlashCommandBuilder, + TextInputBuilder, + TextInputStyle, + type SlashCommandIntegerOption, +} from 'discord.js'; +import type { Announcement } from '~/core/ports'; +import { + maxAnnouncementLength, + type AnnouncementService, +} from '~/core/services'; +import { channelMention, controlId, discordTime } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred } from '../define'; +import type { ComponentHandler, Feature } from '../module'; +import { respond, respondView } from '../router'; + +function contentModal( + id: string, + title: string, + current?: Announcement, +): ModalBuilder { + const titleInput = new TextInputBuilder() + .setCustomId('title') + .setStyle(TextInputStyle.Short) + .setRequired(false) + .setMaxLength(256); + const contentInput = new TextInputBuilder() + .setCustomId('content') + .setStyle(TextInputStyle.Paragraph) + .setMaxLength(maxAnnouncementLength); + + if (current?.title !== undefined && current.title !== null) { + titleInput.setValue(current.title); + } + + if (current) { + contentInput.setValue(current.content); + } + + return new ModalBuilder() + .setCustomId(id) + .setTitle(title) + .addLabelComponents( + new LabelBuilder().setLabel('Title').setTextInputComponent(titleInput), + new LabelBuilder() + .setLabel('Content') + .setTextInputComponent(contentInput), + ); +} + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Announcement') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('announce') + .setDescription('Create and publish announcements') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Draft an announcement') + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post it') + .setRequired(true) + .addChannelTypes( + ChannelType.GuildText, + ChannelType.GuildAnnouncement, + ), + ) + .addBooleanOption((o) => + o.setName('embed').setDescription('Post as an embed (default yes)'), + ) + .addRoleOption((o) => + o.setName('mention').setDescription('Role to mention'), + ), + ) + .addSubcommand((sub) => + sub + .setName('preview') + .setDescription('Preview privately') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('publish') + .setDescription('Publish now') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('schedule') + .setDescription('Publish later') + .addIntegerOption(idOption) + .addStringOption((o) => + o + .setName('when') + .setDescription('e.g. 2h, 2026-11-20 18:00') + .setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('edit') + .setDescription('Edit the text') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel a draft or schedule') + .addIntegerOption(idOption), + ); + +export function announcementCommands( + announcements: AnnouncementService, +): Feature { + const preview = (announcement: Announcement, note: string) => { + const view = announcements.view(announcement); + + return { + ...view, + content: [note, view.content].filter(Boolean).join('\n\n'), + }; + }; + + const create: ComponentHandler = { + prefix: 'announcements:create', + execute: async (interaction, args) => { + if (!interaction.isModalSubmit()) { + return; + } + + const [channelId = '', embed, role = '-'] = args; + const everyone = role === interaction.guildId; + const announcement = await announcements.draft( + toActor(interaction.member), + { + channelId, + title: interaction.fields.getTextInputValue('title'), + content: interaction.fields.getTextInputValue('content'), + embed: embed === '1', + mentionRoleIds: role === '-' || everyone ? [] : [role], + mentionEveryone: everyone, + }, + ); + + await respondView( + interaction, + preview( + announcement, + `Draft #${announcement.id} for ${channelMention(channelId)}. Publish with "/announce publish" or "/announce schedule".`, + ), + ); + }, + }; + + const edit: ComponentHandler = { + prefix: 'announcements:edit', + execute: async (interaction, [id]) => { + if (!interaction.isModalSubmit()) { + return; + } + + const updated = await announcements.edit( + toActor(interaction.member), + Number(id), + { + title: interaction.fields.getTextInputValue('title'), + content: interaction.fields.getTextInputValue('content'), + }, + ); + + await respond(interaction, `Announcement #${updated.id} updated.`); + }, + }; + + return { + name: 'announcements', + permissions: [ + { id: 'announcement:create', description: 'Draft announcements' }, + { + id: 'announcement:publish', + description: 'Publish and edit any announcement', + }, + { id: 'announcement:schedule', description: 'Schedule announcements' }, + ], + components: [create, edit], + commands: [ + { + data: data.toJSON(), + permissions: { create: 'announcement:create' }, + execute: bySubcommand({ + create: async (interaction) => { + const channel = interaction.options.getChannel('channel', true); + const role = interaction.options.getRole('mention'); + const embed = interaction.options.getBoolean('embed') ?? true; + + await interaction.showModal( + contentModal( + controlId( + 'announcements:create', + channel.id, + embed ? 1 : 0, + role?.id ?? '-', + ), + 'New announcement', + ), + ); + }, + preview: async (interaction) => { + const announcement = await announcements.get( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + + await respondView( + interaction, + preview( + announcement, + `Preview of #${announcement.id} (${announcement.status}):`, + ), + ); + }, + publish: deferred(async (interaction) => { + const published = await announcements.publish( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + + await respond( + interaction, + `Published #${published.id} in ${channelMention(published.channelId)}.`, + ); + }), + schedule: async (interaction) => { + const scheduled = await announcements.schedule( + toActor(interaction.member), + interaction.options.getInteger('id', true), + interaction.options.getString('when', true), + ); + + await respond( + interaction, + `Announcement #${scheduled.id} will be published ${discordTime(scheduled.scheduledAt ?? new Date())}.`, + ); + }, + edit: async (interaction) => { + const announcement = await announcements.get( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + + await interaction.showModal( + contentModal( + controlId('announcements:edit', announcement.id), + `Edit announcement #${announcement.id}`, + announcement, + ), + ); + }, + cancel: async (interaction) => { + const cancelled = await announcements.cancel( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + + await respond( + interaction, + `Cancelled announcement #${cancelled.id}.`, + ); + }, + }), + autocomplete: async (interaction) => { + const rows = await announcements.list(interaction.guildId); + + await interaction.respond( + rows + .filter((row) => + ['draft', 'scheduled', 'failed'].includes(row.status), + ) + .slice(0, 25) + .map((row) => ({ + name: `#${row.id} [${row.status}] ${row.title ?? row.content}`.slice( + 0, + 100, + ), + value: row.id, + })), + ); + }, + }, + ], + }; +} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index 47c2f99..7e6790a 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -2,3 +2,4 @@ export * from './permissions'; export * from './settings'; export * from './roles'; export * from './reminders'; +export * from './announcements'; diff --git a/tests/core/services/announcements.test.ts b/tests/core/services/announcements.test.ts new file mode 100644 index 0000000..2586ae7 --- /dev/null +++ b/tests/core/services/announcements.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Announcement, Scheduler } from '~/core/ports'; +import { announcementView, createAnnouncementService } from '~/core/services'; +import { createAnnouncementRepository } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + fakeDirectory, + fakeMessenger, + role, + silentLog, +} from '../../fakes'; + +const sample = (overrides: Partial = {}): Announcement => ({ + id: 1, + guildId: 'g', + authorId: 'a', + channelId: 'c', + title: 'Hello', + content: 'World', + embed: false, + mentionRoleIds: [], + mentionEveryone: false, + status: 'draft', + scheduledAt: null, + publishedAt: null, + messageId: null, + failure: null, + createdAt: new Date(), + ...overrides, +}); + +describe('announcement view', () => { + it('only pings the chosen roles or everyone, never text in the body', () => { + expect( + announcementView(sample({ content: '@everyone hi' })).mentions, + ).toEqual({ everyone: false, roles: [] }); + expect( + announcementView(sample({ mentionRoleIds: ['r1', 'r2'] })), + ).toMatchObject({ + content: '<@&r1> <@&r2>\n**Hello**\nWorld', + mentions: { roles: ['r1', 'r2'] }, + }); + expect( + announcementView(sample({ mentionEveryone: true })).mentions?.everyone, + ).toBe(true); + }); + + it('rejects plain messages over the Discord limit', () => { + expect(() => + announcementView(sample({ content: 'x'.repeat(2001) })), + ).toThrow('2000'); + expect(() => + announcementView(sample({ content: 'x'.repeat(2001), embed: true })), + ).not.toThrow(); + }); +}); + +describe.skipIf(noDatabase)('announcement service', () => { + const setup = (options: { canPost?: boolean; now?: Date } = {}) => { + const { messenger } = fakeMessenger(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const repository = createAnnouncementRepository(testDb()); + const service = createAnnouncementService({ + announcements: repository, + scheduler, + messenger, + directory: fakeDirectory( + [role({ id: 'team' }), role({ id: 'secret', mentionable: false })], + { canPost: options.canPost ?? true }, + ), + authz: allowAll, + log: silentLog, + clock: { now: () => options.now ?? new Date() }, + timezone: async () => 'Europe/Tallinn', + }); + + return { + service, + messenger, + repository, + author: actor({ guildId: snowflake() }), + }; + }; + + it('publishes a draft exactly once', async () => { + const { service, messenger, author } = setup(); + const draft = await service.draft(author, { + channelId: 'c', + content: 'Hi', + mentionRoleIds: ['team'], + }); + + await service.publish(author, draft.id); + await expect(service.publish(author, draft.id)).rejects.toThrow( + 'cannot be published', + ); + expect(messenger.send).toHaveBeenCalledOnce(); + }); + + it('refuses unmentionable roles, everyone and channels the author cannot use', async () => { + const { service, author } = setup(); + + await expect( + service.draft(author, { + channelId: 'c', + content: 'x', + mentionRoleIds: ['secret'], + }), + ).rejects.toThrow('may not mention'); + await expect( + service.draft(author, { + channelId: 'c', + content: 'x', + mentionEveryone: true, + }), + ).rejects.toThrow('everyone'); + await expect( + setup({ canPost: false }).service.draft(author, { + channelId: 'c', + content: 'x', + }), + ).rejects.toThrow('cannot post'); + }); + + it('skips scheduled announcements that are long overdue', async () => { + const { service, messenger, repository, author } = setup(); + const draft = await service.draft(author, { + channelId: 'c', + content: 'Hi', + }); + + await repository.transition(draft.id, ['draft'], { + status: 'scheduled', + scheduledAt: new Date(Date.now() - 2 * 3_600_000), + }); + await service.jobs[0]?.run( + { announcementId: draft.id }, + { id: 1, runAt: new Date(), attempt: 1 }, + ); + expect(messenger.send).not.toHaveBeenCalled(); + expect((await repository.find(draft.id))?.status).toBe('failed'); + }); + + it('publishes due scheduled announcements once', async () => { + const { service, messenger, repository, author } = setup(); + const draft = await service.draft(author, { + channelId: 'c', + content: 'Hi', + }); + const job = service.jobs[0]; + const info = { id: 1, runAt: new Date(), attempt: 1 }; + + await repository.transition(draft.id, ['draft'], { + status: 'scheduled', + scheduledAt: new Date(), + }); + await job?.run({ announcementId: draft.id }, info); + await job?.run({ announcementId: draft.id }, info); + expect(messenger.send).toHaveBeenCalledOnce(); + expect((await repository.find(draft.id))?.status).toBe('published'); + }); + + it('lets only one concurrent publish claim a draft', async () => { + const { service, repository, author } = setup(); + const draft = await service.draft(author, { + channelId: 'c', + content: 'Hi', + }); + const claims = await Promise.all( + Array.from({ length: 5 }, () => + repository.transition(draft.id, ['draft'], { status: 'publishing' }), + ), + ); + + expect(claims.filter(Boolean)).toHaveLength(1); + }); +}); diff --git a/tests/features/announcements/announcements.test.ts b/tests/features/announcements/announcements.test.ts deleted file mode 100644 index 4d11ffc..0000000 --- a/tests/features/announcements/announcements.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { pino } from 'pino'; -import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { render } from '~/features/announcements'; -import type { Announcement } from '~/features/announcements/schema'; -import { - getAnnouncement, - insertAnnouncement, - transition, -} from '~/features/announcements/service'; - -const draft = (overrides: Partial = {}): Announcement => ({ - id: 1, - guildId: 'g', - authorId: 'a', - channelId: 'c', - title: 'Hello', - content: 'World', - embed: false, - mentionRoleId: null, - status: 'draft', - scheduledAt: null, - publishedAt: null, - messageId: null, - failure: null, - createdAt: new Date(), - ...overrides, -}); - -describe('announcement rendering', () => { - it('never parses mentions written into the text', () => { - expect(render(draft({ content: '@everyone hi' })).allowedMentions).toEqual({ - parse: [], - }); - }); - - it('only allows the chosen role or @everyone', () => { - expect(render(draft({ mentionRoleId: 'r' })).allowedMentions).toEqual({ - roles: ['r'], - }); - expect(render(draft({ mentionRoleId: 'g' })).allowedMentions).toEqual({ - parse: ['everyone'], - }); - }); - - it('rejects plain messages over the Discord limit', () => { - expect(() => render(draft({ content: 'x'.repeat(2001) }))).toThrow('2000'); - expect(() => - render(draft({ content: 'x'.repeat(2001), embed: true })), - ).not.toThrow(); - }); -}); - -const input = () => ({ - guildId: snowflake(), - authorId: 'a', - channelId: 'c', - title: 'Hello', - content: 'World', - embed: false, - mentionRoleId: null, -}); - -describe.skipIf(noDatabase)('announcement publishing', () => { - it('lets only one concurrent publish claim a draft', async () => { - const db = testDb(); - const row = await insertAnnouncement(db, input()); - const claims = await Promise.all( - Array.from({ length: 5 }, () => - transition(db, row.id, ['draft'], { status: 'publishing' }), - ), - ); - - expect(claims.filter(Boolean)).toHaveLength(1); - }); - - it('skips scheduled announcements that are long overdue', async () => { - const db = testDb(); - const { announcementsFeature } = await import('~/features/announcements'); - const job = announcementsFeature.jobs?.[0]; - const send = vi.fn(); - const ctx = { - db, - log: pino({ level: 'silent' }), - client: { - channels: { fetch: async () => ({ isSendable: () => true, send }) }, - }, - } as unknown as AppContext; - const row = await insertAnnouncement(db, input()); - - await transition(db, row.id, ['draft'], { - status: 'scheduled', - scheduledAt: new Date(Date.now() - 2 * 3_600_000), - }); - await job?.run( - { announcementId: row.id }, - { id: 1, runAt: new Date(), attempt: 1 }, - ctx, - ); - expect(send).not.toHaveBeenCalled(); - expect((await getAnnouncement(db, row.id))?.status).toBe('failed'); - }); - - it('publishes due scheduled announcements once', async () => { - const db = testDb(); - const { announcementsFeature } = await import('~/features/announcements'); - const job = announcementsFeature.jobs?.[0]; - const send = vi.fn(async () => ({ id: 'm1' })); - const ctx = { - db, - log: pino({ level: 'silent' }), - client: { - channels: { fetch: async () => ({ isSendable: () => true, send }) }, - }, - } as unknown as AppContext; - const row = await insertAnnouncement(db, input()); - - await transition(db, row.id, ['draft'], { - status: 'scheduled', - scheduledAt: new Date(), - }); - const info = { id: 1, runAt: new Date(), attempt: 1 }; - - await job?.run({ announcementId: row.id }, info, ctx); - await job?.run({ announcementId: row.id }, info, ctx); - expect(send).toHaveBeenCalledOnce(); - expect(await getAnnouncement(db, row.id)).toMatchObject({ - status: 'published', - messageId: 'm1', - }); - }); -}); From e964892bae8ee68828e66b04201df29a60a97735 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 19:48:40 +0200 Subject: [PATCH 026/199] refactor(events): event service with calendar port and capped reminder pings --- src/app.ts | 27 +- src/core/ports/events.ts | 49 ++ src/core/ports/index.ts | 1 + src/core/services/events.ts | 462 ++++++++++++ src/core/services/index.ts | 1 + src/features/events/index.ts | 689 ------------------ src/features/movies/index.ts | 10 +- .../schema.ts => infra/db/events/model.ts} | 0 .../service.ts => infra/db/events/repo.ts} | 52 +- src/infra/db/index.ts | 2 + src/infra/discord/commands/events.ts | 303 ++++++++ src/infra/discord/commands/index.ts | 1 + tests/core/services/events.test.ts | 206 ++++++ tests/features/events/events.test.ts | 131 ---- 14 files changed, 1069 insertions(+), 865 deletions(-) create mode 100644 src/core/ports/events.ts create mode 100644 src/core/services/events.ts delete mode 100644 src/features/events/index.ts rename src/{features/events/schema.ts => infra/db/events/model.ts} (100%) rename src/{features/events/service.ts => infra/db/events/repo.ts} (82%) create mode 100644 src/infra/discord/commands/events.ts create mode 100644 tests/core/services/events.test.ts delete mode 100644 tests/features/events/events.test.ts diff --git a/src/app.ts b/src/app.ts index eebd089..69c0d45 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,6 +3,8 @@ import type { Config } from '~/config'; import { announcementCommands, createClient, + createDiscordCalendar, + eventCommands, createInteractionHandler, buildRegistry, createDiscordDirectory, @@ -15,6 +17,7 @@ import { import { createAnnouncementService, createAuthorizer, + createEventService, createPermissionService, createReminderService, createRoleService, @@ -28,6 +31,7 @@ import { systemClock, type Job } from '~/core/ports'; import { connectDatabase, createAnnouncementRepository, + createEventRepository, createGrantRepository, createReminderRepository, createRolePanelRepository, @@ -35,8 +39,7 @@ import { runMigrations, } from '~/infra/db'; import { birthdaysFeature } from '~/features/birthdays'; -import { eventsFeature } from '~/features/events'; -import { moviesFeature } from '~/features/movies'; +import { createMoviesFeature } from '~/features/movies'; import { pollsFeature } from '~/features/polls'; import { createRedmineFeature } from '~/features/redmine'; @@ -97,7 +100,21 @@ export function compose(config: Config, log: Logger) { clock: systemClock, timezone: (guildId) => settings.timezone(guildId), }); - const jobs: Array> = [...reminders.jobs, ...announcements.jobs]; + const events = createEventService({ + events: createEventRepository(database.db), + scheduler, + messenger, + calendar: createDiscordCalendar(client), + directory, + authz, + log: log.child({ service: 'events' }), + timezone: (guildId) => settings.timezone(guildId), + }); + const jobs: Array> = [ + ...reminders.jobs, + ...announcements.jobs, + ...events.jobs, + ]; const permissions = createPermissionService({ grants, directory, @@ -111,10 +128,10 @@ export function compose(config: Config, log: Logger) { settingsCommands(settings), reminderCommands(reminders), announcementCommands(announcements), - eventsFeature, + eventCommands(events), birthdaysFeature, pollsFeature, - moviesFeature, + createMoviesFeature(events), ]; const redmine = createRedmineFeature(config, reminders); diff --git a/src/core/ports/events.ts b/src/core/ports/events.ts new file mode 100644 index 0000000..0c1e3e1 --- /dev/null +++ b/src/core/ports/events.ts @@ -0,0 +1,49 @@ +export const rsvpStatuses = ['going', 'maybe', 'not_going'] as const; + +export type RsvpStatus = (typeof rsvpStatuses)[number]; + +export type RsvpCounts = Record; + +export type Event = { + id: number; + guildId: string; + title: string; + description: string | null; + startsAt: Date; + endsAt: Date | null; + timezone: string; + location: string | null; + organizerId: string; + channelId: string; + messageId: string | null; + capacity: number | null; + mentionRoleId: string | null; + reminderMinutes: number[]; + discordEventId: string | null; + status: 'scheduled' | 'cancelled'; + createdAt: Date; +}; + +export type NewEvent = Omit< + Event, + 'id' | 'messageId' | 'discordEventId' | 'status' | 'createdAt' +>; + +export type EventRepository = { + insert: (event: NewEvent) => Promise; + find: (id: number) => Promise; + upcoming: (guildId: string, limit?: number) => Promise; + update: ( + id: number, + changes: Partial>, + ) => Promise; + setRsvp: ( + eventId: number, + userId: string, + status: RsvpStatus, + ) => Promise; + counts: (eventId: number) => Promise; + attendees: ( + eventId: number, + ) => Promise>; +}; diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 9943dee..1b7e556 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -8,3 +8,4 @@ export type * from './settings'; export type * from './roles'; export type * from './reminders'; export type * from './announcements'; +export * from './events'; diff --git a/src/core/services/events.ts b/src/core/services/events.ts new file mode 100644 index 0000000..bdf0913 --- /dev/null +++ b/src/core/services/events.ts @@ -0,0 +1,462 @@ +import { z } from 'zod'; +import { + channelMention, + controlId, + discordTime, + maxContentLength, + parseFutureWhen, + parseWhen, + requireMentionable, + requireZone, + roleMention, + UserError, + userMention, + type Actor, + type Message, +} from '~/domain'; +import { + rsvpStatuses, + type Authorizer, + type Calendar, + type Directory, + type Event, + type EventRepository, + type Logger, + type Messenger, + type NewEvent, + type RsvpCounts, + type RsvpStatus, + type Scheduler, +} from '~/core/ports'; +import { defineJob } from './jobs'; + +export const rsvpLabels: Record = { + going: 'Going', + maybe: 'Maybe', + not_going: 'Not going', +}; + +const maxReminders = 3; +const defaultDurationMs = 2 * 60 * 60 * 1000; +const reminderKey = (id: number, minutes: number) => + `event:${id}:remind:${minutes}`; + +export type EventRequest = { + title: string; + start: string; + end?: string; + description?: string; + location?: string; + channelId: string; + capacity?: number; + mentionRoleId?: string; + reminders?: string; + timezone?: string; + native?: boolean; +}; + +export type EventChanges = Partial< + Pick< + EventRequest, + 'title' | 'start' | 'end' | 'description' | 'location' | 'capacity' + > +>; + +export function eventView(event: Event, counts: RsvpCounts): Message { + const cancelled = event.status === 'cancelled'; + const until = event.endsAt ? ` – ${discordTime(event.endsAt, 'f')}` : ''; + const going = + event.capacity === null + ? String(counts.going) + : `${counts.going} / ${event.capacity}`; + + return { + embeds: [ + { + title: cancelled ? `[Cancelled] ${event.title}` : event.title, + color: cancelled ? 0x80_80_80 : 0x2b_8a_3e, + ...(event.description !== null && { description: event.description }), + fields: [ + { + name: 'When', + value: `${discordTime(event.startsAt)} (${discordTime(event.startsAt, 'R')})${until}`, + }, + ...(event.location === null + ? [] + : [{ name: 'Where', value: event.location }]), + { + name: 'Organizer', + value: userMention(event.organizerId), + inline: true, + }, + { name: 'Going', value: going, inline: true }, + { name: 'Maybe', value: String(counts.maybe), inline: true }, + ], + footer: `Event #${event.id}`, + }, + ], + controls: cancelled + ? [] + : [ + rsvpStatuses.map((status) => ({ + kind: 'button' as const, + id: controlId('events:rsvp', event.id, status), + label: rsvpLabels[status], + style: + status === 'going' + ? ('success' as const) + : ('secondary' as const), + })), + ], + }; +} + +export function parseReminderMinutes(value: string | undefined): number[] { + if (value === undefined) { + return [60]; + } + + if (value.trim() === '') { + return []; + } + + const minutes = value.split(',').map((part) => Number(part.trim())); + + if ( + minutes.length > maxReminders || + minutes.some((m) => !Number.isInteger(m) || m < 1 || m > 10_080) + ) { + throw new UserError( + `Reminders are up to ${maxReminders} comma-separated minute values, e.g. "60,15".`, + ); + } + + return [...new Set(minutes)]; +} + +export function reminderText( + event: Event, + minutes: number, + going: readonly string[], +) { + const link = + event.messageId === null + ? '' + : ` https://discord.com/channels/${event.guildId}/${event.channelId}/${event.messageId}`; + const head = `⏰ **${event.title}** starts ${discordTime(event.startsAt, 'R')} (${minutes} min reminder).${link}`; + const pinged: string[] = []; + let length = head.length + 1; + + for (const id of going) { + const mention = `${userMention(id)} `; + + if (length + mention.length > maxContentLength) { + break; + } + + pinged.push(id); + length += mention.length; + } + + return { + content: [head, pinged.map((id) => userMention(id)).join(' ')] + .filter(Boolean) + .join('\n'), + pinged, + }; +} + +type Deps = { + events: EventRepository; + scheduler: Scheduler; + messenger: Messenger; + calendar: Calendar; + directory: Directory; + authz: Authorizer; + log: Logger; + timezone: (guildId: string) => Promise; +}; + +export function createEventService(deps: Deps) { + const { events, scheduler, messenger, calendar, directory, authz, log } = + deps; + + const remindJob = defineJob({ + type: 'events:remind', + payload: z.object({ eventId: z.number().int(), minutes: z.number().int() }), + handle: async ({ eventId, minutes }) => { + const event = await events.find(eventId); + + if ( + event?.status !== 'scheduled' || + event.startsAt.getTime() <= Date.now() + ) { + return; + } + + const attendees = await events.attendees(eventId); + const going = attendees + .filter((a) => a.status === 'going') + .map((a) => a.userId); + const { content, pinged } = reminderText(event, minutes, going); + + await messenger.send(event.channelId, { + content, + mentions: { users: pinged }, + }); + }, + }); + + const refresh = async (event: Event) => { + if (event.messageId === null) { + return; + } + + const edited = await messenger.edit( + event.channelId, + event.messageId, + eventView(event, await events.counts(event.id)), + ); + + if (!edited) { + log.warn({ eventId: event.id }, 'Event message or channel was deleted'); + } + }; + + const scheduleReminders = async ( + event: Event, + previous: readonly number[] = [], + ) => { + await Promise.all( + previous.map((minutes) => + scheduler.cancel(reminderKey(event.id, minutes)), + ), + ); + + if (event.status !== 'scheduled') { + return; + } + + const upcoming = event.reminderMinutes + .map((minutes) => ({ + minutes, + runAt: new Date(event.startsAt.getTime() - minutes * 60_000), + })) + .filter(({ runAt }) => runAt.getTime() > Date.now()); + + await Promise.all( + upcoming.map(({ minutes, runAt }) => + scheduler.schedule( + remindJob, + { eventId: event.id, minutes }, + { runAt, key: reminderKey(event.id, minutes) }, + ), + ), + ); + }; + + const syncNative = async (event: Event): Promise => { + try { + if (event.status === 'cancelled') { + if (event.discordEventId !== null) { + await calendar.remove(event.guildId, event.discordEventId); + } + + return null; + } + + return await calendar.upsert(event.guildId, event.discordEventId, { + title: event.title, + description: event.description ?? '', + location: event.location ?? 'See the event post', + startsAt: event.startsAt, + endsAt: + event.endsAt ?? + new Date(event.startsAt.getTime() + defaultDurationMs), + }); + } catch (error) { + log.warn( + { err: error, eventId: event.id }, + 'Could not sync native Discord event', + ); + + return event.discordEventId; + } + }; + + const publish = async (input: NewEvent, native = false) => { + let event = await events.insert(input); + const sent = await messenger.send(event.channelId, { + ...eventView(event, { going: 0, maybe: 0, not_going: 0 }), + ...(event.mentionRoleId !== null && { + content: roleMention(event.mentionRoleId), + mentions: { roles: [event.mentionRoleId] }, + }), + }); + + event = await events.update(event.id, { + messageId: sent.messageId, + discordEventId: native ? await syncNative(event) : null, + }); + await scheduleReminders(event); + + return event; + }; + + const requireEvent = async (actor: Actor, id: number) => { + const event = await events.find(id); + + if (event?.guildId !== actor.guildId) { + throw new UserError(`Event #${id} does not exist.`); + } + + return event; + }; + + const requireManageable = async (actor: Actor, id: number) => { + const event = await requireEvent(actor, id); + + if (event.organizerId !== actor.userId) { + await authz.require(actor, 'event:manage'); + } + + return event; + }; + + const requirePostable = async (actor: Actor, channelId: string) => { + if (!(await directory.canPost(actor, channelId))) { + throw new UserError( + `You cannot post in ${channelMention(channelId)} yourself.`, + ); + } + }; + + return { + jobs: [remindJob], + view: async (actor: Actor, id: number) => { + const event = await requireEvent(actor, id); + + return eventView(event, await events.counts(event.id)); + }, + upcoming: (guildId: string) => events.upcoming(guildId), + attendees: async (actor: Actor, id: number) => { + const event = await requireEvent(actor, id); + + return { event, attendees: await events.attendees(event.id) }; + }, + publish: async (actor: Actor, input: NewEvent) => { + await requirePostable(actor, input.channelId); + + return publish(input); + }, + create: async (actor: Actor, request: EventRequest) => { + await authz.require(actor, 'event:create'); + await requirePostable(actor, request.channelId); + + if (request.mentionRoleId !== undefined) { + const role = await directory.role(actor.guildId, request.mentionRoleId); + + if (!role) { + throw new UserError('That role no longer exists.'); + } + + requireMentionable(actor, role); + } + + const timezone = + request.timezone === undefined + ? await deps.timezone(actor.guildId) + : requireZone(request.timezone); + const event = await publish( + { + guildId: actor.guildId, + title: request.title, + description: request.description ?? null, + startsAt: parseFutureWhen(request.start, timezone), + endsAt: + request.end === undefined ? null : parseWhen(request.end, timezone), + timezone, + location: request.location ?? null, + organizerId: actor.userId, + channelId: request.channelId, + capacity: request.capacity ?? null, + mentionRoleId: request.mentionRoleId ?? null, + reminderMinutes: parseReminderMinutes(request.reminders), + }, + request.native ?? false, + ); + + log.info({ eventId: event.id, actorId: actor.userId }, 'Event created'); + + return event; + }, + edit: async (actor: Actor, id: number, changes: EventChanges) => { + const event = await requireManageable(actor, id); + + if (event.status !== 'scheduled') { + throw new UserError('Cancelled events cannot be edited.'); + } + + const startsAt = + changes.start === undefined + ? event.startsAt + : parseFutureWhen(changes.start, event.timezone); + const endsAt = + changes.end === undefined + ? event.endsAt + : parseWhen(changes.end, event.timezone); + + if (endsAt && endsAt <= startsAt) { + throw new UserError('The end must be after the start.'); + } + + let updated = await events.update(event.id, { + title: changes.title ?? event.title, + description: changes.description ?? event.description, + location: changes.location ?? event.location, + capacity: changes.capacity ?? event.capacity, + startsAt, + endsAt, + }); + + if (updated.discordEventId !== null) { + updated = await events.update(event.id, { + discordEventId: await syncNative(updated), + }); + } + + await refresh(updated); + await scheduleReminders(updated, event.reminderMinutes); + log.info({ eventId: event.id, actorId: actor.userId }, 'Event edited'); + + return updated; + }, + cancel: async (actor: Actor, id: number) => { + const event = await requireManageable(actor, id); + + if (event.status === 'cancelled') { + throw new UserError('That event is already cancelled.'); + } + + const cancelled = await events.update(event.id, { status: 'cancelled' }); + + await Promise.all([ + refresh(cancelled), + scheduleReminders(cancelled, event.reminderMinutes), + cancelled.discordEventId === null ? undefined : syncNative(cancelled), + ]); + log.info({ eventId: event.id, actorId: actor.userId }, 'Event cancelled'); + + return cancelled; + }, + rsvp: async (actor: Actor, id: number, status: RsvpStatus) => { + const event = await requireEvent(actor, id); + + await events.setRsvp(event.id, actor.userId, status); + + return eventView(event, await events.counts(event.id)); + }, + }; +} + +export type EventService = ReturnType; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index 4f6a9ad..b1c2649 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -5,3 +5,4 @@ export * from './settings'; export * from './roles'; export * from './reminders'; export * from './announcements'; +export * from './events'; diff --git a/src/features/events/index.ts b/src/features/events/index.ts deleted file mode 100644 index 688639d..0000000 --- a/src/features/events/index.ts +++ /dev/null @@ -1,689 +0,0 @@ -import { - toActor, - respond, - bySubcommand, - defineJob, - asJobError, - isUnknownObject, - customId, -} from '~/infra/discord'; -import { - ActionRowBuilder, - ButtonBuilder, - ButtonStyle, - ChannelType, - EmbedBuilder, - GuildScheduledEventEntityType, - GuildScheduledEventPrivacyLevel, - InteractionContextType, - MessageFlags, - SlashCommandBuilder, - type BaseMessageOptions, - type SlashCommandIntegerOption, -} from 'discord.js'; -import { z } from 'zod'; -import type { - AppContext, - CommandInteraction, - ComponentHandler, - Feature, -} from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { - UserError, - discordTime, - parseFutureWhen, - parseWhen, - requireZone, -} from '~/domain'; -import type { Event, RsvpStatus } from './schema'; -import { - getEvent, - insertEvent, - listAttendees, - listUpcoming, - requireEvent, - rsvpCounts, - rsvpStatuses, - setRsvp, - updateEvent, - type NewEvent, - type RsvpCounts, -} from './service'; - -const rsvpLabels: Record = { - going: 'Going', - maybe: 'Maybe', - not_going: 'Not going', -}; -const maxReminders = 3; -const defaultNativeDurationMs = 2 * 60 * 60 * 1000; - -export function renderEvent( - event: Event, - counts: RsvpCounts, -): BaseMessageOptions { - const cancelled = event.status === 'cancelled'; - const embed = new EmbedBuilder() - .setTitle(cancelled ? `[Cancelled] ${event.title}` : event.title) - .setColor(cancelled ? 0x80_80_80 : 0x2b_8a_3e) - .addFields( - { - name: 'When', - value: `${discordTime(event.startsAt)} (${discordTime(event.startsAt, 'R')})${ - event.endsAt ? ` – ${discordTime(event.endsAt, 'f')}` : '' - }`, - }, - ...(event.location === null - ? [] - : [{ name: 'Where', value: event.location }]), - { name: 'Organizer', value: `<@${event.organizerId}>`, inline: true }, - { - name: 'Going', - value: - event.capacity === null - ? String(counts.going) - : `${counts.going} / ${event.capacity}`, - inline: true, - }, - { name: 'Maybe', value: String(counts.maybe), inline: true }, - ) - .setFooter({ text: `Event #${event.id}` }); - - if (event.description !== null) { - embed.setDescription(event.description); - } - - const buttons = rsvpStatuses.map((status) => - new ButtonBuilder() - .setCustomId(customId('events:rsvp', event.id, status)) - .setLabel(rsvpLabels[status]) - .setStyle( - status === 'going' ? ButtonStyle.Success : ButtonStyle.Secondary, - ), - ); - - return { - embeds: [embed], - components: cancelled - ? [] - : [new ActionRowBuilder().addComponents(buttons)], - }; -} - -async function refreshMessage(ctx: AppContext, event: Event): Promise { - if (event.messageId === null) { - return; - } - - try { - const channel = await ctx.client.channels.fetch(event.channelId); - - if (channel?.isTextBased() === true) { - await channel.messages.edit( - event.messageId, - renderEvent(event, await rsvpCounts(ctx.db, event.id)), - ); - } - } catch (error) { - if (!isUnknownObject(error)) { - throw error; - } - - ctx.log.warn({ eventId: event.id }, 'Event message or channel was deleted'); - } -} - -const reminderKey = (id: number, minutes: number) => - `event:${id}:remind:${minutes}`; - -export const remindJob = defineJob({ - type: 'events:remind', - payload: z.object({ eventId: z.number().int(), minutes: z.number().int() }), - handle: async ({ eventId, minutes }, _info, ctx) => { - const event = await getEvent(ctx.db, eventId); - - if ( - event?.status !== 'scheduled' || - event.startsAt.getTime() <= Date.now() - ) { - return; - } - - const attendees = await listAttendees(ctx.db, eventId); - const going = attendees - .filter((a) => a.status === 'going') - .slice(0, 90) - .map((a) => a.userId); - const link = - event.messageId === null - ? '' - : ` https://discord.com/channels/${event.guildId}/${event.channelId}/${event.messageId}`; - const pings = going.map((id) => `<@${id}>`).join(' '); - - try { - const channel = await ctx.client.channels.fetch(event.channelId); - - if (channel?.isSendable() === true) { - await channel.send({ - content: `⏰ **${event.title}** starts ${discordTime(event.startsAt, 'R')} (${minutes} min reminder).${link}\n${pings}`, - allowedMentions: { users: going }, - }); - } - } catch (error) { - throw asJobError(error); - } - }, -}); - -async function scheduleReminders( - ctx: AppContext, - event: Event, - previous: readonly number[] = [], -): Promise { - await Promise.all( - previous.map((minutes) => - ctx.scheduler.cancel(reminderKey(event.id, minutes)), - ), - ); - - if (event.status !== 'scheduled') { - return; - } - - const upcoming = event.reminderMinutes - .map((minutes) => ({ - minutes, - runAt: new Date(event.startsAt.getTime() - minutes * 60_000), - })) - .filter(({ runAt }) => runAt.getTime() > Date.now()); - - await Promise.all( - upcoming.map(({ minutes, runAt }) => - ctx.scheduler.schedule( - remindJob, - { eventId: event.id, minutes }, - { runAt, key: reminderKey(event.id, minutes) }, - ), - ), - ); -} - -async function syncNativeEvent( - ctx: AppContext, - event: Event, -): Promise { - try { - const guild = await ctx.client.guilds.fetch(event.guildId); - - if (event.status === 'cancelled') { - if (event.discordEventId !== null) { - await guild.scheduledEvents.delete(event.discordEventId); - } - - return null; - } - - const details = { - name: event.title.slice(0, 100), - scheduledStartTime: event.startsAt, - scheduledEndTime: - event.endsAt ?? - new Date(event.startsAt.getTime() + defaultNativeDurationMs), - description: (event.description ?? '').slice(0, 1000), - entityMetadata: { - location: (event.location ?? 'See the event post').slice(0, 100), - }, - }; - - if (event.discordEventId !== null) { - await guild.scheduledEvents.edit(event.discordEventId, details); - - return event.discordEventId; - } - - const created = await guild.scheduledEvents.create({ - ...details, - privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly, - entityType: GuildScheduledEventEntityType.External, - }); - - return created.id; - } catch (error) { - ctx.log.warn( - { err: error, eventId: event.id }, - 'Could not sync native Discord event', - ); - - return event.discordEventId; - } -} - -export async function createEvent( - ctx: AppContext, - input: NewEvent & { native?: boolean }, -): Promise { - const { native = false, ...values } = input; - const channel = await ctx.client.channels - .fetch(values.channelId) - .catch(() => null); - - if (channel?.isSendable() !== true) { - throw new UserError('I cannot post in that channel.'); - } - - let event = await insertEvent(ctx.db, values); - const message = await channel.send({ - ...renderEvent(event, { going: 0, maybe: 0, not_going: 0 }), - ...(event.mentionRoleId === null - ? {} - : { - content: `<@&${event.mentionRoleId}>`, - allowedMentions: { roles: [event.mentionRoleId] }, - }), - }); - const discordEventId = native ? await syncNativeEvent(ctx, event) : null; - - event = await updateEvent(ctx.db, event.id, { - messageId: message.id, - discordEventId, - }); - await scheduleReminders(ctx, event); - - return event; -} - -function parseReminderMinutes(value: string | null): number[] { - if (value === null) { - return [60]; - } - - if (value.trim() === '') { - return []; - } - - const minutes = value.split(',').map((part) => Number(part.trim())); - - if ( - minutes.length > maxReminders || - minutes.some((m) => !Number.isInteger(m) || m < 1 || m > 10_080) - ) { - throw new UserError( - `Reminders are up to ${maxReminders} comma-separated minute values, e.g. "60,15".`, - ); - } - - return [...new Set(minutes)]; -} - -async function requireManageable( - interaction: CommandInteraction, - ctx: AppContext, -): Promise { - const event = await requireEvent( - ctx.db, - interaction.guildId, - interaction.options.getInteger('id', true), - ); - - if (event.organizerId !== interaction.user.id) { - await ctx.authz.require(toActor(interaction.member), 'event:manage'); - } - - return event; -} - -const rsvpHandler: ComponentHandler = { - prefix: 'events:rsvp', - execute: async (interaction, [id, answer], ctx) => { - const status = rsvpStatuses.find((s) => s === answer); - const eventId = Number(id); - - if ( - !interaction.isButton() || - status === undefined || - !Number.isSafeInteger(eventId) - ) { - throw new UserError('This button is invalid.'); - } - - await setRsvp(ctx.db, eventId, interaction.user.id, status); - const event = await getEvent(ctx.db, eventId); - - if (event) { - await interaction.update( - renderEvent(event, await rsvpCounts(ctx.db, eventId)), - ); - } - - await interaction.followUp({ - content: `RSVP saved: **${rsvpLabels[status]}**.`, - flags: MessageFlags.Ephemeral, - }); - }, -}; - -const idOption = (o: SlashCommandIntegerOption) => - o - .setName('id') - .setDescription('Event') - .setRequired(true) - .setAutocomplete(true); - -const data = new SlashCommandBuilder() - .setName('event') - .setDescription('Organise events') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Create and publish an event') - .addStringOption((o) => - o - .setName('title') - .setDescription('Title') - .setRequired(true) - .setMaxLength(200), - ) - .addStringOption((o) => - o - .setName('start') - .setDescription('e.g. 2026-11-20 18:00') - .setRequired(true), - ) - .addStringOption((o) => - o - .setName('description') - .setDescription('Description') - .setMaxLength(2000), - ) - .addStringOption((o) => o.setName('end').setDescription('End time')) - .addStringOption((o) => - o.setName('location').setDescription('Place or link').setMaxLength(200), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Where to post (default: here)') - .addChannelTypes( - ChannelType.GuildText, - ChannelType.GuildAnnouncement, - ), - ) - .addIntegerOption((o) => - o - .setName('capacity') - .setDescription('Maximum attendees') - .setMinValue(1) - .setMaxValue(10_000), - ) - .addRoleOption((o) => - o.setName('mention').setDescription('Role to notify'), - ) - .addStringOption((o) => - o - .setName('reminders') - .setDescription('Minutes before start, e.g. "60,15" (default 60)'), - ) - .addStringOption((o) => - o.setName('timezone').setDescription('IANA timezone for the times'), - ) - .addBooleanOption((o) => - o - .setName('native') - .setDescription('Also create a Discord scheduled event'), - ), - ) - .addSubcommand((sub) => - sub - .setName('edit') - .setDescription('Change an event') - .addIntegerOption(idOption) - .addStringOption((o) => - o.setName('title').setDescription('Title').setMaxLength(200), - ) - .addStringOption((o) => o.setName('start').setDescription('Start time')) - .addStringOption((o) => o.setName('end').setDescription('End time')) - .addStringOption((o) => - o - .setName('description') - .setDescription('Description') - .setMaxLength(2000), - ) - .addStringOption((o) => - o.setName('location').setDescription('Place or link').setMaxLength(200), - ) - .addIntegerOption((o) => - o - .setName('capacity') - .setDescription('Maximum attendees') - .setMinValue(1), - ), - ) - .addSubcommand((sub) => - sub - .setName('cancel') - .setDescription('Cancel an event') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => sub.setName('list').setDescription('Upcoming events')) - .addSubcommand((sub) => - sub - .setName('view') - .setDescription('Show an event') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('attendees') - .setDescription('Who is coming') - .addIntegerOption(idOption), - ); - -async function editEvent( - interaction: CommandInteraction, - ctx: AppContext, -): Promise { - const event = await requireManageable(interaction, ctx); - - if (event.status !== 'scheduled') { - throw new UserError('Cancelled events cannot be edited.'); - } - - const option = (name: string) => - interaction.options.getString(name) ?? undefined; - const start = option('start'); - const end = option('end'); - const changes = { - title: option('title') ?? event.title, - description: option('description') ?? event.description, - location: option('location') ?? event.location, - capacity: interaction.options.getInteger('capacity') ?? event.capacity, - startsAt: - start === undefined - ? event.startsAt - : parseFutureWhen(start, event.timezone), - endsAt: end === undefined ? event.endsAt : parseWhen(end, event.timezone), - }; - - if (changes.endsAt && changes.endsAt <= changes.startsAt) { - throw new UserError('The end must be after the start.'); - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - let updated = await updateEvent(ctx.db, event.id, changes); - - if (updated.discordEventId !== null) { - updated = await updateEvent(ctx.db, event.id, { - discordEventId: await syncNativeEvent(ctx, updated), - }); - } - - await refreshMessage(ctx, updated); - await scheduleReminders(ctx, updated, event.reminderMinutes); - ctx.log.info( - { eventId: event.id, actorId: interaction.user.id }, - 'Event edited', - ); - await interaction.editReply(`Event #${event.id} updated.`); -} - -export const eventsFeature: Feature = { - name: 'events', - permissions: [ - { id: 'event:create', description: 'Create events' }, - { id: 'event:manage', description: 'Edit and cancel any event' }, - ], - jobs: [remindJob], - components: [rsvpHandler], - commands: [ - { - data: data.toJSON(), - permissions: { create: 'event:create' }, - execute: bySubcommand({ - create: async (interaction, ctx) => { - const zoneOption = interaction.options.getString('timezone'); - const timezone = - zoneOption === null - ? await getGuildTimezone( - ctx.db, - interaction.guildId, - ctx.config.DEFAULT_TIMEZONE, - ) - : requireZone(zoneOption); - const end = interaction.options.getString('end'); - const mention = interaction.options.getRole('mention'); - - if ( - mention && - !mention.mentionable && - !interaction.member.permissions.has('MentionEveryone') - ) { - throw new UserError('You may not mention that role.'); - } - - const input = { - guildId: interaction.guildId, - title: interaction.options.getString('title', true), - description: interaction.options.getString('description'), - startsAt: parseFutureWhen( - interaction.options.getString('start', true), - timezone, - ), - endsAt: end === null ? null : parseWhen(end, timezone), - timezone, - location: interaction.options.getString('location'), - organizerId: interaction.user.id, - channelId: - interaction.options.getChannel('channel')?.id ?? - interaction.channelId, - capacity: interaction.options.getInteger('capacity'), - mentionRoleId: mention?.id ?? null, - reminderMinutes: parseReminderMinutes( - interaction.options.getString('reminders'), - ), - native: interaction.options.getBoolean('native') ?? false, - }; - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const event = await createEvent(ctx, input); - - ctx.log.info( - { eventId: event.id, actorId: interaction.user.id }, - 'Event created', - ); - await interaction.editReply( - `Created event #${event.id} in <#${event.channelId}>.`, - ); - }, - edit: editEvent, - cancel: async (interaction, ctx) => { - const event = await requireManageable(interaction, ctx); - - if (event.status === 'cancelled') { - throw new UserError('That event is already cancelled.'); - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const cancelled = await updateEvent(ctx.db, event.id, { - status: 'cancelled', - }); - - await Promise.all([ - refreshMessage(ctx, cancelled), - scheduleReminders(ctx, cancelled, event.reminderMinutes), - cancelled.discordEventId === null - ? undefined - : syncNativeEvent(ctx, cancelled), - ]); - ctx.log.info( - { eventId: event.id, actorId: interaction.user.id }, - 'Event cancelled', - ); - await interaction.editReply(`Event #${event.id} is cancelled.`); - }, - list: async (interaction, ctx) => { - const upcoming = await listUpcoming(ctx.db, interaction.guildId); - - await respond( - interaction, - upcoming.length === 0 - ? 'No upcoming events.' - : upcoming - .map( - (e) => - `#${e.id} **${e.title}** — ${discordTime(e.startsAt, 'f')}`, - ) - .join('\n'), - ); - }, - view: async (interaction, ctx) => { - const event = await requireEvent( - ctx.db, - interaction.guildId, - interaction.options.getInteger('id', true), - ); - const counts = await rsvpCounts(ctx.db, event.id); - - await interaction.reply({ - embeds: renderEvent(event, counts).embeds ?? [], - flags: MessageFlags.Ephemeral, - }); - }, - attendees: async (interaction, ctx) => { - const event = await requireEvent( - ctx.db, - interaction.guildId, - interaction.options.getInteger('id', true), - ); - const attendees = await listAttendees(ctx.db, event.id); - const section = (status: RsvpStatus) => { - const ids = attendees - .filter((a) => a.status === status) - .map((a) => `<@${a.userId}>`); - - return `**${rsvpLabels[status]} (${ids.length})**\n${ids.join(' ') || '—'}`; - }; - - await respond( - interaction, - rsvpStatuses - .map((status) => section(status)) - .join('\n\n') - .slice(0, 2000), - ); - }, - }), - autocomplete: async (interaction, ctx) => { - const upcoming = await listUpcoming(ctx.db, interaction.guildId); - - await interaction.respond( - upcoming.map((e) => ({ - name: `#${e.id} ${e.title}`.slice(0, 100), - value: e.id, - })), - ); - }, - }, - ], -}; diff --git a/src/features/movies/index.ts b/src/features/movies/index.ts index f55825f..a27d719 100644 --- a/src/features/movies/index.ts +++ b/src/features/movies/index.ts @@ -9,7 +9,7 @@ import { import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; import { getGuildTimezone } from '~/infra/db'; import { UserError, discordTime, parseFutureWhen, parseWhen } from '~/domain'; -import { createEvent } from '~/features/events'; +import type { EventService } from '~/core/services'; import { createPoll, getResults, latestPollBySource } from '~/features/polls'; import type { MovieSuggestion } from './schema'; import { @@ -168,7 +168,7 @@ const data = new SlashCommandBuilder() const zoneOf = (interaction: CommandInteraction, ctx: AppContext) => getGuildTimezone(ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE); -export const moviesFeature: Feature = { +export const createMoviesFeature = (events: EventService): Feature => ({ name: 'movies', permissions: [ { @@ -279,7 +279,7 @@ export const moviesFeature: Feature = { ); await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const event = await createEvent(ctx, { + const event = await events.publish(toActor(interaction.member), { guildId: interaction.guildId, title: `🎬 Movie night: ${label(movie)}`.slice(0, 200), description: movie.note, @@ -291,6 +291,8 @@ export const moviesFeature: Feature = { interaction.options.getChannel('channel')?.id ?? interaction.channelId, capacity: interaction.options.getInteger('capacity'), + endsAt: null, + mentionRoleId: null, reminderMinutes: [60], }); @@ -351,4 +353,4 @@ export const moviesFeature: Feature = { }, }, ], -}; +}); diff --git a/src/features/events/schema.ts b/src/infra/db/events/model.ts similarity index 100% rename from src/features/events/schema.ts rename to src/infra/db/events/model.ts diff --git a/src/features/events/service.ts b/src/infra/db/events/repo.ts similarity index 82% rename from src/features/events/service.ts rename to src/infra/db/events/repo.ts index a23e0e9..76291b7 100644 --- a/src/features/events/service.ts +++ b/src/infra/db/events/repo.ts @@ -1,33 +1,15 @@ import { and, asc, count, eq, gte, ne } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; +import type { EventRepository, NewEvent, RsvpCounts } from '~/core/ports'; +import type { Db } from '../client'; import { UserError } from '~/domain'; -import { - eventRsvps, - events, - rsvpStatus, - type Event, - type RsvpStatus, -} from './schema'; - -export type NewEvent = Omit< - typeof events.$inferInsert, - 'id' | 'messageId' | 'discordEventId' | 'status' | 'createdAt' ->; - -export type RsvpCounts = Record; - -export const rsvpStatuses = rsvpStatus.enumValues; +import { eventRsvps, events, type Event, type RsvpStatus } from './model'; export async function insertEvent(db: Db, input: NewEvent): Promise { if (input.endsAt && input.endsAt <= input.startsAt) { throw new UserError('The end must be after the start.'); } - if ( - input.capacity !== undefined && - input.capacity !== null && - input.capacity < 1 - ) { + if (input.capacity !== null && input.capacity < 1) { throw new UserError('Capacity must be at least 1.'); } @@ -46,20 +28,6 @@ export async function getEvent(db: Db, id: number): Promise { return row; } -export async function requireEvent( - db: Db, - guildId: string, - id: number, -): Promise { - const event = await getEvent(db, id); - - if (event?.guildId !== guildId) { - throw new UserError(`Event #${id} does not exist.`); - } - - return event; -} - export async function listUpcoming( db: Db, guildId: string, @@ -173,3 +141,15 @@ export async function listAttendees( .orderBy(asc(eventRsvps.updatedAt)) .limit(1000); } + +export function createEventRepository(db: Db): EventRepository { + return { + insert: (event) => insertEvent(db, event), + find: (id) => getEvent(db, id), + upcoming: (guildId, limit) => listUpcoming(db, guildId, limit), + update: (id, changes) => updateEvent(db, id, changes), + setRsvp: (eventId, userId, status) => setRsvp(db, eventId, userId, status), + counts: (eventId) => rsvpCounts(db, eventId), + attendees: (eventId) => listAttendees(db, eventId), + }; +} diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index f562265..9113f53 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -10,3 +10,5 @@ export * from './reminders/model'; export * from './reminders/repo'; export * from './announcements/model'; export * from './announcements/repo'; +export * from './events/model'; +export * from './events/repo'; diff --git a/src/infra/discord/commands/events.ts b/src/infra/discord/commands/events.ts new file mode 100644 index 0000000..4d3b031 --- /dev/null +++ b/src/infra/discord/commands/events.ts @@ -0,0 +1,303 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { rsvpStatuses, type RsvpStatus } from '~/core/ports'; +import { rsvpLabels, type EventService } from '~/core/services'; +import { channelMention, discordTime, userMention, UserError } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred } from '../define'; +import type { CommandInteraction, ComponentHandler, Feature } from '../module'; +import { render } from '../render'; +import { respond, respondView } from '../router'; + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Event') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('event') + .setDescription('Organise events') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Create and publish an event') + .addStringOption((o) => + o + .setName('title') + .setDescription('Title') + .setRequired(true) + .setMaxLength(200), + ) + .addStringOption((o) => + o + .setName('start') + .setDescription('e.g. 2026-11-20 18:00') + .setRequired(true), + ) + .addStringOption((o) => + o + .setName('description') + .setDescription('Description') + .setMaxLength(2000), + ) + .addStringOption((o) => o.setName('end').setDescription('End time')) + .addStringOption((o) => + o.setName('location').setDescription('Place or link').setMaxLength(200), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes( + ChannelType.GuildText, + ChannelType.GuildAnnouncement, + ), + ) + .addIntegerOption((o) => + o + .setName('capacity') + .setDescription('Maximum attendees') + .setMinValue(1) + .setMaxValue(10_000), + ) + .addRoleOption((o) => + o.setName('mention').setDescription('Role to notify'), + ) + .addStringOption((o) => + o + .setName('reminders') + .setDescription('Minutes before start, e.g. "60,15" (default 60)'), + ) + .addStringOption((o) => + o.setName('timezone').setDescription('IANA timezone for the times'), + ) + .addBooleanOption((o) => + o + .setName('native') + .setDescription('Also create a Discord scheduled event'), + ), + ) + .addSubcommand((sub) => + sub + .setName('edit') + .setDescription('Change an event') + .addIntegerOption(idOption) + .addStringOption((o) => + o.setName('title').setDescription('Title').setMaxLength(200), + ) + .addStringOption((o) => o.setName('start').setDescription('Start time')) + .addStringOption((o) => o.setName('end').setDescription('End time')) + .addStringOption((o) => + o + .setName('description') + .setDescription('Description') + .setMaxLength(2000), + ) + .addStringOption((o) => + o.setName('location').setDescription('Place or link').setMaxLength(200), + ) + .addIntegerOption((o) => + o + .setName('capacity') + .setDescription('Maximum attendees') + .setMinValue(1), + ), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel an event') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Upcoming events')) + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('Show an event') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('attendees') + .setDescription('Who is coming') + .addIntegerOption(idOption), + ); + +function optional(interaction: CommandInteraction, name: string) { + return interaction.options.getString(name) ?? undefined; +} + +export function eventCommands(events: EventService): Feature { + const rsvp: ComponentHandler = { + prefix: 'events:rsvp', + execute: async (interaction, [id, answer]) => { + const status = rsvpStatuses.find((s) => s === answer); + const eventId = Number(id); + + if ( + !interaction.isButton() || + status === undefined || + !Number.isSafeInteger(eventId) + ) { + throw new UserError('This button is invalid.'); + } + + const view = await events.rsvp( + toActor(interaction.member), + eventId, + status, + ); + const { content, embeds, components } = render(view); + + await interaction.update({ content, embeds, components }); + await respond(interaction, `RSVP saved: **${rsvpLabels[status]}**.`); + }, + }; + + return { + name: 'events', + permissions: [ + { id: 'event:create', description: 'Create events' }, + { id: 'event:manage', description: 'Edit and cancel any event' }, + ], + components: [rsvp], + commands: [ + { + data: data.toJSON(), + permissions: { create: 'event:create' }, + execute: bySubcommand({ + create: deferred(async (interaction) => { + const capacity = interaction.options.getInteger('capacity'); + const mention = interaction.options.getRole('mention'); + const fields = [ + 'description', + 'end', + 'location', + 'reminders', + 'timezone', + ] as const; + const extras = Object.fromEntries( + fields.flatMap((name) => { + const value = optional(interaction, name); + + return value === undefined ? [] : [[name, value]]; + }), + ); + const event = await events.create(toActor(interaction.member), { + ...extras, + title: interaction.options.getString('title', true), + start: interaction.options.getString('start', true), + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + native: interaction.options.getBoolean('native') ?? false, + ...(capacity !== null && { capacity }), + ...(mention && { mentionRoleId: mention.id }), + }); + + await respond( + interaction, + `Created event #${event.id} in ${channelMention(event.channelId)}.`, + ); + }), + edit: deferred(async (interaction) => { + const capacity = interaction.options.getInteger('capacity'); + const fields = [ + 'title', + 'start', + 'end', + 'description', + 'location', + ] as const; + const changes = Object.fromEntries( + fields.flatMap((name) => { + const value = optional(interaction, name); + + return value === undefined ? [] : [[name, value]]; + }), + ); + const event = await events.edit( + toActor(interaction.member), + interaction.options.getInteger('id', true), + { + ...changes, + ...(capacity !== null && { capacity }), + }, + ); + + await respond(interaction, `Event #${event.id} updated.`); + }), + cancel: deferred(async (interaction) => { + const event = await events.cancel( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + + await respond(interaction, `Event #${event.id} is cancelled.`); + }), + list: async (interaction) => { + const upcoming = await events.upcoming(interaction.guildId); + + await respond( + interaction, + upcoming.length === 0 + ? 'No upcoming events.' + : upcoming + .map( + (e) => + `#${e.id} **${e.title}** — ${discordTime(e.startsAt, 'f')}`, + ) + .join('\n'), + ); + }, + view: async (interaction) => { + const view = await events.view( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + + await respondView(interaction, { ...view, controls: [] }); + }, + attendees: async (interaction) => { + const { attendees } = await events.attendees( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + const section = (status: RsvpStatus) => { + const ids = attendees + .filter((a) => a.status === status) + .map((a) => userMention(a.userId)); + + return `**${rsvpLabels[status]} (${ids.length})**\n${ids.join(' ') || '—'}`; + }; + + await respond( + interaction, + rsvpStatuses + .map((status) => section(status)) + .join('\n\n') + .slice(0, 2000), + ); + }, + }), + autocomplete: async (interaction) => { + const upcoming = await events.upcoming(interaction.guildId); + + await interaction.respond( + upcoming.map((e) => ({ + name: `#${e.id} ${e.title}`.slice(0, 100), + value: e.id, + })), + ); + }, + }, + ], + }; +} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index 7e6790a..e4a2057 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -3,3 +3,4 @@ export * from './settings'; export * from './roles'; export * from './reminders'; export * from './announcements'; +export * from './events'; diff --git a/tests/core/services/events.test.ts b/tests/core/services/events.test.ts new file mode 100644 index 0000000..9081b0e --- /dev/null +++ b/tests/core/services/events.test.ts @@ -0,0 +1,206 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Calendar, Scheduler } from '~/core/ports'; +import { + createEventService, + parseReminderMinutes, + reminderText, +} from '~/core/services'; +import { UserError } from '~/domain'; +import { createEventRepository } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + fakeDirectory, + fakeMessenger, + silentLog, +} from '../../fakes'; + +const base = () => ({ + guildId: snowflake(), + title: 'Board game night', + description: null, + startsAt: new Date(Date.now() + 3 * 3_600_000), + endsAt: null, + timezone: 'Europe/Tallinn', + location: null, + organizerId: snowflake(), + channelId: snowflake(), + capacity: null, + mentionRoleId: null, + reminderMinutes: [], +}); + +describe('event helpers', () => { + it('parses reminder minutes', () => { + expect(parseReminderMinutes(undefined)).toEqual([60]); + expect(parseReminderMinutes('60, 15,15')).toEqual([60, 15]); + expect(() => parseReminderMinutes('1,2,3,4')).toThrow(UserError); + }); + + it('keeps reminder pings under the Discord message limit', () => { + const going = Array.from( + { length: 200 }, + (_, n) => `1${String(n).padStart(18, '0')}`, + ); + const { content, pinged } = reminderText( + { + ...base(), + id: 1, + messageId: 'm', + discordEventId: null, + status: 'scheduled', + createdAt: new Date(), + }, + 60, + going, + ); + + expect(content.length).toBeLessThanOrEqual(2000); + expect(pinged.length).toBeGreaterThan(50); + expect(pinged.length).toBeLessThan(200); + }); +}); + +describe.skipIf(noDatabase)('event RSVPs', () => { + const repository = () => createEventRepository(testDb()); + + it('records RSVPs and lets members change them without duplicates', async () => { + const events = repository(); + const event = await events.insert(base()); + const user = snowflake(); + + await events.setRsvp(event.id, user, 'going'); + await events.setRsvp(event.id, user, 'maybe'); + await events.setRsvp(event.id, user, 'maybe'); + expect(await events.attendees(event.id)).toEqual([ + { userId: user, status: 'maybe' }, + ]); + expect(await events.counts(event.id)).toEqual({ + going: 0, + maybe: 1, + not_going: 0, + }); + }); + + it('enforces capacity but lets attendees keep their spot', async () => { + const events = repository(); + const event = await events.insert({ ...base(), capacity: 1 }); + const [first, second] = [snowflake(), snowflake()]; + + await events.setRsvp(event.id, first, 'going'); + await events.setRsvp(event.id, first, 'going'); + await expect(events.setRsvp(event.id, second, 'going')).rejects.toThrow( + 'full', + ); + await events.setRsvp(event.id, first, 'not_going'); + await events.setRsvp(event.id, second, 'going'); + expect((await events.counts(event.id)).going).toBe(1); + }); + + it('never exceeds capacity under concurrent registrations', async () => { + const events = repository(); + const event = await events.insert({ ...base(), capacity: 3 }); + const results = await Promise.allSettled( + Array.from({ length: 15 }, () => + events.setRsvp(event.id, snowflake(), 'going'), + ), + ); + + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(3); + expect((await events.counts(event.id)).going).toBe(3); + }); + + it('closes RSVPs once cancelled', async () => { + const events = repository(); + const event = await events.insert(base()); + + await events.update(event.id, { status: 'cancelled' }); + await expect( + events.setRsvp(event.id, snowflake(), 'going'), + ).rejects.toBeInstanceOf(UserError); + }); +}); + +describe.skipIf(noDatabase)('event service', () => { + const setup = () => { + const { messenger } = fakeMessenger(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const calendar = { + upsert: vi.fn(async () => 'native'), + remove: vi.fn(async () => undefined), + }; + const service = createEventService({ + events: createEventRepository(testDb()), + scheduler, + messenger, + calendar, + directory: fakeDirectory(), + authz: allowAll, + log: silentLog, + timezone: async () => 'Europe/Tallinn', + }); + + return { + service, + messenger, + scheduler, + calendar, + organizer: actor({ guildId: snowflake(), userId: snowflake() }), + }; + }; + + it('publishes, schedules only future reminders and mirrors natively', async () => { + const { service, messenger, scheduler, calendar, organizer } = setup(); + const event = await service.create(organizer, { + title: 'Quiz', + start: '3h', + channelId: 'c', + reminders: '60,600', + native: true, + }); + + expect(event.messageId).not.toBeNull(); + expect(event.discordEventId).toBe('native'); + expect(messenger.send).toHaveBeenCalledOnce(); + expect(scheduler.schedule).toHaveBeenCalledOnce(); + expect(calendar.upsert).toHaveBeenCalledOnce(); + }); + + it('skips reminders for cancelled events and lets only organizers manage', async () => { + const { service, messenger, organizer } = setup(); + const event = await service.create(organizer, { + title: 'Quiz', + start: '3h', + channelId: 'c', + }); + + await service.cancel(organizer, event.id); + messenger.send.mockClear(); + await service.jobs[0]?.run( + { eventId: event.id, minutes: 60 }, + { id: 1, runAt: new Date(), attempt: 1 }, + ); + expect(messenger.send).not.toHaveBeenCalled(); + }); + + it('returns an updated view after an RSVP', async () => { + const { service, organizer } = setup(); + const event = await service.create(organizer, { + title: 'Quiz', + start: '3h', + channelId: 'c', + capacity: 5, + }); + const view = await service.rsvp( + actor({ guildId: organizer.guildId, userId: snowflake() }), + event.id, + 'going', + ); + + expect(JSON.stringify(view.embeds)).toContain('1 / 5'); + }); +}); diff --git a/tests/features/events/events.test.ts b/tests/features/events/events.test.ts deleted file mode 100644 index 9137444..0000000 --- a/tests/features/events/events.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { pino } from 'pino'; -import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { UserError } from '~/domain'; -import { createEvent, remindJob } from '~/features/events'; -import { - insertEvent, - listAttendees, - rsvpCounts, - setRsvp, - updateEvent, -} from '~/features/events/service'; - -const base = () => ({ - guildId: snowflake(), - title: 'Board game night', - startsAt: new Date(Date.now() + 3 * 3_600_000), - timezone: 'Europe/Tallinn', - organizerId: snowflake(), - channelId: snowflake(), -}); - -describe.skipIf(noDatabase)('event RSVPs', () => { - const db = noDatabase ? undefined : testDb(); - const database = () => { - if (!db) { - throw new Error('unreachable'); - } - - return db; - }; - - it('records RSVPs and lets members change them without duplicates', async () => { - const event = await insertEvent(database(), base()); - const user = snowflake(); - - await setRsvp(database(), event.id, user, 'going'); - await setRsvp(database(), event.id, user, 'maybe'); - await setRsvp(database(), event.id, user, 'maybe'); - expect(await listAttendees(database(), event.id)).toEqual([ - { userId: user, status: 'maybe' }, - ]); - expect(await rsvpCounts(database(), event.id)).toEqual({ - going: 0, - maybe: 1, - not_going: 0, - }); - }); - - it('enforces capacity but lets attendees keep their spot', async () => { - const event = await insertEvent(database(), { ...base(), capacity: 1 }); - const [first, second] = [snowflake(), snowflake()]; - - await setRsvp(database(), event.id, first, 'going'); - await setRsvp(database(), event.id, first, 'going'); - await expect( - setRsvp(database(), event.id, second, 'going'), - ).rejects.toThrow('full'); - await setRsvp(database(), event.id, second, 'maybe'); - await setRsvp(database(), event.id, first, 'not_going'); - await setRsvp(database(), event.id, second, 'going'); - expect((await rsvpCounts(database(), event.id)).going).toBe(1); - }); - - it('never exceeds capacity under concurrent registrations', async () => { - const event = await insertEvent(database(), { ...base(), capacity: 3 }); - const results = await Promise.allSettled( - Array.from({ length: 15 }, () => - setRsvp(database(), event.id, snowflake(), 'going'), - ), - ); - - expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(3); - expect((await rsvpCounts(database(), event.id)).going).toBe(3); - }); - - it('closes RSVPs once cancelled', async () => { - const event = await insertEvent(database(), base()); - - await updateEvent(database(), event.id, { status: 'cancelled' }); - await expect( - setRsvp(database(), event.id, snowflake(), 'going'), - ).rejects.toBeInstanceOf(UserError); - }); - - it('validates times and capacity', async () => { - const start = new Date(Date.now() + 3_600_000); - - await expect( - insertEvent(database(), { ...base(), startsAt: start, endsAt: start }), - ).rejects.toThrow('end'); - await expect( - insertEvent(database(), { ...base(), capacity: 0 }), - ).rejects.toThrow('Capacity'); - }); - - it('publishes, schedules future reminders and skips reminders for cancelled events', async () => { - const send = vi.fn(async () => ({ id: snowflake() })); - const schedule = vi.fn(async () => undefined); - const ctx = { - db: database(), - log: pino({ level: 'silent' }), - client: { - channels: { fetch: async () => ({ isSendable: () => true, send }) }, - }, - scheduler: { schedule, cancel: vi.fn() }, - } as unknown as AppContext; - const event = await createEvent(ctx, { - ...base(), - reminderMinutes: [60, 600], - }); - - expect(event.messageId).not.toBeNull(); - expect(schedule).toHaveBeenCalledOnce(); - expect(schedule).toHaveBeenCalledWith( - remindJob, - { eventId: event.id, minutes: 60 }, - expect.anything(), - ); - - send.mockClear(); - await updateEvent(database(), event.id, { status: 'cancelled' }); - await remindJob.run( - { eventId: event.id, minutes: 60 }, - { id: 1, runAt: new Date(), attempt: 1 }, - ctx, - ); - expect(send).not.toHaveBeenCalled(); - }); -}); From 82171c7dc5c80896a5e87bce7db45339db268335 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 21:17:05 +0200 Subject: [PATCH 027/199] refactor(polls, movies): poll and movie services; movies reuse polls and events --- src/app.ts | 29 +- src/core/ports/index.ts | 2 + src/core/ports/movies.ts | 44 ++ src/core/ports/polls.ts | 64 +++ src/core/services/index.ts | 2 + src/core/services/movies.ts | 175 ++++++ src/core/services/polls.ts | 296 +++++++++++ src/domain/index.ts | 2 + src/domain/movie.ts | 10 + src/domain/poll.ts | 57 ++ src/features/movies/index.ts | 356 ------------- src/features/polls/index.ts | 498 ------------------ src/infra/db/index.ts | 4 + .../schema.ts => infra/db/movies/model.ts} | 0 .../service.ts => infra/db/movies/repo.ts} | 28 +- .../schema.ts => infra/db/polls/model.ts} | 0 .../service.ts => infra/db/polls/repo.ts} | 117 ++-- src/infra/discord/commands/index.ts | 2 + src/infra/discord/commands/movies.ts | 243 +++++++++ src/infra/discord/commands/polls.ts | 251 +++++++++ tests/core/services/movies.test.ts | 133 +++++ tests/core/services/polls.test.ts | 184 +++++++ tests/domain/poll.test.ts | 48 ++ tests/features/movies/movies.test.ts | 117 ---- tests/features/polls/polls.test.ts | 159 ------ 25 files changed, 1594 insertions(+), 1227 deletions(-) create mode 100644 src/core/ports/movies.ts create mode 100644 src/core/ports/polls.ts create mode 100644 src/core/services/movies.ts create mode 100644 src/core/services/polls.ts create mode 100644 src/domain/movie.ts create mode 100644 src/domain/poll.ts delete mode 100644 src/features/movies/index.ts delete mode 100644 src/features/polls/index.ts rename src/{features/movies/schema.ts => infra/db/movies/model.ts} (100%) rename src/{features/movies/service.ts => infra/db/movies/repo.ts} (86%) rename src/{features/polls/schema.ts => infra/db/polls/model.ts} (100%) rename src/{features/polls/service.ts => infra/db/polls/repo.ts} (69%) create mode 100644 src/infra/discord/commands/movies.ts create mode 100644 src/infra/discord/commands/polls.ts create mode 100644 tests/core/services/movies.test.ts create mode 100644 tests/core/services/polls.test.ts create mode 100644 tests/domain/poll.test.ts delete mode 100644 tests/features/movies/movies.test.ts delete mode 100644 tests/features/polls/polls.test.ts diff --git a/src/app.ts b/src/app.ts index 69c0d45..81b6093 100644 --- a/src/app.ts +++ b/src/app.ts @@ -5,6 +5,8 @@ import { createClient, createDiscordCalendar, eventCommands, + movieCommands, + pollCommands, createInteractionHandler, buildRegistry, createDiscordDirectory, @@ -18,6 +20,8 @@ import { createAnnouncementService, createAuthorizer, createEventService, + createMovieService, + createPollService, createPermissionService, createReminderService, createRoleService, @@ -33,14 +37,14 @@ import { createAnnouncementRepository, createEventRepository, createGrantRepository, + createMovieRepository, + createPollRepository, createReminderRepository, createRolePanelRepository, createSettingsRepository, runMigrations, } from '~/infra/db'; import { birthdaysFeature } from '~/features/birthdays'; -import { createMoviesFeature } from '~/features/movies'; -import { pollsFeature } from '~/features/polls'; import { createRedmineFeature } from '~/features/redmine'; function legacyPanel(config: Config): LegacyPanel | undefined { @@ -110,7 +114,24 @@ export function compose(config: Config, log: Logger) { log: log.child({ service: 'events' }), timezone: (guildId) => settings.timezone(guildId), }); + const polls = createPollService({ + polls: createPollRepository(database.db), + scheduler, + messenger, + directory, + authz, + log: log.child({ service: 'polls' }), + timezone: (guildId) => settings.timezone(guildId), + }); + const movies = createMovieService({ + movies: createMovieRepository(database.db), + polls, + events, + authz, + timezone: (guildId) => settings.timezone(guildId), + }); const jobs: Array> = [ + ...polls.jobs, ...reminders.jobs, ...announcements.jobs, ...events.jobs, @@ -130,8 +151,8 @@ export function compose(config: Config, log: Logger) { announcementCommands(announcements), eventCommands(events), birthdaysFeature, - pollsFeature, - createMoviesFeature(events), + pollCommands(polls), + movieCommands(movies), ]; const redmine = createRedmineFeature(config, reminders); diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 1b7e556..7437d86 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -9,3 +9,5 @@ export type * from './roles'; export type * from './reminders'; export type * from './announcements'; export * from './events'; +export type * from './polls'; +export type * from './movies'; diff --git a/src/core/ports/movies.ts b/src/core/ports/movies.ts new file mode 100644 index 0000000..7b93435 --- /dev/null +++ b/src/core/ports/movies.ts @@ -0,0 +1,44 @@ +export type MovieSuggestion = { + id: number; + guildId: string; + title: string; + normalizedTitle: string; + year: number | null; + note: string | null; + suggestedBy: string; + createdAt: Date; + removedAt: Date | null; +}; + +export type NewSuggestion = Pick< + MovieSuggestion, + 'guildId' | 'title' | 'year' | 'note' | 'suggestedBy' +>; + +export type Screening = { + guildId: string; + suggestionId: number; + eventId?: number | null; + pollId?: number | null; + scheduledFor?: Date | null; +}; + +export type WatchedMovie = { + title: string; + year: number | null; + watchedAt: Date | null; +}; + +export type MovieRepository = { + suggest: (suggestion: NewSuggestion) => Promise; + find: (guildId: string, id: number) => Promise; + unwatched: (guildId: string, limit?: number) => Promise; + remove: (id: number) => Promise; + recordScreening: (screening: Screening) => Promise; + markWatched: ( + guildId: string, + suggestionId: number, + at: Date, + ) => Promise; + history: (guildId: string, limit?: number) => Promise; +}; diff --git a/src/core/ports/polls.ts b/src/core/ports/polls.ts new file mode 100644 index 0000000..35a7715 --- /dev/null +++ b/src/core/ports/polls.ts @@ -0,0 +1,64 @@ +import type { Tally } from '~/domain'; + +export type PollStatus = 'open' | 'closed' | 'cancelled'; + +export type Poll = { + id: number; + guildId: string; + channelId: string; + messageId: string | null; + creatorId: string; + question: string; + multiple: boolean; + anonymous: boolean; + showResults: 'live' | 'closed'; + closesAt: Date | null; + status: PollStatus; + source: string | null; + createdAt: Date; +}; + +export type PollOption = { + id: number; + pollId: number; + position: number; + label: string; + ref: string | null; +}; + +export type PollWithOptions = Poll & { options: PollOption[] }; + +export type PollResults = Tally; + +export type NewPoll = Pick< + Poll, + 'guildId' | 'channelId' | 'creatorId' | 'question' +> & + Partial< + Pick + > & { + options: ReadonlyArray<{ label: string; ref?: string | null }>; + }; + +export type PollRepository = { + insert: (poll: NewPoll) => Promise; + find: (id: number) => Promise; + vote: ( + pollId: number, + userId: string, + optionIds: readonly number[], + ) => Promise; + results: (poll: PollWithOptions) => Promise; + choices: (pollId: number, userId: string) => Promise; + voters: (pollId: number) => Promise>; + finish: ( + id: number, + status: 'closed' | 'cancelled', + ) => Promise; + setMessage: (id: number, messageId: string) => Promise; + open: (guildId: string) => Promise; + latestBySource: ( + guildId: string, + source: string, + ) => Promise; +}; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index b1c2649..18da569 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -6,3 +6,5 @@ export * from './roles'; export * from './reminders'; export * from './announcements'; export * from './events'; +export * from './polls'; +export * from './movies'; diff --git a/src/core/services/movies.ts b/src/core/services/movies.ts new file mode 100644 index 0000000..81f9ec7 --- /dev/null +++ b/src/core/services/movies.ts @@ -0,0 +1,175 @@ +import { + movieLabel, + parseFutureWhen, + parseWhen, + UserError, + type Actor, +} from '~/domain'; +import type { Authorizer, MovieRepository } from '~/core/ports'; +import type { EventService } from './events'; +import { guard } from './guard'; +import type { PollService } from './polls'; + +const pollSource = 'movies'; + +export type MovieNight = { + start: string; + movieId?: number; + location?: string; + capacity?: number; + channelId: string; +}; + +type Deps = { + movies: MovieRepository; + polls: PollService; + events: EventService; + authz: Authorizer; + timezone: (guildId: string) => Promise; +}; + +export function createMovieService(deps: Deps) { + const { movies, polls, events, authz, timezone } = deps; + + const pick = async (actor: Actor, movieId: number | undefined) => { + if (movieId !== undefined) { + return { movie: await movies.find(actor.guildId, movieId), pollId: null }; + } + + const poll = await polls.latestBySource(actor.guildId, pollSource); + + if (poll?.status !== 'closed') { + throw new UserError('Pick a movie, or close a "/movie vote" poll first.'); + } + + const { winners, tie } = await polls.results(poll); + const [winner] = winners; + + if (winner === undefined) { + throw new UserError('The last movie poll had no votes. Pick a movie.'); + } + + if (tie) { + const tied = winners.map((w) => `#${w.ref ?? '?'} ${w.label}`).join(', '); + + throw new UserError( + `The last poll is a tie between ${tied}. Pick one with the "movie" option.`, + ); + } + + return { + movie: await movies.find(actor.guildId, Number(winner.ref)), + pollId: poll.id, + }; + }; + + return { + pick, + suggest: ( + actor: Actor, + suggestion: { title: string; year: number | null; note: string | null }, + ) => + movies.suggest({ + ...suggestion, + guildId: actor.guildId, + suggestedBy: actor.userId, + }), + unwatched: (guildId: string, limit?: number) => + movies.unwatched(guildId, limit), + history: (guildId: string) => movies.history(guildId), + remove: async (actor: Actor, id: number) => { + const movie = await movies.find(actor.guildId, id); + + if (movie.suggestedBy !== actor.userId) { + await authz.require(actor, 'movie:manage'); + } + + await movies.remove(movie.id); + + return movie; + }, + vote: guard( + authz, + 'movie:manage', + async ( + actor, + request: { count?: number; closes?: string; channelId: string }, + ) => { + const candidates = await movies.unwatched( + actor.guildId, + request.count ?? 10, + ); + + if (candidates.length < 2) { + throw new UserError( + 'At least two unwatched suggestions are needed for a vote.', + ); + } + + const closesAt = parseFutureWhen( + request.closes ?? '2d', + await timezone(actor.guildId), + ); + + return polls.publish(actor, { + guildId: actor.guildId, + channelId: request.channelId, + creatorId: actor.userId, + question: '🎬 What should we watch next?', + options: candidates.map((m) => ({ + label: movieLabel(m).slice(0, 100), + ref: String(m.id), + })), + closesAt, + source: pollSource, + }); + }, + ), + night: guard(authz, 'movie:manage', async (actor, night: MovieNight) => { + const { movie, pollId } = await pick(actor, night.movieId); + const zone = await timezone(actor.guildId); + const startsAt = parseFutureWhen(night.start, zone); + const event = await events.publish(actor, { + guildId: actor.guildId, + title: `🎬 Movie night: ${movieLabel(movie)}`.slice(0, 200), + description: movie.note, + startsAt, + endsAt: null, + timezone: zone, + location: night.location ?? null, + organizerId: actor.userId, + channelId: night.channelId, + capacity: night.capacity ?? null, + mentionRoleId: null, + reminderMinutes: [60], + }); + + await movies.recordScreening({ + guildId: actor.guildId, + suggestionId: movie.id, + eventId: event.id, + pollId, + scheduledFor: startsAt, + }); + + return { movie, event }; + }), + watched: guard( + authz, + 'movie:manage', + async (actor, id: number, date?: string) => { + const movie = await movies.find(actor.guildId, id); + const at = + date === undefined + ? new Date() + : parseWhen(date, await timezone(actor.guildId)); + + await movies.markWatched(actor.guildId, movie.id, at); + + return movie; + }, + ), + }; +} + +export type MovieService = ReturnType; diff --git a/src/core/services/polls.ts b/src/core/services/polls.ts new file mode 100644 index 0000000..caf22ef --- /dev/null +++ b/src/core/services/polls.ts @@ -0,0 +1,296 @@ +import { z } from 'zod'; +import { + channelMention, + controlId, + discordTime, + isPollOpen, + parseFutureWhen, + UserError, + type Actor, + type Message, +} from '~/domain'; +import type { + Authorizer, + Directory, + Logger, + Messenger, + NewPoll, + Poll, + PollRepository, + PollResults, + PollWithOptions, + Scheduler, +} from '~/core/ports'; +import { defineJob } from './jobs'; + +const closeKey = (id: number) => `poll:${id}:close`; + +export type PollRequest = { + question: string; + options: readonly string[]; + channelId: string; + multiple?: boolean; + anonymous?: boolean; + showResults?: 'live' | 'closed'; + closes?: string; +}; + +function bar(votes: number, total: number): string { + const filled = total === 0 ? 0 : Math.round((votes / total) * 10); + + return '█'.repeat(filled) + '░'.repeat(10 - filled); +} + +export function describeOutcome(results: PollResults, leader: string): string { + const label = results.tie ? 'Tie' : leader; + + return `**${label}:** ${results.winners.map((w) => w.label).join(', ')}`; +} + +function statusLine(poll: Poll, open: boolean): string { + if (open) { + return poll.closesAt === null + ? 'Open' + : `Closes ${discordTime(poll.closesAt, 'R')}`; + } + + return poll.status === 'cancelled' ? 'Cancelled' : 'Closed'; +} + +export function pollView(poll: PollWithOptions, results: PollResults): Message { + const open = isPollOpen(poll); + const showCounts = poll.showResults === 'live' || !open; + const lines = results.options.map((option) => + showCounts + ? `**${option.label}**\n${bar(option.votes, results.voters)} ${option.votes}` + : `• ${option.label}`, + ); + const outcome = + !open && results.winners.length > 0 + ? `\n\n${describeOutcome(results, 'Winner')}` + : ''; + const footer = [ + `Poll #${poll.id}`, + poll.multiple ? 'multiple choice' : 'single choice', + poll.anonymous ? 'anonymous' : 'votes visible to organizers', + `${results.voters} voter${results.voters === 1 ? '' : 's'}`, + statusLine(poll, open), + ].join(' · '); + + return { + embeds: [ + { + title: poll.question, + description: `${lines.join('\n')}${outcome}`, + footer, + }, + ], + controls: open + ? [ + [ + { + kind: 'select', + id: controlId('polls:vote', poll.id), + placeholder: poll.multiple ? 'Choose one or more' : 'Choose one', + min: 1, + max: poll.multiple ? poll.options.length : 1, + options: poll.options.map((option) => ({ + label: option.label, + value: String(option.id), + })), + }, + ], + [ + { + kind: 'button', + id: controlId('polls:clear', poll.id), + label: 'Clear my vote', + style: 'secondary', + }, + ], + ] + : [], + }; +} + +type Deps = { + polls: PollRepository; + scheduler: Scheduler; + messenger: Messenger; + directory: Directory; + authz: Authorizer; + log: Logger; + timezone: (guildId: string) => Promise; +}; + +export function createPollService(deps: Deps) { + const { polls, scheduler, messenger, directory, authz, log } = deps; + + const refresh = async (id: number) => { + const poll = await polls.find(id); + + if (poll?.messageId === undefined || poll.messageId === null) { + return; + } + + if ( + !(await messenger.edit( + poll.channelId, + poll.messageId, + pollView(poll, await polls.results(poll)), + )) + ) { + log.warn({ pollId: id }, 'Poll message or channel was deleted'); + } + }; + + const closeJob = defineJob({ + type: 'polls:close', + payload: z.object({ pollId: z.number().int() }), + handle: async ({ pollId }) => { + if (await polls.finish(pollId, 'closed')) { + await refresh(pollId); + } + }, + }); + + const publish = async (actor: Actor, input: NewPoll) => { + if (!(await directory.canPost(actor, input.channelId))) { + throw new UserError( + `You cannot post in ${channelMention(input.channelId)} yourself.`, + ); + } + + const poll = await polls.insert(input); + const sent = await messenger.send( + poll.channelId, + pollView(poll, await polls.results(poll)), + ); + + await polls.setMessage(poll.id, sent.messageId); + + if (poll.closesAt !== null) { + await scheduler.schedule( + closeJob, + { pollId: poll.id }, + { runAt: poll.closesAt, key: closeKey(poll.id) }, + ); + } + + return { ...poll, messageId: sent.messageId }; + }; + + const requirePoll = async (actor: Actor, id: number) => { + const poll = await polls.find(id); + + if (poll?.guildId !== actor.guildId) { + throw new UserError(`Poll #${id} does not exist.`); + } + + return poll; + }; + + const isManager = async (actor: Actor, poll: Poll) => + poll.creatorId === actor.userId || authz.can(actor, 'poll:manage'); + + const requireManager = async (actor: Actor, id: number) => { + const poll = await requirePoll(actor, id); + + if (poll.creatorId !== actor.userId) { + await authz.require(actor, 'poll:manage'); + } + + return poll; + }; + + const vote = async ( + actor: Actor, + id: number, + optionIds: readonly number[], + ) => { + await requirePoll(actor, id); + await polls.vote(id, actor.userId, optionIds); + + const poll = await requirePoll(actor, id); + const chosen = poll.options + .filter((o) => optionIds.includes(o.id)) + .map((o) => o.label); + + return { view: pollView(poll, await polls.results(poll)), chosen }; + }; + + return { + jobs: [closeJob], + publish, + results: (poll: PollWithOptions) => polls.results(poll), + latestBySource: (guildId: string, source: string) => + polls.latestBySource(guildId, source), + open: (guildId: string) => polls.open(guildId), + create: async (actor: Actor, request: PollRequest) => { + await authz.require(actor, 'poll:create'); + + const zone = await deps.timezone(actor.guildId); + + return publish(actor, { + guildId: actor.guildId, + channelId: request.channelId, + creatorId: actor.userId, + question: request.question, + options: request.options.map((label) => ({ label })), + multiple: request.multiple ?? false, + anonymous: request.anonymous ?? false, + showResults: request.showResults ?? 'live', + closesAt: + request.closes === undefined + ? null + : parseFutureWhen(request.closes, zone), + }); + }, + vote, + clear: async (actor: Actor, id: number) => { + const current = await polls.choices(id, actor.userId); + + if (current.length === 0) { + throw new UserError('You have not voted.'); + } + + return vote(actor, id, []); + }, + summary: async (actor: Actor, id: number) => { + const poll = await requirePoll(actor, id); + const manager = await isManager(actor, poll); + + if (poll.showResults === 'closed' && isPollOpen(poll) && !manager) { + throw new UserError('Results are shown when the poll closes.'); + } + + const results = await polls.results(poll); + const voters = + !poll.anonymous && manager ? await polls.voters(poll.id) : undefined; + + return { poll, results, voters }; + }, + close: async (actor: Actor, id: number) => { + await requireManager(actor, id); + + if (!(await polls.finish(id, 'closed'))) { + throw new UserError('That poll is not open.'); + } + + await scheduler.cancel(closeKey(id)); + await refresh(id); + }, + cancel: async (actor: Actor, id: number) => { + await requireManager(actor, id); + + if (!(await polls.finish(id, 'cancelled'))) { + throw new UserError('That poll is not open.'); + } + + await scheduler.cancel(closeKey(id)); + await refresh(id); + }, + }; +} + +export type PollService = ReturnType; diff --git a/src/domain/index.ts b/src/domain/index.ts index 24fcec3..328212b 100644 --- a/src/domain/index.ts +++ b/src/domain/index.ts @@ -4,3 +4,5 @@ export * from './message'; export * from './permission'; export * from './role'; export * from './time'; +export * from './poll'; +export * from './movie'; diff --git a/src/domain/movie.ts b/src/domain/movie.ts new file mode 100644 index 0000000..6178b03 --- /dev/null +++ b/src/domain/movie.ts @@ -0,0 +1,10 @@ +export function normalizeTitle(title: string): string { + return title + .normalize('NFKD') + .toLowerCase() + .replaceAll(/[^\p{L}\p{N}]+/gu, ' ') + .trim(); +} + +export const movieLabel = (movie: { title: string; year: number | null }) => + movie.year === null ? movie.title : `${movie.title} (${movie.year})`; diff --git a/src/domain/poll.ts b/src/domain/poll.ts new file mode 100644 index 0000000..8b498eb --- /dev/null +++ b/src/domain/poll.ts @@ -0,0 +1,57 @@ +import { UserError } from './errors'; + +export const maxPollOptions = 25; + +export type Tally = { + options: Array; + voters: number; + winners: Array; + tie: boolean; +}; + +export function isPollOpen( + poll: { status: string; closesAt: Date | null }, + now = new Date(), +): boolean { + return ( + poll.status === 'open' && (poll.closesAt === null || poll.closesAt > now) + ); +} + +export function tally( + options: readonly O[], + votes: ReadonlyMap, + voters: number, +): Tally { + const counted = options.map((option) => ({ + ...option, + votes: votes.get(option.id) ?? 0, + })); + const top = Math.max(0, ...counted.map((option) => option.votes)); + const winners = + top === 0 ? [] : counted.filter((option) => option.votes === top); + + return { options: counted, voters, winners, tie: winners.length > 1 }; +} + +export function validatePollOptions(labels: readonly string[]): string[] { + const trimmed = labels.map((label) => label.trim()); + + if (trimmed.length < 2 || trimmed.length > maxPollOptions) { + throw new UserError( + `A poll needs between 2 and ${maxPollOptions} options.`, + ); + } + + if (trimmed.some((label) => label === '' || label.length > 100)) { + throw new UserError('Options must be 1–100 characters.'); + } + + if ( + new Set(trimmed.map((label) => label.toLowerCase())).size !== trimmed.length + ) { + throw new UserError('Options must be distinct.'); + } + + return trimmed; +} diff --git a/src/features/movies/index.ts b/src/features/movies/index.ts deleted file mode 100644 index a27d719..0000000 --- a/src/features/movies/index.ts +++ /dev/null @@ -1,356 +0,0 @@ -import { toActor, respond, bySubcommand } from '~/infra/discord'; -import { - ChannelType, - InteractionContextType, - MessageFlags, - SlashCommandBuilder, - type SlashCommandIntegerOption, -} from 'discord.js'; -import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { UserError, discordTime, parseFutureWhen, parseWhen } from '~/domain'; -import type { EventService } from '~/core/services'; -import { createPoll, getResults, latestPollBySource } from '~/features/polls'; -import type { MovieSuggestion } from './schema'; -import { - listUnwatched, - markWatched, - recordScreening, - removeSuggestion, - requireSuggestion, - suggestMovie, - watchHistory, -} from './service'; - -const pollSource = 'movies'; - -const label = (movie: Pick) => - movie.year === null ? movie.title : `${movie.title} (${movie.year})`; - -export async function pickMovie( - ctx: AppContext, - guildId: string, - movieId: number | null, -) { - if (movieId !== null) { - return { - movie: await requireSuggestion(ctx.db, guildId, movieId), - pollId: null, - }; - } - - const poll = await latestPollBySource(ctx.db, guildId, pollSource); - - if (poll?.status !== 'closed') { - throw new UserError('Pick a movie, or close a `/movie vote` poll first.'); - } - - const { winners, tie } = await getResults(ctx.db, poll); - - if (winners.length === 0) { - throw new UserError('The last movie poll had no votes. Pick a movie.'); - } - - if (tie) { - const tied = winners.map((w) => `#${w.ref ?? '?'} ${w.label}`).join(', '); - - throw new UserError( - `The last poll is a tie between ${tied}. Pick one with the \`movie\` option.`, - ); - } - - const winner = winners[0]; - - return { - movie: await requireSuggestion(ctx.db, guildId, Number(winner?.ref)), - pollId: poll.id, - }; -} - -const movieOption = (o: SlashCommandIntegerOption) => - o.setName('movie').setDescription('Movie').setAutocomplete(true); - -const data = new SlashCommandBuilder() - .setName('movie') - .setDescription('Movie suggestions and movie nights') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('suggest') - .setDescription('Suggest a movie') - .addStringOption((o) => - o - .setName('title') - .setDescription('Title') - .setRequired(true) - .setMaxLength(200), - ) - .addIntegerOption((o) => - o - .setName('year') - .setDescription('Release year') - .setMinValue(1880) - .setMaxValue(2100), - ) - .addStringOption((o) => - o.setName('note').setDescription('Why watch it?').setMaxLength(300), - ), - ) - .addSubcommand((sub) => - sub.setName('suggestions').setDescription('Movies waiting to be watched'), - ) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription('Remove a suggestion') - .addIntegerOption((o) => movieOption(o).setRequired(true)), - ) - .addSubcommand((sub) => - sub - .setName('vote') - .setDescription('Start a poll over the suggestions') - .addIntegerOption((o) => - o - .setName('count') - .setDescription('How many movies (default 10)') - .setMinValue(2) - .setMaxValue(25), - ) - .addStringOption((o) => - o.setName('closes').setDescription('When voting ends (default 2d)'), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Where to post (default: here)') - .addChannelTypes(ChannelType.GuildText), - ), - ) - .addSubcommand((sub) => - sub - .setName('night') - .setDescription( - 'Schedule a movie night (defaults to the last poll winner)', - ) - .addStringOption((o) => - o - .setName('start') - .setDescription('e.g. 2026-11-20 19:00') - .setRequired(true), - ) - .addIntegerOption(movieOption) - .addStringOption((o) => - o.setName('location').setDescription('Where').setMaxLength(200), - ) - .addIntegerOption((o) => - o.setName('capacity').setDescription('Seats').setMinValue(1), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Where to post (default: here)') - .addChannelTypes(ChannelType.GuildText), - ), - ) - .addSubcommand((sub) => - sub - .setName('watched') - .setDescription('Mark a movie as watched') - .addIntegerOption((o) => movieOption(o).setRequired(true)) - .addStringOption((o) => - o.setName('date').setDescription('When (default: now)'), - ), - ) - .addSubcommand((sub) => - sub.setName('history').setDescription('Movies we have watched'), - ); - -const zoneOf = (interaction: CommandInteraction, ctx: AppContext) => - getGuildTimezone(ctx.db, interaction.guildId, ctx.config.DEFAULT_TIMEZONE); - -export const createMoviesFeature = (events: EventService): Feature => ({ - name: 'movies', - permissions: [ - { - id: 'movie:manage', - description: 'Run movie votes and movie nights, remove suggestions', - }, - ], - commands: [ - { - data: data.toJSON(), - permissions: { - vote: 'movie:manage', - night: 'movie:manage', - watched: 'movie:manage', - }, - execute: bySubcommand({ - suggest: async (interaction, ctx) => { - const movie = await suggestMovie(ctx.db, { - guildId: interaction.guildId, - title: interaction.options.getString('title', true), - year: interaction.options.getInteger('year'), - note: interaction.options.getString('note'), - suggestedBy: interaction.user.id, - }); - - await respond( - interaction, - `Added #${movie.id} ${label(movie)} to the list.`, - ); - }, - suggestions: async (interaction, ctx) => { - const movies = await listUnwatched(ctx.db, interaction.guildId); - - await respond( - interaction, - movies.length === 0 - ? 'No suggestions yet. Add one with `/movie suggest`.' - : movies - .map((m) => `#${m.id} ${label(m)} — <@${m.suggestedBy}>`) - .join('\n'), - ); - }, - remove: async (interaction, ctx) => { - const movie = await requireSuggestion( - ctx.db, - interaction.guildId, - interaction.options.getInteger('movie', true), - ); - - if (movie.suggestedBy !== interaction.user.id) { - await ctx.authz.require( - toActor(interaction.member), - 'movie:manage', - ); - } - - await removeSuggestion(ctx.db, movie.id); - await respond(interaction, `Removed ${label(movie)}.`); - }, - vote: async (interaction, ctx) => { - const movies = await listUnwatched( - ctx.db, - interaction.guildId, - interaction.options.getInteger('count') ?? 10, - ); - - if (movies.length < 2) { - throw new UserError( - 'At least two unwatched suggestions are needed for a vote.', - ); - } - - const closesAt = parseFutureWhen( - interaction.options.getString('closes') ?? '2d', - await zoneOf(interaction, ctx), - ); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const poll = await createPoll(ctx, { - guildId: interaction.guildId, - channelId: - interaction.options.getChannel('channel')?.id ?? - interaction.channelId, - creatorId: interaction.user.id, - question: '🎬 What should we watch next?', - options: movies.map((m) => ({ - label: label(m).slice(0, 100), - ref: String(m.id), - })), - closesAt, - source: pollSource, - }); - - await interaction.editReply( - `Movie poll #${poll.id} closes ${discordTime(closesAt, 'R')}.`, - ); - }, - night: async (interaction, ctx) => { - const { movie, pollId } = await pickMovie( - ctx, - interaction.guildId, - interaction.options.getInteger('movie'), - ); - const timezone = await zoneOf(interaction, ctx); - const startsAt = parseFutureWhen( - interaction.options.getString('start', true), - timezone, - ); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const event = await events.publish(toActor(interaction.member), { - guildId: interaction.guildId, - title: `🎬 Movie night: ${label(movie)}`.slice(0, 200), - description: movie.note, - startsAt, - timezone, - location: interaction.options.getString('location'), - organizerId: interaction.user.id, - channelId: - interaction.options.getChannel('channel')?.id ?? - interaction.channelId, - capacity: interaction.options.getInteger('capacity'), - endsAt: null, - mentionRoleId: null, - reminderMinutes: [60], - }); - - await recordScreening(ctx.db, { - guildId: interaction.guildId, - suggestionId: movie.id, - eventId: event.id, - pollId, - scheduledFor: startsAt, - }); - await interaction.editReply( - `Movie night for ${label(movie)} is event #${event.id}.`, - ); - }, - watched: async (interaction, ctx) => { - const movie = await requireSuggestion( - ctx.db, - interaction.guildId, - interaction.options.getInteger('movie', true), - ); - const date = interaction.options.getString('date'); - const watchedAt = - date === null - ? new Date() - : parseWhen(date, await zoneOf(interaction, ctx)); - - await markWatched(ctx.db, interaction.guildId, movie.id, watchedAt); - await respond(interaction, `Marked ${label(movie)} as watched.`); - }, - history: async (interaction, ctx) => { - const history = await watchHistory(ctx.db, interaction.guildId); - - await respond( - interaction, - history.length === 0 - ? 'No movies watched yet.' - : history - .map( - (h) => - `${h.watchedAt ? discordTime(h.watchedAt, 'D') : ''} ${label(h)}`, - ) - .join('\n'), - ); - }, - }), - autocomplete: async (interaction, ctx) => { - const query = interaction.options.getFocused().toLowerCase(); - const movies = await listUnwatched(ctx.db, interaction.guildId); - - await interaction.respond( - movies - .filter((m) => m.title.toLowerCase().includes(query)) - .map((m) => ({ - name: `#${m.id} ${label(m)}`.slice(0, 100), - value: m.id, - })), - ); - }, - }, - ], -}); diff --git a/src/features/polls/index.ts b/src/features/polls/index.ts deleted file mode 100644 index d2bad57..0000000 --- a/src/features/polls/index.ts +++ /dev/null @@ -1,498 +0,0 @@ -import { - toActor, - respond, - bySubcommand, - defineJob, - isUnknownObject, - customId, -} from '~/infra/discord'; -import { - ActionRowBuilder, - ButtonBuilder, - ButtonStyle, - ChannelType, - EmbedBuilder, - InteractionContextType, - MessageFlags, - SlashCommandBuilder, - StringSelectMenuBuilder, - userMention, - type BaseMessageOptions, - type SlashCommandIntegerOption, -} from 'discord.js'; -import { z } from 'zod'; -import type { - AppContext, - CommandInteraction, - ComponentHandler, - Feature, -} from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { UserError, discordTime, parseFutureWhen } from '~/domain'; -import type { Poll } from './schema'; -import { - castVote, - finishPoll, - getPoll, - getResults, - getVoterChoices, - getVoters, - insertPoll, - isOpen, - listOpenPolls, - requirePoll, - setPollMessage, - type NewPoll, - type PollResults, - type PollWithOptions, -} from './service'; - -export type { PollResults, PollWithOptions } from './service'; -export { getResults, latestPollBySource } from './service'; - -const closeKey = (id: number) => `poll:${id}:close`; - -function bar(votes: number, total: number): string { - const filled = total === 0 ? 0 : Math.round((votes / total) * 10); - - return '█'.repeat(filled) + '░'.repeat(10 - filled); -} - -function describeOutcome(results: PollResults, leader: string): string { - const label = results.tie ? 'Tie' : leader; - - return `**${label}:** ${results.winners.map((w) => w.label).join(', ')}`; -} - -export function renderPoll( - poll: PollWithOptions, - results: PollResults, -): BaseMessageOptions { - const open = isOpen(poll); - const showCounts = poll.showResults === 'live' || !open; - const lines = results.options.map((option) => - showCounts - ? `**${option.label}**\n${bar(option.votes, results.voters)} ${option.votes}` - : `• ${option.label}`, - ); - let status = poll.status === 'cancelled' ? 'Cancelled' : 'Closed'; - - if (open) { - status = - poll.closesAt === null - ? 'Open' - : `Closes ${discordTime(poll.closesAt, 'R')}`; - } - - const outcome = - !open && results.winners.length > 0 - ? `\n\n${describeOutcome(results, 'Winner')}` - : ''; - const embed = new EmbedBuilder() - .setTitle(poll.question) - .setDescription(`${lines.join('\n')}${outcome}`) - .setFooter({ - text: [ - `Poll #${poll.id}`, - poll.multiple ? 'multiple choice' : 'single choice', - poll.anonymous ? 'anonymous' : 'votes visible to organizers', - `${results.voters} voter${results.voters === 1 ? '' : 's'}`, - status, - ].join(' · '), - }); - - if (!open) { - return { embeds: [embed], components: [] }; - } - - const select = new StringSelectMenuBuilder() - .setCustomId(customId('polls:vote', poll.id)) - .setPlaceholder(poll.multiple ? 'Choose one or more' : 'Choose one') - .setMinValues(1) - .setMaxValues(poll.multiple ? poll.options.length : 1) - .addOptions( - poll.options.map((option) => ({ - label: option.label, - value: String(option.id), - })), - ); - const clear = new ButtonBuilder() - .setCustomId(customId('polls:clear', poll.id)) - .setLabel('Clear my vote') - .setStyle(ButtonStyle.Secondary); - - return { - embeds: [embed], - components: [ - new ActionRowBuilder().addComponents(select), - new ActionRowBuilder().addComponents(clear), - ], - }; -} - -async function refreshMessage(ctx: AppContext, poll: Poll): Promise { - const full = await getPoll(ctx.db, poll.id); - - if (full?.messageId === null || full?.messageId === undefined) { - return; - } - - try { - const channel = await ctx.client.channels.fetch(full.channelId); - - if (channel?.isTextBased() === true) { - await channel.messages.edit( - full.messageId, - renderPoll(full, await getResults(ctx.db, full)), - ); - } - } catch (error) { - if (!isUnknownObject(error)) { - throw error; - } - - ctx.log.warn({ pollId: poll.id }, 'Poll message or channel was deleted'); - } -} - -export const closeJob = defineJob({ - type: 'polls:close', - payload: z.object({ pollId: z.number().int() }), - handle: async ({ pollId }, _info, ctx) => { - const closed = await finishPoll(ctx.db, pollId, 'closed'); - - if (closed) { - await refreshMessage(ctx, closed); - } - }, -}); - -export async function createPoll( - ctx: AppContext, - input: NewPoll, -): Promise { - const channel = await ctx.client.channels - .fetch(input.channelId) - .catch(() => null); - - if (channel?.isSendable() !== true) { - throw new UserError('I cannot post in that channel.'); - } - - const poll = await insertPoll(ctx.db, input); - const message = await channel.send( - renderPoll(poll, await getResults(ctx.db, poll)), - ); - - await setPollMessage(ctx.db, poll.id, message.id); - if (poll.closesAt !== null) { - await ctx.scheduler.schedule( - closeJob, - { pollId: poll.id }, - { runAt: poll.closesAt, key: closeKey(poll.id) }, - ); - } - - return { ...poll, messageId: message.id }; -} - -export async function closePoll( - ctx: AppContext, - pollId: number, -): Promise { - const closed = await finishPoll(ctx.db, pollId, 'closed'); - - if (!closed) { - return false; - } - - await ctx.scheduler.cancel(closeKey(pollId)); - await refreshMessage(ctx, closed); - - return true; -} - -async function vote( - interaction: Parameters[0], - pollId: number, - optionIds: number[], - ctx: AppContext, -): Promise { - await castVote(ctx.db, pollId, interaction.user.id, optionIds); - const poll = await getPoll(ctx.db, pollId); - - if (!poll || interaction.isModalSubmit()) { - return; - } - - const results = await getResults(ctx.db, poll); - - await interaction.update(renderPoll(poll, results)); - const chosen = poll.options - .filter((o) => optionIds.includes(o.id)) - .map((o) => o.label); - - await interaction.followUp({ - content: - chosen.length === 0 - ? 'Your vote is cleared.' - : `Your vote: **${chosen.join(', ')}**`, - flags: MessageFlags.Ephemeral, - }); -} - -function parseId(value: string | undefined): number { - const id = Number(value); - - if (!Number.isSafeInteger(id)) { - throw new UserError('This poll control is invalid.'); - } - - return id; -} - -const voteHandler: ComponentHandler = { - prefix: 'polls:vote', - execute: async (interaction, [id], ctx) => { - if (!interaction.isStringSelectMenu()) { - return; - } - - await vote(interaction, parseId(id), interaction.values.map(Number), ctx); - }, -}; - -const clearHandler: ComponentHandler = { - prefix: 'polls:clear', - execute: async (interaction, [id], ctx) => { - const pollId = parseId(id); - const current = await getVoterChoices(ctx.db, pollId, interaction.user.id); - - if (current.length === 0) { - throw new UserError('You have not voted.'); - } - - await vote(interaction, pollId, [], ctx); - }, -}; - -async function requireManageable( - interaction: CommandInteraction, - ctx: AppContext, -): Promise { - const poll = await requirePoll( - ctx.db, - interaction.guildId, - interaction.options.getInteger('id', true), - ); - - if (poll.creatorId !== interaction.user.id) { - await ctx.authz.require(toActor(interaction.member), 'poll:manage'); - } - - return poll; -} - -const idOption = (o: SlashCommandIntegerOption) => - o - .setName('id') - .setDescription('Poll') - .setRequired(true) - .setAutocomplete(true); - -const data = new SlashCommandBuilder() - .setName('poll') - .setDescription('Polls') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Start a poll') - .addStringOption((o) => - o - .setName('question') - .setDescription('Question') - .setRequired(true) - .setMaxLength(256), - ) - .addStringOption((o) => - o - .setName('options') - .setDescription('Options separated by | e.g. "Pizza | Sushi | Tacos"') - .setRequired(true), - ) - .addBooleanOption((o) => - o.setName('multiple').setDescription('Allow several choices'), - ) - .addBooleanOption((o) => - o.setName('anonymous').setDescription('Hide who voted for what'), - ) - .addStringOption((o) => - o - .setName('results') - .setDescription('When results are visible') - .addChoices( - { name: 'live', value: 'live' }, - { name: 'after closing', value: 'closed' }, - ), - ) - .addStringOption((o) => - o.setName('closes').setDescription('e.g. 1d, 2h, 2026-11-20 18:00'), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Where to post (default: here)') - .addChannelTypes(ChannelType.GuildText), - ), - ) - .addSubcommand((sub) => sub.setName('list').setDescription('Open polls')) - .addSubcommand((sub) => - sub - .setName('results') - .setDescription('Show results') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('close') - .setDescription('Close a poll now') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('cancel') - .setDescription('Cancel a poll') - .addIntegerOption(idOption), - ); - -async function showResults( - interaction: CommandInteraction, - ctx: AppContext, -): Promise { - const poll = await requirePoll( - ctx.db, - interaction.guildId, - interaction.options.getInteger('id', true), - ); - const manager = - poll.creatorId === interaction.user.id || - (await ctx.authz.can(toActor(interaction.member), 'poll:manage')); - - if (poll.showResults === 'closed' && isOpen(poll) && !manager) { - throw new UserError('Results are shown when the poll closes.'); - } - - const results = await getResults(ctx.db, poll); - const voters = - !poll.anonymous && manager ? await getVoters(ctx.db, poll.id) : undefined; - const lines = results.options.map((option) => { - const names = voters?.get(option.id)?.map((id) => userMention(id)) ?? []; - - return [`**${option.label}** — ${option.votes}`, ...names].join(' '); - }); - const winner = - results.winners.length === 0 - ? 'No votes yet.' - : describeOutcome(results, 'Leading'); - - await respond( - interaction, - [`**${poll.question}**`, ...lines, winner].join('\n').slice(0, 2000), - ); -} - -export const pollsFeature: Feature = { - name: 'polls', - permissions: [ - { id: 'poll:create', description: 'Start polls' }, - { id: 'poll:manage', description: 'Close and cancel any poll, see voters' }, - ], - jobs: [closeJob], - components: [voteHandler, clearHandler], - commands: [ - { - data: data.toJSON(), - permissions: { create: 'poll:create' }, - execute: bySubcommand({ - create: async (interaction, ctx) => { - const closes = interaction.options.getString('closes'); - const zone = await getGuildTimezone( - ctx.db, - interaction.guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const poll = await createPoll(ctx, { - guildId: interaction.guildId, - channelId: - interaction.options.getChannel('channel')?.id ?? - interaction.channelId, - creatorId: interaction.user.id, - question: interaction.options.getString('question', true), - options: interaction.options - .getString('options', true) - .split('|') - .map((label) => ({ label })), - multiple: interaction.options.getBoolean('multiple') ?? false, - anonymous: interaction.options.getBoolean('anonymous') ?? false, - showResults: - interaction.options.getString('results') === 'closed' - ? 'closed' - : 'live', - closesAt: closes === null ? null : parseFutureWhen(closes, zone), - }); - - await interaction.editReply( - `Poll #${poll.id} is up in <#${poll.channelId}>.`, - ); - }, - list: async (interaction, ctx) => { - const open = await listOpenPolls(ctx.db, interaction.guildId); - - await respond( - interaction, - open.length === 0 - ? 'No open polls.' - : open - .map((p) => `#${p.id} ${p.question} — <#${p.channelId}>`) - .join('\n'), - ); - }, - results: showResults, - close: async (interaction, ctx) => { - const poll = await requireManageable(interaction, ctx); - - if (!(await closePoll(ctx, poll.id))) { - throw new UserError('That poll is not open.'); - } - - await respond(interaction, `Poll #${poll.id} is closed.`); - }, - cancel: async (interaction, ctx) => { - const poll = await requireManageable(interaction, ctx); - const cancelled = await finishPoll(ctx.db, poll.id, 'cancelled'); - - if (!cancelled) { - throw new UserError('That poll is not open.'); - } - - await ctx.scheduler.cancel(closeKey(poll.id)); - await refreshMessage(ctx, cancelled); - await respond(interaction, `Poll #${poll.id} is cancelled.`); - }, - }), - autocomplete: async (interaction, ctx) => { - const open = await listOpenPolls(ctx.db, interaction.guildId); - - await interaction.respond( - open.map((p) => ({ - name: `#${p.id} ${p.question}`.slice(0, 100), - value: p.id, - })), - ); - }, - }, - ], -}; diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index 9113f53..a18cda7 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -12,3 +12,7 @@ export * from './announcements/model'; export * from './announcements/repo'; export * from './events/model'; export * from './events/repo'; +export * from './polls/model'; +export * from './polls/repo'; +export * from './movies/model'; +export * from './movies/repo'; diff --git a/src/features/movies/schema.ts b/src/infra/db/movies/model.ts similarity index 100% rename from src/features/movies/schema.ts rename to src/infra/db/movies/model.ts diff --git a/src/features/movies/service.ts b/src/infra/db/movies/repo.ts similarity index 86% rename from src/features/movies/service.ts rename to src/infra/db/movies/repo.ts index 8e6c3ee..2f7274a 100644 --- a/src/features/movies/service.ts +++ b/src/infra/db/movies/repo.ts @@ -1,19 +1,12 @@ import { and, asc, desc, eq, isNotNull, isNull, notExists } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; -import { UserError } from '~/domain'; +import type { MovieRepository } from '~/core/ports'; +import type { Db } from '../client'; +import { normalizeTitle, UserError } from '~/domain'; import { movieScreenings, movieSuggestions, type MovieSuggestion, -} from './schema'; - -export function normalizeTitle(title: string): string { - return title - .normalize('NFKD') - .toLowerCase() - .replaceAll(/[^\p{L}\p{N}]+/gu, ' ') - .trim(); -} +} from './model'; const watched = (db: Db) => db @@ -214,3 +207,16 @@ export async function watchHistory(db: Db, guildId: string, limit = 25) { .orderBy(desc(movieScreenings.watchedAt)) .limit(limit); } + +export function createMovieRepository(db: Db): MovieRepository { + return { + suggest: (suggestion) => suggestMovie(db, suggestion), + find: (guildId, id) => requireSuggestion(db, guildId, id), + unwatched: (guildId, limit) => listUnwatched(db, guildId, limit), + remove: (id) => removeSuggestion(db, id), + recordScreening: (screening) => recordScreening(db, screening), + markWatched: (guildId, suggestionId, at) => + markWatched(db, guildId, suggestionId, at), + history: (guildId, limit) => watchHistory(db, guildId, limit), + }; +} diff --git a/src/features/polls/schema.ts b/src/infra/db/polls/model.ts similarity index 100% rename from src/features/polls/schema.ts rename to src/infra/db/polls/model.ts diff --git a/src/features/polls/service.ts b/src/infra/db/polls/repo.ts similarity index 69% rename from src/features/polls/service.ts rename to src/infra/db/polls/repo.ts index eb0a9b4..a529add 100644 --- a/src/features/polls/service.ts +++ b/src/infra/db/polls/repo.ts @@ -8,58 +8,23 @@ import { inArray, sql, } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; -import { UserError } from '~/domain'; -import { - pollOptions, - polls, - pollVotes, - type Poll, - type PollOption, -} from './schema'; - -export const maxOptions = 25; - -export type NewPoll = Pick< - Poll, - 'guildId' | 'channelId' | 'creatorId' | 'question' -> & - Partial< - Pick - > & { - options: ReadonlyArray<{ label: string; ref?: string | null }>; - }; - -export type PollWithOptions = Poll & { options: PollOption[] }; - -export type OptionResult = PollOption & { votes: number }; - -export type PollResults = { - options: OptionResult[]; - voters: number; - winners: OptionResult[]; - tie: boolean; -}; +import type { + NewPoll, + PollRepository, + PollResults, + PollWithOptions, +} from '~/core/ports'; +import type { Db } from '../client'; +import { isPollOpen, tally, UserError, validatePollOptions } from '~/domain'; +import { pollOptions, polls, pollVotes, type Poll } from './model'; export async function insertPoll( db: Db, input: NewPoll, ): Promise { - const labels = input.options.map((option) => option.label.trim()); - - if (labels.length < 2 || labels.length > maxOptions) { - throw new UserError(`A poll needs between 2 and ${maxOptions} options.`); - } - - if (labels.some((label) => label === '' || label.length > 100)) { - throw new UserError('Options must be 1–100 characters.'); - } - - if ( - new Set(labels.map((label) => label.toLowerCase())).size !== labels.length - ) { - throw new UserError('Options must be distinct.'); - } + const labels = validatePollOptions( + input.options.map((option) => option.label), + ); return db.transaction(async (tx) => { const { options, ...values } = input; @@ -107,26 +72,6 @@ export async function getPoll( return { ...poll, options }; } -export async function requirePoll( - db: Db, - guildId: string, - id: number, -): Promise { - const poll = await getPoll(db, id); - - if (poll?.guildId !== guildId) { - throw new UserError(`Poll #${id} does not exist.`); - } - - return poll; -} - -export function isOpen(poll: Poll, now = new Date()): boolean { - return ( - poll.status === 'open' && (poll.closesAt === null || poll.closesAt > now) - ); -} - export async function castVote( db: Db, pollId: number, @@ -140,7 +85,7 @@ export async function castVote( .where(eq(polls.id, pollId)) .for('update'); - if (!poll || !isOpen(poll)) { + if (!poll || !isPollOpen(poll)) { throw new UserError('This poll is closed.'); } @@ -189,21 +134,12 @@ export async function getResults( .from(pollVotes) .where(eq(pollVotes.pollId, poll.id)), ]); - const byOption = new Map(counts.map((row) => [row.optionId, row.votes])); - const options = poll.options.map((option) => ({ - ...option, - votes: byOption.get(option.id) ?? 0, - })); - const top = Math.max(0, ...options.map((option) => option.votes)); - const winners = - top === 0 ? [] : options.filter((option) => option.votes === top); - return { - options, - voters: voters?.total ?? 0, - winners, - tie: winners.length > 1, - }; + return tally( + poll.options, + new Map(counts.map((row) => [row.optionId, row.votes])), + voters?.total ?? 0, + ); } export async function getVoterChoices( @@ -288,3 +224,20 @@ export async function latestPollBySource( return row ? getPoll(db, row.id) : undefined; } + +export function createPollRepository(db: Db): PollRepository { + return { + insert: (poll) => insertPoll(db, poll), + find: (id) => getPoll(db, id), + vote: (pollId, userId, optionIds) => + castVote(db, pollId, userId, optionIds), + results: (poll) => getResults(db, poll), + choices: (pollId, userId) => getVoterChoices(db, pollId, userId), + voters: (pollId) => getVoters(db, pollId), + finish: (id, status) => finishPoll(db, id, status), + setMessage: (id, messageId) => setPollMessage(db, id, messageId), + open: (guildId) => listOpenPolls(db, guildId), + latestBySource: (guildId, source) => + latestPollBySource(db, guildId, source), + }; +} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index e4a2057..d1ffe36 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -4,3 +4,5 @@ export * from './roles'; export * from './reminders'; export * from './announcements'; export * from './events'; +export * from './polls'; +export * from './movies'; diff --git a/src/infra/discord/commands/movies.ts b/src/infra/discord/commands/movies.ts new file mode 100644 index 0000000..dfd7e39 --- /dev/null +++ b/src/infra/discord/commands/movies.ts @@ -0,0 +1,243 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, + type SlashCommandIntegerOption, +} from 'discord.js'; +import type { MovieService } from '~/core/services'; +import { discordTime, movieLabel, userMention } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred } from '../define'; +import type { Feature } from '../module'; +import { respond } from '../router'; + +const movieOption = (o: SlashCommandIntegerOption) => + o.setName('movie').setDescription('Movie').setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('movie') + .setDescription('Movie suggestions and movie nights') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('suggest') + .setDescription('Suggest a movie') + .addStringOption((o) => + o + .setName('title') + .setDescription('Title') + .setRequired(true) + .setMaxLength(200), + ) + .addIntegerOption((o) => + o + .setName('year') + .setDescription('Release year') + .setMinValue(1880) + .setMaxValue(2100), + ) + .addStringOption((o) => + o.setName('note').setDescription('Why watch it?').setMaxLength(300), + ), + ) + .addSubcommand((sub) => + sub.setName('suggestions').setDescription('Movies waiting to be watched'), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription('Remove a suggestion') + .addIntegerOption((o) => movieOption(o).setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('vote') + .setDescription('Start a poll over the suggestions') + .addIntegerOption((o) => + o + .setName('count') + .setDescription('How many movies (default 10)') + .setMinValue(2) + .setMaxValue(25), + ) + .addStringOption((o) => + o.setName('closes').setDescription('When voting ends (default 2d)'), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => + sub + .setName('night') + .setDescription( + 'Schedule a movie night (defaults to the last poll winner)', + ) + .addStringOption((o) => + o + .setName('start') + .setDescription('e.g. 2026-11-20 19:00') + .setRequired(true), + ) + .addIntegerOption(movieOption) + .addStringOption((o) => + o.setName('location').setDescription('Where').setMaxLength(200), + ) + .addIntegerOption((o) => + o.setName('capacity').setDescription('Seats').setMinValue(1), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => + sub + .setName('watched') + .setDescription('Mark a movie as watched') + .addIntegerOption((o) => movieOption(o).setRequired(true)) + .addStringOption((o) => + o.setName('date').setDescription('When (default: now)'), + ), + ) + .addSubcommand((sub) => + sub.setName('history').setDescription('Movies we have watched'), + ); + +export function movieCommands(movies: MovieService): Feature { + return { + name: 'movies', + permissions: [ + { + id: 'movie:manage', + description: 'Run movie votes and movie nights, remove suggestions', + }, + ], + commands: [ + { + data: data.toJSON(), + execute: bySubcommand({ + suggest: async (interaction) => { + const movie = await movies.suggest(toActor(interaction.member), { + title: interaction.options.getString('title', true), + year: interaction.options.getInteger('year'), + note: interaction.options.getString('note'), + }); + + await respond( + interaction, + `Added #${movie.id} ${movieLabel(movie)} to the list.`, + ); + }, + suggestions: async (interaction) => { + const list = await movies.unwatched(interaction.guildId); + + await respond( + interaction, + list.length === 0 + ? 'No suggestions yet. Add one with "/movie suggest".' + : list + .map( + (m) => + `#${m.id} ${movieLabel(m)} — ${userMention(m.suggestedBy)}`, + ) + .join('\n'), + ); + }, + remove: async (interaction) => { + const movie = await movies.remove( + toActor(interaction.member), + interaction.options.getInteger('movie', true), + ); + + await respond(interaction, `Removed ${movieLabel(movie)}.`); + }, + vote: deferred(async (interaction) => { + const count = interaction.options.getInteger('count'); + const closes = interaction.options.getString('closes'); + const poll = await movies.vote(toActor(interaction.member), { + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + ...(count !== null && { count }), + ...(closes !== null && { closes }), + }); + + await respond( + interaction, + `Movie poll #${poll.id} closes ${discordTime(poll.closesAt ?? new Date(), 'R')}.`, + ); + }), + night: deferred(async (interaction) => { + const movieId = interaction.options.getInteger('movie'); + const location = interaction.options.getString('location'); + const capacity = interaction.options.getInteger('capacity'); + const { movie, event } = await movies.night( + toActor(interaction.member), + { + start: interaction.options.getString('start', true), + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + ...(movieId !== null && { movieId }), + ...(location !== null && { location }), + ...(capacity !== null && { capacity }), + }, + ); + + await respond( + interaction, + `Movie night for ${movieLabel(movie)} is event #${event.id}.`, + ); + }), + watched: async (interaction) => { + const date = interaction.options.getString('date'); + const movie = await movies.watched( + toActor(interaction.member), + interaction.options.getInteger('movie', true), + ...(date === null ? [] : [date]), + ); + + await respond( + interaction, + `Marked ${movieLabel(movie)} as watched.`, + ); + }, + history: async (interaction) => { + const history = await movies.history(interaction.guildId); + + await respond( + interaction, + history.length === 0 + ? 'No movies watched yet.' + : history + .map( + (h) => + `${h.watchedAt ? discordTime(h.watchedAt, 'D') : ''} ${movieLabel(h)}`, + ) + .join('\n'), + ); + }, + }), + autocomplete: async (interaction) => { + const query = interaction.options.getFocused().toLowerCase(); + const list = await movies.unwatched(interaction.guildId); + + await interaction.respond( + list + .filter((m) => m.title.toLowerCase().includes(query)) + .map((m) => ({ + name: `#${m.id} ${movieLabel(m)}`.slice(0, 100), + value: m.id, + })), + ); + }, + }, + ], + }; +} diff --git a/src/infra/discord/commands/polls.ts b/src/infra/discord/commands/polls.ts new file mode 100644 index 0000000..84d205b --- /dev/null +++ b/src/infra/discord/commands/polls.ts @@ -0,0 +1,251 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, + type SlashCommandIntegerOption, +} from 'discord.js'; +import { describeOutcome, type PollService } from '~/core/services'; +import { channelMention, userMention, UserError } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred } from '../define'; +import type { ComponentHandler, Feature } from '../module'; +import { render } from '../render'; +import { respond } from '../router'; + +const idOption = (o: SlashCommandIntegerOption) => + o + .setName('id') + .setDescription('Poll') + .setRequired(true) + .setAutocomplete(true); + +const data = new SlashCommandBuilder() + .setName('poll') + .setDescription('Polls') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Start a poll') + .addStringOption((o) => + o + .setName('question') + .setDescription('Question') + .setRequired(true) + .setMaxLength(256), + ) + .addStringOption((o) => + o + .setName('options') + .setDescription('Options separated by | e.g. "Pizza | Sushi | Tacos"') + .setRequired(true), + ) + .addBooleanOption((o) => + o.setName('multiple').setDescription('Allow several choices'), + ) + .addBooleanOption((o) => + o.setName('anonymous').setDescription('Hide who voted for what'), + ) + .addStringOption((o) => + o + .setName('results') + .setDescription('When results are visible') + .addChoices( + { name: 'live', value: 'live' }, + { name: 'after closing', value: 'closed' }, + ), + ) + .addStringOption((o) => + o.setName('closes').setDescription('e.g. 1d, 2h, 2026-11-20 18:00'), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Where to post (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Open polls')) + .addSubcommand((sub) => + sub + .setName('results') + .setDescription('Show results') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('close') + .setDescription('Close a poll now') + .addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('cancel') + .setDescription('Cancel a poll') + .addIntegerOption(idOption), + ); + +function parseId(value: string | undefined): number { + const id = Number(value); + + if (!Number.isSafeInteger(id)) { + throw new UserError('This poll control is invalid.'); + } + + return id; +} + +export function pollCommands(polls: PollService): Feature { + const answer = async ( + interaction: Parameters[0], + outcome: Awaited>, + ) => { + if (interaction.isModalSubmit()) { + return; + } + + const { content, embeds, components } = render(outcome.view); + + await interaction.update({ content, embeds, components }); + await respond( + interaction, + outcome.chosen.length === 0 + ? 'Your vote is cleared.' + : `Your vote: **${outcome.chosen.join(', ')}**`, + ); + }; + + const vote: ComponentHandler = { + prefix: 'polls:vote', + execute: async (interaction, [id]) => { + if (!interaction.isStringSelectMenu()) { + return; + } + + await answer( + interaction, + await polls.vote( + toActor(interaction.member), + parseId(id), + interaction.values.map((value) => Number(value)), + ), + ); + }, + }; + + const clear: ComponentHandler = { + prefix: 'polls:clear', + execute: async (interaction, [id]) => { + await answer( + interaction, + await polls.clear(toActor(interaction.member), parseId(id)), + ); + }, + }; + + return { + name: 'polls', + permissions: [ + { id: 'poll:create', description: 'Start polls' }, + { + id: 'poll:manage', + description: 'Close and cancel any poll, see voters', + }, + ], + components: [vote, clear], + commands: [ + { + data: data.toJSON(), + permissions: { create: 'poll:create' }, + execute: bySubcommand({ + create: deferred(async (interaction) => { + const closes = interaction.options.getString('closes'); + const poll = await polls.create(toActor(interaction.member), { + question: interaction.options.getString('question', true), + options: interaction.options + .getString('options', true) + .split('|'), + channelId: + interaction.options.getChannel('channel')?.id ?? + interaction.channelId, + multiple: interaction.options.getBoolean('multiple') ?? false, + anonymous: interaction.options.getBoolean('anonymous') ?? false, + showResults: + interaction.options.getString('results') === 'closed' + ? 'closed' + : 'live', + ...(closes !== null && { closes }), + }); + + await respond( + interaction, + `Poll #${poll.id} is up in ${channelMention(poll.channelId)}.`, + ); + }), + list: async (interaction) => { + const open = await polls.open(interaction.guildId); + + await respond( + interaction, + open.length === 0 + ? 'No open polls.' + : open + .map( + (p) => + `#${p.id} ${p.question} — ${channelMention(p.channelId)}`, + ) + .join('\n'), + ); + }, + results: async (interaction) => { + const { poll, results, voters } = await polls.summary( + toActor(interaction.member), + interaction.options.getInteger('id', true), + ); + const lines = results.options.map((option) => { + const names = + voters?.get(option.id)?.map((id) => userMention(id)) ?? []; + + return [`**${option.label}** — ${option.votes}`, ...names].join( + ' ', + ); + }); + const winner = + results.winners.length === 0 + ? 'No votes yet.' + : describeOutcome(results, 'Leading'); + + await respond( + interaction, + [`**${poll.question}**`, ...lines, winner] + .join('\n') + .slice(0, 2000), + ); + }, + close: deferred(async (interaction) => { + const id = interaction.options.getInteger('id', true); + + await polls.close(toActor(interaction.member), id); + await respond(interaction, `Poll #${id} is closed.`); + }), + cancel: deferred(async (interaction) => { + const id = interaction.options.getInteger('id', true); + + await polls.cancel(toActor(interaction.member), id); + await respond(interaction, `Poll #${id} is cancelled.`); + }), + }), + autocomplete: async (interaction) => { + const open = await polls.open(interaction.guildId); + + await interaction.respond( + open.map((p) => ({ + name: `#${p.id} ${p.question}`.slice(0, 100), + value: p.id, + })), + ); + }, + }, + ], + }; +} diff --git a/tests/core/services/movies.test.ts b/tests/core/services/movies.test.ts new file mode 100644 index 0000000..832b738 --- /dev/null +++ b/tests/core/services/movies.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Calendar, Scheduler } from '~/core/ports'; +import { + createEventService, + createMovieService, + createPollService, +} from '~/core/services'; +import { + createEventRepository, + createMovieRepository, + createPollRepository, +} from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + fakeDirectory, + fakeMessenger, + silentLog, +} from '../../fakes'; + +describe.skipIf(noDatabase)('movie service', () => { + const setup = () => { + const { messenger } = fakeMessenger(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const calendar = { + upsert: vi.fn(async () => 'n'), + remove: vi.fn(async () => undefined), + }; + const shared = { + scheduler, + messenger, + directory: fakeDirectory(), + authz: allowAll, + log: silentLog, + timezone: async () => 'Europe/Tallinn', + }; + const pollRepository = createPollRepository(testDb()); + const polls = createPollService({ ...shared, polls: pollRepository }); + const events = createEventService({ + ...shared, + events: createEventRepository(testDb()), + calendar, + }); + const movies = createMovieService({ + movies: createMovieRepository(testDb()), + polls, + events, + authz: allowAll, + timezone: shared.timezone, + }); + + return { + movies, + polls, + pollRepository, + member: actor({ guildId: snowflake(), userId: snowflake() }), + }; + }; + + const suggestion = (title: string) => ({ title, year: null, note: null }); + + it('rejects duplicate suggestions and points out watched ones', async () => { + const { movies, member } = setup(); + const movie = await movies.suggest(member, suggestion('Paprika')); + + await expect( + movies.suggest(member, suggestion('paprika!')), + ).rejects.toThrow('already suggested'); + await movies.watched(member, movie.id, '2026-01-02'); + await expect(movies.suggest(member, suggestion('Paprika'))).rejects.toThrow( + 'already watched (2026-01-', + ); + }); + + it('votes through the poll service and refuses ties', async () => { + const { movies, polls, pollRepository, member } = setup(); + + await movies.suggest(member, suggestion('Alien')); + await movies.suggest(member, suggestion('Brazil')); + + const poll = await movies.vote(member, { channelId: 'c' }); + const [alien, brazil] = poll.options.map((o) => o.id); + + await expect(movies.pick(member, undefined)).rejects.toThrow('close'); + await polls.vote( + actor({ guildId: member.guildId, userId: snowflake() }), + poll.id, + [alien ?? 0], + ); + await polls.vote( + actor({ guildId: member.guildId, userId: snowflake() }), + poll.id, + [brazil ?? 0], + ); + await pollRepository.finish(poll.id, 'closed'); + await expect(movies.pick(member, undefined)).rejects.toThrow('tie'); + }); + + it('schedules a movie night through the event service and records history', async () => { + const { movies, polls, pollRepository, member } = setup(); + + await movies.suggest(member, suggestion('Heat')); + await movies.suggest(member, suggestion('Ran')); + + const poll = await movies.vote(member, { channelId: 'c' }); + + await polls.vote( + actor({ guildId: member.guildId, userId: snowflake() }), + poll.id, + [poll.options[0]?.id ?? 0], + ); + await pollRepository.finish(poll.id, 'closed'); + + const { movie, event } = await movies.night(member, { + start: '2d', + channelId: 'c', + }); + + expect(movie.title).toBe('Heat'); + expect(event.title).toContain('Heat'); + await movies.watched(member, movie.id); + expect((await movies.history(member.guildId)).map((h) => h.title)).toEqual([ + 'Heat', + ]); + expect( + (await movies.unwatched(member.guildId)).map((m) => m.title), + ).toEqual(['Ran']); + }); +}); diff --git a/tests/core/services/polls.test.ts b/tests/core/services/polls.test.ts new file mode 100644 index 0000000..64bcca4 --- /dev/null +++ b/tests/core/services/polls.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { NewPoll, Scheduler } from '~/core/ports'; +import { createPollService, pollView } from '~/core/services'; +import { UserError } from '~/domain'; +import { createPollRepository } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + fakeDirectory, + fakeMessenger, + silentLog, +} from '../../fakes'; + +const base = (overrides: Partial = {}): NewPoll => ({ + guildId: snowflake(), + channelId: snowflake(), + creatorId: snowflake(), + question: 'Lunch?', + options: [{ label: 'Pizza' }, { label: 'Sushi' }, { label: 'Tacos' }], + ...overrides, +}); + +describe.skipIf(noDatabase)('poll repository', () => { + const polls = () => createPollRepository(testDb()); + + it('replaces a single-choice vote instead of adding another', async () => { + const poll = await polls().insert(base()); + const [pizza, sushi] = poll.options.map((o) => o.id); + const user = snowflake(); + + await polls().vote(poll.id, user, [pizza ?? 0]); + await polls().vote(poll.id, user, [sushi ?? 0]); + expect(await polls().choices(poll.id, user)).toEqual([sushi]); + await expect( + polls().vote(poll.id, user, [pizza ?? 0, sushi ?? 0]), + ).rejects.toThrow('only one'); + }); + + it('accepts several choices in multiple-choice polls and clearing', async () => { + const poll = await polls().insert(base({ multiple: true })); + const user = snowflake(); + + await polls().vote( + poll.id, + user, + poll.options.map((o) => o.id), + ); + expect((await polls().results(poll)).options.map((o) => o.votes)).toEqual([ + 1, 1, 1, + ]); + await polls().vote(poll.id, user, []); + expect((await polls().results(poll)).voters).toBe(0); + }); + + it('rejects options from another poll and votes after closing', async () => { + const poll = await polls().insert(base()); + const other = await polls().insert(base()); + + await expect( + polls().vote(poll.id, snowflake(), [other.options[0]?.id ?? 0]), + ).rejects.toThrow('not part'); + expect(await polls().finish(poll.id, 'closed')).toBeDefined(); + expect(await polls().finish(poll.id, 'closed')).toBeUndefined(); + await expect( + polls().vote(poll.id, snowflake(), [poll.options[0]?.id ?? 0]), + ).rejects.toBeInstanceOf(UserError); + }); + + it('keeps counts exact under concurrent voting', async () => { + const poll = await polls().insert(base()); + const [pizza, sushi] = poll.options.map((o) => o.id); + const user = snowflake(); + + await Promise.all([ + ...Array.from({ length: 20 }, () => + polls().vote(poll.id, snowflake(), [pizza ?? 0]), + ), + ...Array.from({ length: 10 }, (_, n) => + polls().vote(poll.id, user, [(n % 2 === 0 ? pizza : sushi) ?? 0]), + ), + ]); + expect((await polls().results(poll)).voters).toBe(21); + expect(await polls().choices(poll.id, user)).toHaveLength(1); + }); +}); + +describe.skipIf(noDatabase)('poll service', () => { + const setup = () => { + const { messenger } = fakeMessenger(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const repository = createPollRepository(testDb()); + const service = createPollService({ + polls: repository, + scheduler, + messenger, + directory: fakeDirectory(), + authz: allowAll, + log: silentLog, + timezone: async () => 'Europe/Tallinn', + }); + + return { + service, + messenger, + scheduler, + repository, + creator: actor({ guildId: snowflake(), userId: snowflake() }), + }; + }; + + it('publishes, schedules closing and hides live counts when asked', async () => { + const { service, scheduler, creator } = setup(); + const poll = await service.create(creator, { + question: 'Lunch?', + options: ['Pizza', 'Sushi'], + channelId: 'c', + showResults: 'closed', + closes: '1d', + }); + + expect(scheduler.schedule).toHaveBeenCalledOnce(); + + const { view } = await service.vote( + actor({ guildId: creator.guildId, userId: snowflake() }), + poll.id, + [poll.options[0]?.id ?? 0], + ); + + expect(JSON.stringify(view.embeds)).not.toContain('█'); + }); + + it('closes on schedule, shows the winner and removes controls', async () => { + const { service, repository, messenger, creator } = setup(); + const poll = await service.create(creator, { + question: 'Lunch?', + options: ['Pizza', 'Sushi'], + channelId: 'c', + }); + + await service.vote( + actor({ guildId: creator.guildId, userId: snowflake() }), + poll.id, + [poll.options[1]?.id ?? 0], + ); + await service.jobs[0]?.run( + { pollId: poll.id }, + { id: 1, runAt: new Date(), attempt: 1 }, + ); + + const closed = await repository.find(poll.id); + + expect(closed?.status).toBe('closed'); + + if (closed) { + const view = pollView(closed, await repository.results(closed)); + + expect(JSON.stringify(view.embeds)).toContain('Winner'); + expect(view.controls).toEqual([]); + } + + expect(messenger.edit).toHaveBeenCalled(); + }); + + it('hides voters of anonymous polls even from managers', async () => { + const { service, creator } = setup(); + const poll = await service.create(creator, { + question: 'Q', + options: ['A', 'B'], + channelId: 'c', + anonymous: true, + }); + + await service.vote( + actor({ guildId: creator.guildId, userId: snowflake() }), + poll.id, + [poll.options[0]?.id ?? 0], + ); + expect((await service.summary(creator, poll.id)).voters).toBeUndefined(); + }); +}); diff --git a/tests/domain/poll.test.ts b/tests/domain/poll.test.ts new file mode 100644 index 0000000..e50d0f0 --- /dev/null +++ b/tests/domain/poll.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; +import { + isPollOpen, + normalizeTitle, + tally, + validatePollOptions, +} from '~/domain'; + +describe('poll rules', () => { + it('reports winners and ties', () => { + const options = [{ id: 1 }, { id: 2 }, { id: 3 }]; + + expect( + tally( + options, + new Map([ + [1, 2], + [2, 2], + ]), + 4, + ), + ).toMatchObject({ tie: true, winners: [{ id: 1 }, { id: 2 }] }); + expect(tally(options, new Map([[3, 1]]), 1)).toMatchObject({ + tie: false, + winners: [{ id: 3 }], + }); + expect(tally(options, new Map(), 0).winners).toEqual([]); + }); + + it('validates options', () => { + expect(() => validatePollOptions(['only'])).toThrow('between 2'); + expect(() => validatePollOptions(['A', 'a'])).toThrow('distinct'); + expect(validatePollOptions([' A ', 'B'])).toEqual(['A', 'B']); + }); + + it('treats a passed deadline as closed', () => { + expect( + isPollOpen({ status: 'open', closesAt: new Date(Date.now() - 1000) }), + ).toBe(false); + expect(isPollOpen({ status: 'open', closesAt: null })).toBe(true); + }); + + it('normalises movie titles', () => { + expect(normalizeTitle('The Matrix!')).toBe( + normalizeTitle(' the MATRIX '), + ); + }); +}); diff --git a/tests/features/movies/movies.test.ts b/tests/features/movies/movies.test.ts deleted file mode 100644 index ffdc3d6..0000000 --- a/tests/features/movies/movies.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { castVote, finishPoll, insertPoll } from '~/features/polls/service'; -import { pickMovie } from '~/features/movies'; -import { - listUnwatched, - markWatched, - normalizeTitle, - recordScreening, - suggestMovie, - watchHistory, -} from '~/features/movies/service'; - -describe('normalizeTitle', () => { - it('ignores case, punctuation and spacing', () => { - expect(normalizeTitle('The Matrix!')).toBe( - normalizeTitle(' the MATRIX '), - ); - expect(normalizeTitle('Amélie')).toBe(normalizeTitle('amélie')); - }); -}); - -describe.skipIf(noDatabase)('movies', () => { - const ctx = () => ({ db: testDb() }) as unknown as AppContext; - const suggest = (guildId: string, title: string) => - suggestMovie(testDb(), { - guildId, - title, - year: null, - note: null, - suggestedBy: snowflake(), - }); - - it('rejects duplicate suggestions and points out watched ones', async () => { - const guildId = snowflake(); - const movie = await suggest(guildId, 'Paprika'); - - await expect(suggest(guildId, 'paprika!')).rejects.toThrow( - 'already suggested', - ); - await markWatched( - testDb(), - guildId, - movie.id, - new Date('2026-01-02T20:00:00Z'), - ); - await expect(suggest(guildId, 'Paprika')).rejects.toThrow( - 'already watched (2026-01-02)', - ); - expect(await suggest(snowflake(), 'Paprika')).toBeDefined(); - }); - - it('picks the winner of the latest movie poll and refuses ties', async () => { - const guildId = snowflake(); - const [a, b] = [ - await suggest(guildId, 'Alien'), - await suggest(guildId, 'Brazil'), - ]; - const poll = await insertPoll(testDb(), { - guildId, - channelId: snowflake(), - creatorId: snowflake(), - question: 'Next?', - source: 'movies', - options: [a, b].map((m) => ({ label: m.title, ref: String(m.id) })), - }); - - await expect(pickMovie(ctx(), guildId, null)).rejects.toThrow('close'); - - const [optionA, optionB] = poll.options.map((o) => o.id); - - await castVote(testDb(), poll.id, snowflake(), [optionA ?? 0]); - await castVote(testDb(), poll.id, snowflake(), [optionB ?? 0]); - await finishPoll(testDb(), poll.id, 'closed'); - await expect(pickMovie(ctx(), guildId, null)).rejects.toThrow('tie'); - expect((await pickMovie(ctx(), guildId, b.id)).movie.title).toBe('Brazil'); - - const second = await insertPoll(testDb(), { - guildId, - channelId: snowflake(), - creatorId: snowflake(), - question: 'Again?', - source: 'movies', - options: [a, b].map((m) => ({ label: m.title, ref: String(m.id) })), - }); - - await castVote(testDb(), second.id, snowflake(), [ - second.options[0]?.id ?? 0, - ]); - await finishPoll(testDb(), second.id, 'closed'); - expect(await pickMovie(ctx(), guildId, null)).toMatchObject({ - movie: { title: 'Alien' }, - pollId: second.id, - }); - }); - - it('tracks screenings and history', async () => { - const guildId = snowflake(); - const movie = await suggest(guildId, 'Heat'); - - await recordScreening(testDb(), { - guildId, - suggestionId: movie.id, - eventId: 1, - scheduledFor: new Date(), - }); - expect((await listUnwatched(testDb(), guildId)).map((m) => m.id)).toEqual([ - movie.id, - ]); - await markWatched(testDb(), guildId, movie.id, new Date()); - expect(await listUnwatched(testDb(), guildId)).toEqual([]); - expect((await watchHistory(testDb(), guildId)).map((h) => h.title)).toEqual( - ['Heat'], - ); - }); -}); diff --git a/tests/features/polls/polls.test.ts b/tests/features/polls/polls.test.ts deleted file mode 100644 index 5973399..0000000 --- a/tests/features/polls/polls.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { pino } from 'pino'; -import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { UserError } from '~/domain'; -import { closeJob, renderPoll } from '~/features/polls'; -import { - castVote, - finishPoll, - getPoll, - getResults, - getVoterChoices, - insertPoll, - type NewPoll, -} from '~/features/polls/service'; - -const base = (overrides: Partial = {}): NewPoll => ({ - guildId: snowflake(), - channelId: snowflake(), - creatorId: snowflake(), - question: 'Lunch?', - options: [{ label: 'Pizza' }, { label: 'Sushi' }, { label: 'Tacos' }], - ...overrides, -}); - -describe.skipIf(noDatabase)('polls', () => { - const db = () => testDb(); - - it('validates options', async () => { - await expect( - insertPoll(db(), base({ options: [{ label: 'Only' }] })), - ).rejects.toThrow('between 2'); - await expect( - insertPoll(db(), base({ options: [{ label: 'A' }, { label: 'a' }] })), - ).rejects.toThrow('distinct'); - }); - - it('replaces a single-choice vote instead of adding another', async () => { - const poll = await insertPoll(db(), base()); - const [pizza, sushi] = poll.options; - const user = snowflake(); - - await castVote(db(), poll.id, user, [pizza?.id ?? 0]); - await castVote(db(), poll.id, user, [sushi?.id ?? 0]); - expect(await getVoterChoices(db(), poll.id, user)).toEqual([sushi?.id]); - await expect( - castVote(db(), poll.id, user, [pizza?.id ?? 0, sushi?.id ?? 0]), - ).rejects.toThrow('only one'); - }); - - it('accepts several choices in multiple-choice polls and clearing', async () => { - const poll = await insertPoll(db(), base({ multiple: true })); - const ids = poll.options.map((o) => o.id); - const user = snowflake(); - - await castVote(db(), poll.id, user, ids); - expect((await getResults(db(), poll)).voters).toBe(1); - expect((await getResults(db(), poll)).options.map((o) => o.votes)).toEqual([ - 1, 1, 1, - ]); - await castVote(db(), poll.id, user, []); - expect((await getResults(db(), poll)).voters).toBe(0); - }); - - it('rejects options from another poll', async () => { - const poll = await insertPoll(db(), base()); - const other = await insertPoll(db(), base()); - - await expect( - castVote(db(), poll.id, snowflake(), [other.options[0]?.id ?? 0]), - ).rejects.toThrow('not part'); - }); - - it('reports ties and winners', async () => { - const poll = await insertPoll(db(), base()); - const [pizza, sushi] = poll.options.map((o) => o.id); - - await castVote(db(), poll.id, snowflake(), [pizza ?? 0]); - await castVote(db(), poll.id, snowflake(), [sushi ?? 0]); - const tied = await getResults(db(), poll); - - expect(tied.tie).toBe(true); - expect(tied.winners.map((w) => w.label)).toEqual(['Pizza', 'Sushi']); - await castVote(db(), poll.id, snowflake(), [sushi ?? 0]); - const won = await getResults(db(), poll); - - expect(won.tie).toBe(false); - expect(won.winners.map((w) => w.label)).toEqual(['Sushi']); - }); - - it('refuses votes after closing or the deadline', async () => { - const poll = await insertPoll(db(), base()); - - expect(await finishPoll(db(), poll.id, 'closed')).toBeDefined(); - expect(await finishPoll(db(), poll.id, 'closed')).toBeUndefined(); - await expect( - castVote(db(), poll.id, snowflake(), [poll.options[0]?.id ?? 0]), - ).rejects.toBeInstanceOf(UserError); - - const expired = await insertPoll( - db(), - base({ closesAt: new Date(Date.now() - 1000) }), - ); - - await expect( - castVote(db(), expired.id, snowflake(), [expired.options[0]?.id ?? 0]), - ).rejects.toThrow('closed'); - }); - - it('keeps counts exact under concurrent voting', async () => { - const poll = await insertPoll(db(), base()); - const [pizza, sushi] = poll.options.map((o) => o.id); - const user = snowflake(); - const voters = Array.from({ length: 20 }, () => snowflake()); - - await Promise.all([ - ...voters.map((voter) => castVote(db(), poll.id, voter, [pizza ?? 0])), - ...Array.from({ length: 10 }, (_, n) => - castVote(db(), poll.id, user, [(n % 2 === 0 ? pizza : sushi) ?? 0]), - ), - ]); - const results = await getResults(db(), poll); - - expect(results.voters).toBe(21); - expect(await getVoterChoices(db(), poll.id, user)).toHaveLength(1); - }); - - it('closes on schedule and hides live counts when requested', async () => { - const poll = await insertPoll(db(), base({ showResults: 'closed' })); - - await castVote(db(), poll.id, snowflake(), [poll.options[0]?.id ?? 0]); - const hidden = JSON.stringify( - renderPoll(poll, await getResults(db(), poll)).embeds, - ); - - expect(hidden).not.toContain('█'); - - const ctx = { - db: db(), - log: pino({ level: 'silent' }), - client: { channels: { fetch: vi.fn() } }, - } as unknown as AppContext; - - await closeJob.run( - { pollId: poll.id }, - { id: 1, runAt: new Date(), attempt: 1 }, - ctx, - ); - const closed = await getPoll(db(), poll.id); - - expect(closed?.status).toBe('closed'); - if (closed) { - const rendered = renderPoll(closed, await getResults(db(), closed)); - - expect(JSON.stringify(rendered.embeds)).toContain('Winner'); - expect(rendered.components).toEqual([]); - } - }); -}); From 23fca5f0535981c3b05032babff16bfc67fd0d06 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 21:20:36 +0200 Subject: [PATCH 028/199] refactor(birthdays): birthday service with pure date rules in the domain --- src/app.ts | 16 +- src/core/ports/birthdays.ts | 33 ++ src/core/ports/index.ts | 1 + src/core/services/birthdays.ts | 257 ++++++++++++ src/core/services/index.ts | 1 + src/domain/birthday.ts | 31 ++ src/domain/index.ts | 1 + src/features/birthdays/index.ts | 387 ------------------ .../schema.ts => infra/db/birthdays/model.ts} | 0 .../service.ts => infra/db/birthdays/repo.ts} | 50 +-- src/infra/db/index.ts | 2 + src/infra/discord/commands/birthdays.ts | 170 ++++++++ src/infra/discord/commands/index.ts | 1 + tests/core/services/birthdays.test.ts | 196 +++++++++ tests/domain/birthday.test.ts | 31 ++ tests/features/birthdays/birthdays.test.ts | 214 ---------- 16 files changed, 759 insertions(+), 632 deletions(-) create mode 100644 src/core/ports/birthdays.ts create mode 100644 src/core/services/birthdays.ts create mode 100644 src/domain/birthday.ts delete mode 100644 src/features/birthdays/index.ts rename src/{features/birthdays/schema.ts => infra/db/birthdays/model.ts} (100%) rename src/{features/birthdays/service.ts => infra/db/birthdays/repo.ts} (79%) create mode 100644 src/infra/discord/commands/birthdays.ts create mode 100644 tests/core/services/birthdays.test.ts create mode 100644 tests/domain/birthday.test.ts delete mode 100644 tests/features/birthdays/birthdays.test.ts diff --git a/src/app.ts b/src/app.ts index 81b6093..a849f23 100644 --- a/src/app.ts +++ b/src/app.ts @@ -2,6 +2,7 @@ import { Events, type Client } from 'discord.js'; import type { Config } from '~/config'; import { announcementCommands, + birthdayCommands, createClient, createDiscordCalendar, eventCommands, @@ -19,6 +20,7 @@ import { import { createAnnouncementService, createAuthorizer, + createBirthdayService, createEventService, createMovieService, createPollService, @@ -36,6 +38,7 @@ import { connectDatabase, createAnnouncementRepository, createEventRepository, + createBirthdayRepository, createGrantRepository, createMovieRepository, createPollRepository, @@ -44,7 +47,6 @@ import { createSettingsRepository, runMigrations, } from '~/infra/db'; -import { birthdaysFeature } from '~/features/birthdays'; import { createRedmineFeature } from '~/features/redmine'; function legacyPanel(config: Config): LegacyPanel | undefined { @@ -130,7 +132,17 @@ export function compose(config: Config, log: Logger) { authz, timezone: (guildId) => settings.timezone(guildId), }); + const birthdays = createBirthdayService({ + birthdays: createBirthdayRepository(database.db), + scheduler, + messenger, + directory, + authz, + log: log.child({ service: 'birthdays' }), + timezone: (guildId) => settings.timezone(guildId), + }); const jobs: Array> = [ + ...birthdays.jobs, ...polls.jobs, ...reminders.jobs, ...announcements.jobs, @@ -150,7 +162,7 @@ export function compose(config: Config, log: Logger) { reminderCommands(reminders), announcementCommands(announcements), eventCommands(events), - birthdaysFeature, + birthdayCommands(birthdays), pollCommands(polls), movieCommands(movies), ]; diff --git a/src/core/ports/birthdays.ts b/src/core/ports/birthdays.ts new file mode 100644 index 0000000..e10a14c --- /dev/null +++ b/src/core/ports/birthdays.ts @@ -0,0 +1,33 @@ +import type { BirthdayVisibility, CalendarDay } from '~/domain'; + +export type Birthday = { + guildId: string; + userId: string; + month: number; + day: number; + visibility: BirthdayVisibility; + lastAnnouncedYear: number | null; +}; + +export type BirthdaySettings = { + guildId: string; + channelId: string; + roleId: string | null; + hour: number; +}; + +export type BirthdayRepository = { + set: (birthday: Omit) => Promise; + remove: (guildId: string, userId: string) => Promise; + find: (guildId: string, userId: string) => Promise; + upcoming: ( + guildId: string, + today: CalendarDay, + limit?: number, + ) => Promise; + claim: (guildId: string, today: CalendarDay) => Promise; + release: (guildId: string, userIds: string[], year: number) => Promise; + settings: (guildId: string) => Promise; + saveSettings: (settings: BirthdaySettings) => Promise; + deleteSettings: (guildId: string) => Promise; +}; diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 7437d86..5cc1ffe 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -11,3 +11,4 @@ export type * from './announcements'; export * from './events'; export type * from './polls'; export type * from './movies'; +export type * from './birthdays'; diff --git a/src/core/services/birthdays.ts b/src/core/services/birthdays.ts new file mode 100644 index 0000000..5598a05 --- /dev/null +++ b/src/core/services/birthdays.ts @@ -0,0 +1,257 @@ +import { format } from 'date-fns'; +import { z } from 'zod'; +import { + birthdayVisibilities, + calendarDay, + channelMention, + nextDailyRun, + PermanentError, + UserError, + userMention, + type Actor, + type BirthdayVisibility, +} from '~/domain'; +import type { + Authorizer, + Birthday, + BirthdayRepository, + BirthdaySettings, + Directory, + Logger, + Messenger, + Scheduler, +} from '~/core/ports'; +import { sequential } from '~/lib'; +import { guard } from './guard'; +import { defineJob } from './jobs'; + +const dailyKey = (guildId: string) => `birthdays:${guildId}`; + +export type BirthdayConfiguration = { + channelId?: string; + roleId?: string; + hour?: number; + disable?: boolean; +}; + +export function describeBirthday(birthday: Birthday): string { + const date = format( + new Date(2024, birthday.month - 1, birthday.day), + 'd MMMM', + ); + + return `${userMention(birthday.userId)} — ${date}`; +} + +type Deps = { + birthdays: BirthdayRepository; + scheduler: Scheduler; + messenger: Messenger; + directory: Directory; + authz: Authorizer; + log: Logger; + timezone: (guildId: string) => Promise; +}; + +export function createBirthdayService(deps: Deps) { + const { birthdays, scheduler, messenger, directory, authz, log, timezone } = + deps; + + const removeRoleJob = defineJob({ + type: 'birthdays:remove-role', + payload: z.object({ + guildId: z.string(), + userId: z.string(), + roleId: z.string(), + }), + handle: async ({ guildId, userId, roleId }) => { + try { + await directory.removeRoles( + { guildId, userId }, + [roleId], + 'Birthday is over', + ); + } catch (error) { + if (!(error instanceof PermanentError)) { + throw error; + } + } + }, + }); + + const giveRole = async ( + settings: BirthdaySettings, + roleId: string, + userIds: string[], + ) => { + const zone = await timezone(settings.guildId); + const midnight = nextDailyRun(zone, 0); + + await sequential(userIds, async (userId) => { + try { + await directory.addRoles( + { guildId: settings.guildId, userId }, + [roleId], + 'Birthday', + ); + await scheduler.schedule( + removeRoleJob, + { guildId: settings.guildId, userId, roleId }, + { + runAt: midnight, + key: `birthday-role:${settings.guildId}:${userId}`, + }, + ); + } catch (error) { + log.warn({ err: error, userId }, 'Could not give birthday role'); + } + }); + }; + + const announce = async ( + settings: BirthdaySettings, + userIds: string[], + year: number, + ) => { + try { + await messenger.send(settings.channelId, { + content: `🎉 Palju õnne! Happy birthday ${userIds.map((id) => userMention(id)).join(', ')}!`, + mentions: { users: userIds }, + }); + } catch (error) { + if (!(error instanceof PermanentError)) { + await birthdays.release(settings.guildId, userIds, year); + + throw error; + } + + log.error( + { err: error, guildId: settings.guildId }, + 'Birthday channel is unusable; skipping today', + ); + } + }; + + const dailyJob = defineJob({ + type: 'birthdays:daily', + payload: z.object({ guildId: z.string() }), + handle: async ({ guildId }) => { + const settings = await birthdays.settings(guildId); + + if (!settings) { + return null; + } + + const zone = await timezone(guildId); + const today = calendarDay(new Date(), zone); + const userIds = await birthdays.claim(guildId, today); + + if (userIds.length > 0) { + await announce(settings, userIds, today.year); + + if (settings.roleId !== null) { + await giveRole(settings, settings.roleId, userIds); + } + } + + return { rescheduleAt: nextDailyRun(zone, settings.hour) }; + }, + }); + + const resolveSettings = async ( + actor: Actor, + change: BirthdayConfiguration, + ) => { + const current = await birthdays.settings(actor.guildId); + const channelId = change.channelId ?? current?.channelId; + + if (channelId === undefined) { + throw new UserError('Choose an announcement channel.'); + } + + if (change.roleId !== undefined) { + const role = await directory.role(actor.guildId, change.roleId); + + if (!role || role.managed || !role.botCanAssign) { + throw new UserError('I cannot manage that role.'); + } + } + + return { + guildId: actor.guildId, + channelId, + roleId: change.roleId ?? current?.roleId ?? null, + hour: change.hour ?? current?.hour ?? 9, + }; + }; + + return { + jobs: [dailyJob, removeRoleJob], + set: async ( + actor: Actor, + birthday: { day: number; month: number; visibility?: string }, + ) => { + const visibility: BirthdayVisibility = + birthdayVisibilities.find((v) => v === birthday.visibility) ?? 'public'; + + await birthdays.set({ + guildId: actor.guildId, + userId: actor.userId, + day: birthday.day, + month: birthday.month, + visibility, + }); + + return visibility; + }, + remove: (actor: Actor) => birthdays.remove(actor.guildId, actor.userId), + view: async (actor: Actor, userId: string) => { + const birthday = await birthdays.find(actor.guildId, userId); + + return birthday && + (userId === actor.userId || birthday.visibility === 'public') + ? birthday + : undefined; + }, + upcoming: async (guildId: string) => + birthdays.upcoming( + guildId, + calendarDay(new Date(), await timezone(guildId)), + ), + configure: guard( + authz, + 'birthday:manage', + async (actor, change: BirthdayConfiguration) => { + if (change.disable === true) { + await birthdays.deleteSettings(actor.guildId); + await scheduler.cancel(dailyKey(actor.guildId)); + + return 'Birthday announcements are off.'; + } + + const settings = await resolveSettings(actor, change); + const zone = await timezone(actor.guildId); + + await birthdays.saveSettings(settings); + await scheduler.schedule( + dailyJob, + { guildId: actor.guildId }, + { + runAt: nextDailyRun(zone, settings.hour), + key: dailyKey(actor.guildId), + }, + ); + log.info( + { guildId: actor.guildId, actorId: actor.userId, settings }, + 'Birthday settings changed', + ); + + const role = settings.roleId === null ? '' : ' with a role for the day'; + + return `Birthdays are announced in ${channelMention(settings.channelId)} at ${settings.hour}:00 (${zone})${role}.`; + }, + ), + }; +} + +export type BirthdayService = ReturnType; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index 18da569..872710f 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -8,3 +8,4 @@ export * from './announcements'; export * from './events'; export * from './polls'; export * from './movies'; +export * from './birthdays'; diff --git a/src/domain/birthday.ts b/src/domain/birthday.ts new file mode 100644 index 0000000..05c5029 --- /dev/null +++ b/src/domain/birthday.ts @@ -0,0 +1,31 @@ +import { isLeapYear } from 'date-fns'; +import { UserError } from './errors'; +import type { CalendarDay } from './time'; + +export const birthdayVisibilities = ['public', 'announce', 'private'] as const; + +export type BirthdayVisibility = (typeof birthdayVisibilities)[number]; + +export function validateBirthday(month: number, day: number): void { + const date = new Date(2024, month - 1, day); + + if (date.getMonth() !== month - 1 || date.getDate() !== day) { + throw new UserError('That is not a valid date.'); + } +} + +export function celebratedOn( + date: CalendarDay, +): Array<{ month: number; day: number }> { + const dates = [{ month: date.month, day: date.day }]; + + if ( + date.month === 2 && + date.day === 28 && + !isLeapYear(new Date(date.year, 0, 1)) + ) { + dates.push({ month: 2, day: 29 }); + } + + return dates; +} diff --git a/src/domain/index.ts b/src/domain/index.ts index 328212b..6960764 100644 --- a/src/domain/index.ts +++ b/src/domain/index.ts @@ -6,3 +6,4 @@ export * from './role'; export * from './time'; export * from './poll'; export * from './movie'; +export * from './birthday'; diff --git a/src/features/birthdays/index.ts b/src/features/birthdays/index.ts deleted file mode 100644 index df68193..0000000 --- a/src/features/birthdays/index.ts +++ /dev/null @@ -1,387 +0,0 @@ -import { - ChannelType, - InteractionContextType, - SlashCommandBuilder, - channelMention, - roleMention, - userMention, -} from 'discord.js'; -import { format } from 'date-fns'; -import { z } from 'zod'; -import { - respond, - bySubcommand, - defineJob, - isPermanentDiscordError, -} from '~/infra/discord'; -import type { AppContext, CommandInteraction, Feature } from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { sequential } from '~/lib'; -import { UserError, calendarDay, nextDailyRun } from '~/domain'; -import { - birthdayVisibility, - type Birthday, - type BirthdayVisibility, -} from './schema'; -import { - claimTodaysBirthdays, - deleteSettings, - getBirthday, - getSettings, - releaseClaims, - removeBirthday, - saveSettings, - setBirthday, - upcomingBirthdays, -} from './service'; - -const dailyKey = (guildId: string) => `birthdays:${guildId}`; -const visibilities = birthdayVisibility.enumValues; - -const removeRoleJob = defineJob({ - type: 'birthdays:remove-role', - payload: z.object({ - guildId: z.string(), - userId: z.string(), - roleId: z.string(), - }), - handle: async ({ guildId, userId, roleId }, _info, ctx) => { - try { - const guild = await ctx.client.guilds.fetch(guildId); - const member = await guild.members.fetch(userId); - - await member.roles.remove(roleId, 'Birthday is over'); - } catch (error) { - if (!isPermanentDiscordError(error)) { - throw error; - } - } - }, -}); - -async function giveRole( - ctx: AppContext, - target: { guildId: string; roleId: string; zone: string }, - userIds: string[], -) { - const { guildId, roleId, zone } = target; - const guild = await ctx.client.guilds.fetch(guildId); - const midnight = nextDailyRun(zone, 0); - - await sequential(userIds, async (userId) => { - try { - const member = await guild.members.fetch(userId); - - await member.roles.add(roleId, 'Birthday'); - await ctx.scheduler.schedule( - removeRoleJob, - { guildId, userId, roleId }, - { - runAt: midnight, - key: `birthday-role:${guildId}:${userId}`, - }, - ); - } catch (error) { - ctx.log.warn({ err: error, userId }, 'Could not give birthday role'); - } - }); -} - -export const dailyJob = defineJob({ - type: 'birthdays:daily', - payload: z.object({ guildId: z.string() }), - handle: async ({ guildId }, _info, ctx) => { - const settings = await getSettings(ctx.db, guildId); - - if (!settings) { - return null; - } - - const zone = await getGuildTimezone( - ctx.db, - guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - const today = calendarDay(new Date(), zone); - const userIds = await claimTodaysBirthdays(ctx.db, guildId, today); - - if (userIds.length > 0) { - try { - const channel = await ctx.client.channels.fetch(settings.channelId); - - if (channel?.isSendable() !== true) { - throw new UserError('Birthday channel is not available'); - } - - await channel.send({ - content: `🎉 Palju õnne! Happy birthday ${userIds.map((id) => userMention(id)).join(', ')}!`, - allowedMentions: { users: userIds }, - }); - } catch (error) { - if (!isPermanentDiscordError(error) && !(error instanceof UserError)) { - await releaseClaims(ctx.db, guildId, userIds, today.year); - throw error; - } - - ctx.log.error( - { err: error, guildId }, - 'Birthday channel is unusable; skipping today', - ); - } - - if (settings.roleId !== null) { - await giveRole( - ctx, - { guildId, roleId: settings.roleId, zone }, - userIds, - ); - } - } - - return { rescheduleAt: nextDailyRun(zone, settings.hour) }; - }, -}); - -function describe(birthday: Birthday): string { - const date = format( - new Date(2024, birthday.month - 1, birthday.day), - 'd MMMM', - ); - - return `<@${birthday.userId}> — ${date}`; -} - -const data = new SlashCommandBuilder() - .setName('birthday') - .setDescription('Birthdays') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('set') - .setDescription('Save your birthday (no year needed)') - .addIntegerOption((o) => - o - .setName('day') - .setDescription('Day') - .setRequired(true) - .setMinValue(1) - .setMaxValue(31), - ) - .addIntegerOption((o) => - o - .setName('month') - .setDescription('Month') - .setRequired(true) - .setMinValue(1) - .setMaxValue(12), - ) - .addStringOption((o) => - o - .setName('visibility') - .setDescription( - 'public: announced and listed; announce: announced only; private: neither', - ) - .addChoices(visibilities.map((v) => ({ name: v, value: v }))), - ), - ) - .addSubcommand((sub) => - sub.setName('remove').setDescription('Delete your birthday data'), - ) - .addSubcommand((sub) => - sub - .setName('view') - .setDescription('See a birthday') - .addUserOption((o) => - o.setName('member').setDescription('Member (default: you)'), - ), - ) - .addSubcommand((sub) => - sub.setName('upcoming').setDescription('Upcoming public birthdays'), - ) - .addSubcommand((sub) => - sub - .setName('settings') - .setDescription('Configure birthday announcements') - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Announcement channel') - .addChannelTypes(ChannelType.GuildText), - ) - .addRoleOption((o) => - o.setName('role').setDescription('Role to give for the day'), - ) - .addIntegerOption((o) => - o - .setName('hour') - .setDescription('Hour to announce (server time)') - .setMinValue(0) - .setMaxValue(23), - ) - .addBooleanOption((o) => - o.setName('disable').setDescription('Turn announcements off'), - ), - ); - -async function readSettings( - interaction: CommandInteraction, - ctx: AppContext, -): Promise<{ - guildId: string; - channelId: string; - roleId: string | null; - hour: number; -}> { - const current = await getSettings(ctx.db, interaction.guildId); - const channelId = - interaction.options.getChannel('channel')?.id ?? current?.channelId; - - if (channelId === undefined) { - throw new UserError('Choose an announcement channel.'); - } - - const role = interaction.options.getRole('role'); - - if (role && (role.managed || !role.editable)) { - throw new UserError(`I cannot manage ${role.name}.`); - } - - return { - guildId: interaction.guildId, - channelId, - roleId: role?.id ?? current?.roleId ?? null, - hour: interaction.options.getInteger('hour') ?? current?.hour ?? 9, - }; -} - -async function configure( - interaction: CommandInteraction, - ctx: AppContext, -): Promise { - const guildId = interaction.guildId; - - if (interaction.options.getBoolean('disable') === true) { - await deleteSettings(ctx.db, guildId); - await ctx.scheduler.cancel(dailyKey(guildId)); - await respond(interaction, 'Birthday announcements are off.'); - - return; - } - - const settings = await readSettings(interaction, ctx); - - await saveSettings(ctx.db, settings); - const zone = await getGuildTimezone( - ctx.db, - guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - - await ctx.scheduler.schedule( - dailyJob, - { guildId }, - { runAt: nextDailyRun(zone, settings.hour), key: dailyKey(guildId) }, - ); - ctx.log.info( - { guildId, actorId: interaction.user.id, settings }, - 'Birthday settings changed', - ); - const role = - settings.roleId === null - ? '' - : ` with ${roleMention(settings.roleId)} for the day`; - - await respond( - interaction, - `Birthdays are announced in ${channelMention(settings.channelId)} at ${settings.hour}:00 (${zone})${role}.`, - ); -} - -export const birthdaysFeature: Feature = { - name: 'birthdays', - permissions: [ - { id: 'birthday:manage', description: 'Configure birthday announcements' }, - ], - jobs: [dailyJob, removeRoleJob], - commands: [ - { - data: data.toJSON(), - permissions: { settings: 'birthday:manage' }, - execute: bySubcommand({ - set: async (interaction, ctx) => { - const visibility: BirthdayVisibility = - visibilities.find( - (v) => v === interaction.options.getString('visibility'), - ) ?? 'public'; - - await setBirthday(ctx.db, { - guildId: interaction.guildId, - userId: interaction.user.id, - day: interaction.options.getInteger('day', true), - month: interaction.options.getInteger('month', true), - visibility, - }); - const leap = - interaction.options.getInteger('month', true) === 2 && - interaction.options.getInteger('day', true) === 29 - ? ' In non-leap years it is celebrated on 28 February.' - : ''; - - await respond(interaction, `Saved (${visibility}).${leap}`); - }, - remove: async (interaction, ctx) => { - const removed = await removeBirthday( - ctx.db, - interaction.guildId, - interaction.user.id, - ); - - await respond( - interaction, - removed - ? 'Your birthday data is deleted.' - : 'You had no birthday saved.', - ); - }, - view: async (interaction, ctx) => { - const user = - interaction.options.getUser('member') ?? interaction.user; - const birthday = await getBirthday( - ctx.db, - interaction.guildId, - user.id, - ); - const visible = - birthday && - (user.id === interaction.user.id || - birthday.visibility === 'public'); - - await respond( - interaction, - visible === true ? describe(birthday) : 'No birthday to show.', - ); - }, - upcoming: async (interaction, ctx) => { - const zone = await getGuildTimezone( - ctx.db, - interaction.guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - const list = await upcomingBirthdays( - ctx.db, - interaction.guildId, - calendarDay(new Date(), zone), - ); - - await respond( - interaction, - list.length === 0 - ? 'No public birthdays yet.' - : list.map((birthday) => describe(birthday)).join('\n'), - ); - }, - settings: configure, - }), - }, - ], -}; diff --git a/src/features/birthdays/schema.ts b/src/infra/db/birthdays/model.ts similarity index 100% rename from src/features/birthdays/schema.ts rename to src/infra/db/birthdays/model.ts diff --git a/src/features/birthdays/service.ts b/src/infra/db/birthdays/repo.ts similarity index 79% rename from src/features/birthdays/service.ts rename to src/infra/db/birthdays/repo.ts index 58cfa95..360b57e 100644 --- a/src/features/birthdays/service.ts +++ b/src/infra/db/birthdays/repo.ts @@ -1,38 +1,14 @@ import { and, eq, inArray, isNull, lt, ne, or, sql } from 'drizzle-orm'; -import { isLeapYear } from 'date-fns'; import type { CalendarDay } from '~/domain'; -import type { Db } from '~/infra/db'; -import { UserError } from '~/domain'; +import type { BirthdayRepository } from '~/core/ports'; +import type { Db } from '../client'; +import { celebratedOn, validateBirthday } from '~/domain'; import { birthdays, birthdaySettings, type Birthday, type BirthdayVisibility, -} from './schema'; - -export function validateDate(month: number, day: number): void { - const date = new Date(2024, month - 1, day); - - if (date.getMonth() !== month - 1 || date.getDate() !== day) { - throw new UserError('That is not a valid date.'); - } -} - -export function celebratedOn( - date: CalendarDay, -): Array<{ month: number; day: number }> { - const dates = [{ month: date.month, day: date.day }]; - - if ( - date.month === 2 && - date.day === 28 && - !isLeapYear(new Date(date.year, 0, 1)) - ) { - dates.push({ month: 2, day: 29 }); - } - - return dates; -} +} from './model'; export async function setBirthday( db: Db, @@ -44,7 +20,7 @@ export async function setBirthday( visibility: BirthdayVisibility; }, ): Promise { - validateDate(input.month, input.day); + validateBirthday(input.month, input.day); await db .insert(birthdays) .values(input) @@ -181,3 +157,19 @@ export async function deleteSettings(db: Db, guildId: string): Promise { .delete(birthdaySettings) .where(eq(birthdaySettings.guildId, guildId)); } + +export function createBirthdayRepository(db: Db): BirthdayRepository { + return { + set: (birthday) => setBirthday(db, birthday), + remove: (guildId, userId) => removeBirthday(db, guildId, userId), + find: (guildId, userId) => getBirthday(db, guildId, userId), + upcoming: (guildId, today, limit) => + upcomingBirthdays(db, guildId, today, limit), + claim: (guildId, today) => claimTodaysBirthdays(db, guildId, today), + release: (guildId, userIds, year) => + releaseClaims(db, guildId, userIds, year), + settings: (guildId) => getSettings(db, guildId), + saveSettings: (settings) => saveSettings(db, settings), + deleteSettings: (guildId) => deleteSettings(db, guildId), + }; +} diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index a18cda7..6f82571 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -16,3 +16,5 @@ export * from './polls/model'; export * from './polls/repo'; export * from './movies/model'; export * from './movies/repo'; +export * from './birthdays/model'; +export * from './birthdays/repo'; diff --git a/src/infra/discord/commands/birthdays.ts b/src/infra/discord/commands/birthdays.ts new file mode 100644 index 0000000..e1a5176 --- /dev/null +++ b/src/infra/discord/commands/birthdays.ts @@ -0,0 +1,170 @@ +import { + ChannelType, + InteractionContextType, + SlashCommandBuilder, +} from 'discord.js'; +import { describeBirthday, type BirthdayService } from '~/core/services'; +import { birthdayVisibilities } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand } from '../define'; +import type { Feature } from '../module'; +import { respond } from '../router'; + +const data = new SlashCommandBuilder() + .setName('birthday') + .setDescription('Birthdays') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub + .setName('set') + .setDescription('Save your birthday (no year needed)') + .addIntegerOption((o) => + o + .setName('day') + .setDescription('Day') + .setRequired(true) + .setMinValue(1) + .setMaxValue(31), + ) + .addIntegerOption((o) => + o + .setName('month') + .setDescription('Month') + .setRequired(true) + .setMinValue(1) + .setMaxValue(12), + ) + .addStringOption((o) => + o + .setName('visibility') + .setDescription( + 'public: announced and listed; announce: announced only; private: neither', + ) + .addChoices(birthdayVisibilities.map((v) => ({ name: v, value: v }))), + ), + ) + .addSubcommand((sub) => + sub.setName('remove').setDescription('Delete your birthday data'), + ) + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('See a birthday') + .addUserOption((o) => + o.setName('member').setDescription('Member (default: you)'), + ), + ) + .addSubcommand((sub) => + sub.setName('upcoming').setDescription('Upcoming public birthdays'), + ) + .addSubcommand((sub) => + sub + .setName('settings') + .setDescription('Configure birthday announcements') + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Announcement channel') + .addChannelTypes(ChannelType.GuildText), + ) + .addRoleOption((o) => + o.setName('role').setDescription('Role to give for the day'), + ) + .addIntegerOption((o) => + o + .setName('hour') + .setDescription('Hour to announce (server time)') + .setMinValue(0) + .setMaxValue(23), + ) + .addBooleanOption((o) => + o.setName('disable').setDescription('Turn announcements off'), + ), + ); + +export function birthdayCommands(birthdays: BirthdayService): Feature { + return { + name: 'birthdays', + permissions: [ + { + id: 'birthday:manage', + description: 'Configure birthday announcements', + }, + ], + commands: [ + { + data: data.toJSON(), + execute: bySubcommand({ + set: async (interaction) => { + const day = interaction.options.getInteger('day', true); + const month = interaction.options.getInteger('month', true); + const visibility = await birthdays.set( + toActor(interaction.member), + { + day, + month, + visibility: + interaction.options.getString('visibility') ?? 'public', + }, + ); + const leap = + month === 2 && day === 29 + ? ' In non-leap years it is celebrated on 28 February.' + : ''; + + await respond(interaction, `Saved (${visibility}).${leap}`); + }, + remove: async (interaction) => { + const removed = await birthdays.remove(toActor(interaction.member)); + + await respond( + interaction, + removed + ? 'Your birthday data is deleted.' + : 'You had no birthday saved.', + ); + }, + view: async (interaction) => { + const user = + interaction.options.getUser('member') ?? interaction.user; + const birthday = await birthdays.view( + toActor(interaction.member), + user.id, + ); + + await respond( + interaction, + birthday ? describeBirthday(birthday) : 'No birthday to show.', + ); + }, + upcoming: async (interaction) => { + const list = await birthdays.upcoming(interaction.guildId); + + await respond( + interaction, + list.length === 0 + ? 'No public birthdays yet.' + : list.map((birthday) => describeBirthday(birthday)).join('\n'), + ); + }, + settings: async (interaction) => { + const channel = interaction.options.getChannel('channel'); + const role = interaction.options.getRole('role'); + const hour = interaction.options.getInteger('hour'); + const message = await birthdays.configure( + toActor(interaction.member), + { + ...(channel && { channelId: channel.id }), + ...(role && { roleId: role.id }), + ...(hour !== null && { hour }), + disable: interaction.options.getBoolean('disable') ?? false, + }, + ); + + await respond(interaction, message); + }, + }), + }, + ], + }; +} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index d1ffe36..72659ae 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -6,3 +6,4 @@ export * from './announcements'; export * from './events'; export * from './polls'; export * from './movies'; +export * from './birthdays'; diff --git a/tests/core/services/birthdays.test.ts b/tests/core/services/birthdays.test.ts new file mode 100644 index 0000000..7004a68 --- /dev/null +++ b/tests/core/services/birthdays.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Scheduler } from '~/core/ports'; +import { createBirthdayService } from '~/core/services'; +import { calendarDay } from '~/domain'; +import { createBirthdayRepository } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + allowAll, + fakeDirectory, + fakeMessenger, + silentLog, +} from '../../fakes'; + +describe.skipIf(noDatabase)('birthdays', () => { + const repository = () => createBirthdayRepository(testDb()); + const today = { year: 2027, month: 2, day: 28 }; + + it('announces each birthday once per year and respects privacy', async () => { + const birthdays = repository(); + const guildId = snowflake(); + const [pub, announce, priv, leap, other] = [ + snowflake(), + snowflake(), + snowflake(), + snowflake(), + snowflake(), + ]; + + await birthdays.set({ + guildId, + userId: pub, + month: 2, + day: 28, + visibility: 'public', + }); + await birthdays.set({ + guildId, + userId: announce, + month: 2, + day: 28, + visibility: 'announce', + }); + await birthdays.set({ + guildId, + userId: priv, + month: 2, + day: 28, + visibility: 'private', + }); + await birthdays.set({ + guildId, + userId: leap, + month: 2, + day: 29, + visibility: 'public', + }); + await birthdays.set({ + guildId, + userId: other, + month: 3, + day: 1, + visibility: 'public', + }); + + const claimed = await birthdays.claim(guildId, today); + + expect(claimed).toHaveLength(3); + expect(claimed).toEqual(expect.arrayContaining([pub, announce, leap])); + expect(await birthdays.claim(guildId, today)).toEqual([]); + expect( + await birthdays.claim(guildId, { ...today, year: 2028 }), + ).toHaveLength(2); + }); + + it('can release a claim after a failed post', async () => { + const birthdays = repository(); + const guildId = snowflake(); + const user = snowflake(); + + await birthdays.set({ + guildId, + userId: user, + month: 2, + day: 28, + visibility: 'public', + }); + await birthdays.claim(guildId, today); + await birthdays.release(guildId, [user], today.year); + expect(await birthdays.claim(guildId, today)).toEqual([user]); + }); + + it('lists only public birthdays, starting from today', async () => { + const birthdays = repository(); + const guildId = snowflake(); + const [jan, jun, dec, hidden] = [ + snowflake(), + snowflake(), + snowflake(), + snowflake(), + ]; + + await birthdays.set({ + guildId, + userId: jan, + month: 1, + day: 5, + visibility: 'public', + }); + await birthdays.set({ + guildId, + userId: jun, + month: 6, + day: 5, + visibility: 'public', + }); + await birthdays.set({ + guildId, + userId: dec, + month: 12, + day: 5, + visibility: 'public', + }); + await birthdays.set({ + guildId, + userId: hidden, + month: 6, + day: 6, + visibility: 'announce', + }); + + const list = await birthdays.upcoming(guildId, { + year: 2026, + month: 6, + day: 1, + }); + + expect(list.map((b) => b.userId)).toEqual([jun, dec, jan]); + }); + + it('posts one message per day and reschedules', async () => { + const { messenger } = fakeMessenger(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const service = createBirthdayService({ + birthdays: repository(), + scheduler, + messenger, + directory: fakeDirectory(), + authz: allowAll, + log: silentLog, + timezone: async () => 'Europe/Tallinn', + }); + const admin = actor({ guildId: snowflake(), userId: snowflake() }); + const now = calendarDay(new Date(), 'Europe/Tallinn'); + + await service.set(admin, { day: now.day, month: now.month }); + await service.configure(admin, { channelId: 'c' }); + + const [daily] = service.jobs; + const info = { id: 1, runAt: new Date(), attempt: 1 }; + const outcome = await daily?.run({ guildId: admin.guildId }, info); + + await daily?.run({ guildId: admin.guildId }, info); + expect(messenger.send).toHaveBeenCalledOnce(); + expect(messenger.send).toHaveBeenCalledWith( + 'c', + expect.objectContaining({ mentions: { users: [admin.userId] } }), + ); + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); + }); + + it('hides non-public birthdays from other members', async () => { + const service = createBirthdayService({ + birthdays: repository(), + scheduler: { + schedule: async () => undefined, + cancel: async () => undefined, + }, + messenger: fakeMessenger().messenger, + directory: fakeDirectory(), + authz: allowAll, + log: silentLog, + timezone: async () => 'Europe/Tallinn', + }); + const owner = actor({ guildId: snowflake(), userId: snowflake() }); + + await service.set(owner, { day: 1, month: 5, visibility: 'announce' }); + expect(await service.view(owner, owner.userId)).toBeDefined(); + expect( + await service.view(actor({ guildId: owner.guildId }), owner.userId), + ).toBeUndefined(); + }); +}); diff --git a/tests/domain/birthday.test.ts b/tests/domain/birthday.test.ts new file mode 100644 index 0000000..3a7120d --- /dev/null +++ b/tests/domain/birthday.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +import { celebratedOn, nextDailyRun, validateBirthday } from '~/domain'; + +describe('birthday dates', () => { + it('accepts 29 February and rejects impossible dates', () => { + expect(() => validateBirthday(2, 29)).not.toThrow(); + expect(() => validateBirthday(2, 30)).toThrow('valid date'); + expect(() => validateBirthday(4, 31)).toThrow('valid date'); + }); + + it('celebrates leap-day birthdays on 28 February in non-leap years', () => { + expect(celebratedOn({ year: 2027, month: 2, day: 28 })).toEqual([ + { month: 2, day: 28 }, + { month: 2, day: 29 }, + ]); + expect(celebratedOn({ year: 2028, month: 2, day: 28 })).toEqual([ + { month: 2, day: 28 }, + ]); + }); + + it('computes the next announcement hour in the guild timezone', () => { + const now = new Date('2026-06-01T10:00:00Z'); + + expect(nextDailyRun('Europe/Tallinn', 9, now).toISOString()).toBe( + '2026-06-02T06:00:00.000Z', + ); + expect(nextDailyRun('Europe/Tallinn', 15, now).toISOString()).toBe( + '2026-06-01T12:00:00.000Z', + ); + }); +}); diff --git a/tests/features/birthdays/birthdays.test.ts b/tests/features/birthdays/birthdays.test.ts deleted file mode 100644 index cef3af4..0000000 --- a/tests/features/birthdays/birthdays.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { pino } from 'pino'; -import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { AppContext } from '~/infra/discord'; -import { calendarDay, nextDailyRun } from '~/domain'; -import { dailyJob } from '~/features/birthdays'; -import { - celebratedOn, - claimTodaysBirthdays, - releaseClaims, - saveSettings, - setBirthday, - upcomingBirthdays, - validateDate, -} from '~/features/birthdays/service'; - -describe('birthday dates', () => { - it('accepts 29 February and rejects impossible dates', () => { - expect(() => validateDate(2, 29)).not.toThrow(); - expect(() => validateDate(2, 30)).toThrow('valid date'); - expect(() => validateDate(4, 31)).toThrow('valid date'); - }); - - it('celebrates leap-day birthdays on 28 February in non-leap years', () => { - expect(celebratedOn({ year: 2027, month: 2, day: 28 })).toEqual([ - { month: 2, day: 28 }, - { month: 2, day: 29 }, - ]); - expect(celebratedOn({ year: 2028, month: 2, day: 28 })).toEqual([ - { month: 2, day: 28 }, - ]); - expect(celebratedOn({ year: 2028, month: 2, day: 29 })).toEqual([ - { month: 2, day: 29 }, - ]); - }); - - it('computes the next announcement hour in the guild timezone', () => { - const now = new Date('2026-06-01T10:00:00Z'); - - expect(nextDailyRun('Europe/Tallinn', 9, now).toISOString()).toBe( - '2026-06-02T06:00:00.000Z', - ); - expect(nextDailyRun('Europe/Tallinn', 15, now).toISOString()).toBe( - '2026-06-01T12:00:00.000Z', - ); - }); -}); - -describe.skipIf(noDatabase)('birthday announcements', () => { - const today = { year: 2027, month: 2, day: 28 }; - - it('announces each birthday once per year and respects privacy', async () => { - const db = testDb(); - const guildId = snowflake(); - const [pub, announce, priv, leap, other] = [ - snowflake(), - snowflake(), - snowflake(), - snowflake(), - snowflake(), - ]; - - await setBirthday(db, { - guildId, - userId: pub, - month: 2, - day: 28, - visibility: 'public', - }); - await setBirthday(db, { - guildId, - userId: announce, - month: 2, - day: 28, - visibility: 'announce', - }); - await setBirthday(db, { - guildId, - userId: priv, - month: 2, - day: 28, - visibility: 'private', - }); - await setBirthday(db, { - guildId, - userId: leap, - month: 2, - day: 29, - visibility: 'public', - }); - await setBirthday(db, { - guildId, - userId: other, - month: 3, - day: 1, - visibility: 'public', - }); - - const claimed = await claimTodaysBirthdays(db, guildId, today); - - expect(claimed).toHaveLength(3); - expect(claimed).toEqual(expect.arrayContaining([pub, announce, leap])); - expect(await claimTodaysBirthdays(db, guildId, today)).toEqual([]); - expect( - await claimTodaysBirthdays(db, guildId, { - ...today, - year: today.year + 1, - }), - ).toHaveLength(2); - }); - - it('can release a claim after a failed post', async () => { - const db = testDb(); - const guildId = snowflake(); - const user = snowflake(); - - await setBirthday(db, { - guildId, - userId: user, - month: 2, - day: 28, - visibility: 'public', - }); - await claimTodaysBirthdays(db, guildId, today); - await releaseClaims(db, guildId, [user], today.year); - expect(await claimTodaysBirthdays(db, guildId, today)).toEqual([user]); - }); - - it('lists only public birthdays, starting from today', async () => { - const db = testDb(); - const guildId = snowflake(); - const [jan, jun, dec, hidden] = [ - snowflake(), - snowflake(), - snowflake(), - snowflake(), - ]; - - await setBirthday(db, { - guildId, - userId: jan, - month: 1, - day: 5, - visibility: 'public', - }); - await setBirthday(db, { - guildId, - userId: jun, - month: 6, - day: 5, - visibility: 'public', - }); - await setBirthday(db, { - guildId, - userId: dec, - month: 12, - day: 5, - visibility: 'public', - }); - await setBirthday(db, { - guildId, - userId: hidden, - month: 6, - day: 6, - visibility: 'announce', - }); - const list = await upcomingBirthdays(db, guildId, { - year: 2026, - month: 6, - day: 1, - }); - - expect(list.map((b) => b.userId)).toEqual([jun, dec, jan]); - }); - - it('posts one message and reschedules for the next day', async () => { - const db = testDb(); - const guildId = snowflake(); - const user = snowflake(); - const now = calendarDay(new Date(), 'Europe/Tallinn'); - - await setBirthday(db, { - guildId, - userId: user, - month: now.month, - day: now.day, - visibility: 'public', - }); - await saveSettings(db, { - guildId, - channelId: snowflake(), - roleId: null, - hour: 9, - }); - const send = vi.fn(async () => undefined); - const ctx = { - db, - log: pino({ level: 'silent' }), - config: { DEFAULT_TIMEZONE: 'Europe/Tallinn' }, - client: { - channels: { fetch: async () => ({ isSendable: () => true, send }) }, - }, - } as unknown as AppContext; - const info = { id: 1, runAt: new Date(), attempt: 1 }; - const outcome = await dailyJob.run({ guildId }, info, ctx); - - await dailyJob.run({ guildId }, info, ctx); - expect(send).toHaveBeenCalledOnce(); - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ allowedMentions: { users: [user] } }), - ); - expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); - }); -}); From b4fa78ba9bf874383ea294047f30499b5da7e73f Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 21:28:44 +0200 Subject: [PATCH 029/199] refactor(redmine): issue tracker port with Redmine as an adapter --- src/app.ts | 54 +- src/core/ports/index.ts | 1 + src/core/ports/issues.ts | 59 ++ src/core/services/index.ts | 1 + src/core/services/redmine.ts | 457 +++++++++++++ src/domain/index.ts | 1 + src/domain/issue.ts | 168 +++++ src/features/redmine/index.ts | 647 ------------------ src/features/redmine/notifications.ts | 202 ------ src/infra/db/index.ts | 2 + .../schema.ts => infra/db/redmine/model.ts} | 0 .../service.ts => infra/db/redmine/repo.ts} | 96 +-- src/infra/discord/commands/index.ts | 1 + src/infra/discord/commands/redmine.ts | 436 ++++++++++++ src/infra/redmine/client.ts | 123 ++-- tests/core/services/redmine.test.ts | 141 ++++ tests/domain/issue.test.ts | 92 +++ tests/features/redmine/redmine.test.ts | 198 ------ tests/infra/redmine/client.test.ts | 5 +- 19 files changed, 1476 insertions(+), 1208 deletions(-) create mode 100644 src/core/ports/issues.ts create mode 100644 src/core/services/redmine.ts create mode 100644 src/domain/issue.ts delete mode 100644 src/features/redmine/index.ts delete mode 100644 src/features/redmine/notifications.ts rename src/{features/redmine/schema.ts => infra/db/redmine/model.ts} (100%) rename src/{features/redmine/service.ts => infra/db/redmine/repo.ts} (53%) create mode 100644 src/infra/discord/commands/redmine.ts create mode 100644 tests/core/services/redmine.test.ts create mode 100644 tests/domain/issue.test.ts delete mode 100644 tests/features/redmine/redmine.test.ts diff --git a/src/app.ts b/src/app.ts index a849f23..98485f4 100644 --- a/src/app.ts +++ b/src/app.ts @@ -4,6 +4,7 @@ import { announcementCommands, birthdayCommands, createClient, + redmineCommands, createDiscordCalendar, eventCommands, movieCommands, @@ -20,6 +21,7 @@ import { import { createAnnouncementService, createAuthorizer, + createRedmineService, createBirthdayService, createEventService, createMovieService, @@ -40,6 +42,8 @@ import { createEventRepository, createBirthdayRepository, createGrantRepository, + createTrackerRepository, + type Db, createMovieRepository, createPollRepository, createReminderRepository, @@ -47,7 +51,8 @@ import { createSettingsRepository, runMigrations, } from '~/infra/db'; -import { createRedmineFeature } from '~/features/redmine'; +import { createSecretBox } from '~/infra/crypto'; +import { RedmineClient } from '~/infra/redmine'; function legacyPanel(config: Config): LegacyPanel | undefined { const channelId = config.ROLE_SELECTION_CHANNEL_ID; @@ -67,6 +72,40 @@ function legacyPanel(config: Config): LegacyPanel | undefined { return { channelId, roles }; } +type RedmineDeps = Omit< + Parameters[0], + 'baseUrl' | 'connect' | 'service' | 'tracker' | 'secrets' | 'defaultTimezone' +> & { db: Db }; + +function createRedmine(config: Config, { db, ...deps }: RedmineDeps) { + const baseUrl = config.REDMINE_BASE_URL; + + if (baseUrl === undefined) { + return null; + } + + if (config.CREDENTIAL_ENCRYPTION_KEY === undefined) { + throw new Error( + 'CREDENTIAL_ENCRYPTION_KEY is required when REDMINE_BASE_URL is set', + ); + } + + const connect = (apiKey: string) => new RedmineClient(baseUrl, apiKey); + + return createRedmineService({ + ...deps, + baseUrl, + connect, + service: + config.REDMINE_API_KEY === undefined + ? undefined + : connect(config.REDMINE_API_KEY), + tracker: createTrackerRepository(db), + secrets: createSecretBox(config.CREDENTIAL_ENCRYPTION_KEY), + defaultTimezone: config.DEFAULT_TIMEZONE, + }); +} + export function compose(config: Config, log: Logger) { const database = connectDatabase(config.DATABASE_URL); const client = createClient(); @@ -166,10 +205,19 @@ export function compose(config: Config, log: Logger) { pollCommands(polls), movieCommands(movies), ]; - const redmine = createRedmineFeature(config, reminders); + const redmine = createRedmine(config, { + db: database.db, + reminders, + scheduler, + messenger, + authz, + log, + timezone: (guildId) => settings.timezone(guildId), + }); if (redmine) { - features.push(redmine); + features.push(redmineCommands(redmine, config.REDMINE_BASE_URL ?? '')); + jobs.push(...redmine.jobs); } const registry = buildRegistry(features); diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 5cc1ffe..42708fd 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -12,3 +12,4 @@ export * from './events'; export type * from './polls'; export type * from './movies'; export type * from './birthdays'; +export type * from './issues'; diff --git a/src/core/ports/issues.ts b/src/core/ports/issues.ts new file mode 100644 index 0000000..aa96ef5 --- /dev/null +++ b/src/core/ports/issues.ts @@ -0,0 +1,59 @@ +import type { + Issue, + IssueChanges, + IssueQuery, + IssueStatus, + TrackerProject, + TrackerUser, +} from '~/domain'; + +export type IssueTracker = { + currentUser: () => Promise; + listProjects: ( + offset?: number, + limit?: number, + ) => Promise<{ projects: TrackerProject[]; total: number }>; + listIssues: ( + query?: IssueQuery, + ) => Promise<{ issues: Issue[]; total: number }>; + getIssue: (id: number, withJournals?: boolean) => Promise; + listStatuses: () => Promise; + createIssue: ( + fields: IssueChanges & { project_id: number | string; subject: string }, + ) => Promise; + updateIssue: (id: number, changes: IssueChanges) => Promise; +}; + +export type TrackerLink = { + userId: string; + redmineUserId: number; + redmineLogin: string; + encryptedApiKey: string; +}; + +export type Subscription = { + id: number; + guildId: string; + channelId: string; + projectId: number; + projectName: string; + createdBy: string; + checkpoint: Date; +}; + +export type TrackerRepository = { + saveLink: (link: TrackerLink) => Promise; + link: (userId: string) => Promise; + unlink: (userId: string) => Promise; + subscribe: ( + subscription: Omit, + ) => Promise; + unsubscribe: ( + guildId: string, + channelId: string, + projectId: number, + ) => Promise; + subscriptions: (afterId?: number, limit?: number) => Promise; + setCheckpoint: (id: number, checkpoint: Date) => Promise; + claimNotification: (subscriptionId: number, key: string) => Promise; +}; diff --git a/src/core/services/index.ts b/src/core/services/index.ts index 872710f..c527a82 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -9,3 +9,4 @@ export * from './events'; export * from './polls'; export * from './movies'; export * from './birthdays'; +export * from './redmine'; diff --git a/src/core/services/redmine.ts b/src/core/services/redmine.ts new file mode 100644 index 0000000..52af81b --- /dev/null +++ b/src/core/services/redmine.ts @@ -0,0 +1,457 @@ +import { z } from 'zod'; +import { + addCalendarDays, + calendarDay, + formatCalendarDay, + IntegrationError, + issueNotifications, + nextDailyRun, + parseCalendarDay, + UserError, + zonedTime, + type Actor, + type IssueQuery, + type IssueStatus, + type Notification, + type TrackerUser, +} from '~/domain'; +import type { + Authorizer, + IssueTracker, + Logger, + Messenger, + Scheduler, + SecretBox, + Subscription, + TrackerRepository, +} from '~/core/ports'; +import { sequential } from '~/lib'; +import { guard } from './guard'; +import { defineJob } from './jobs'; +import type { ReminderService } from './reminders'; + +const pollIntervalMs = 2 * 60 * 1000; +const issuesPerPoll = 25; +const deadlineHour = 9; + +export type IssueDraft = { + project: string; + subject: string; + description?: string; + assignToMe?: boolean; +}; + +type Deps = { + baseUrl: string; + connect: (apiKey: string) => IssueTracker; + service?: IssueTracker | undefined; + tracker: TrackerRepository; + secrets: SecretBox; + reminders: ReminderService; + scheduler: Scheduler; + messenger: Messenger; + authz: Authorizer; + log: Logger; + defaultTimezone: string; + timezone: (guildId: string) => Promise; +}; + +export function createRedmineService(deps: Deps) { + const { + connect, + service, + tracker, + secrets, + reminders, + messenger, + authz, + log, + } = deps; + const root = deps.baseUrl.endsWith('/') ? deps.baseUrl : `${deps.baseUrl}/`; + const issueUrl = (id: number) => `${root}issues/${id}`; + + const asUser = async ( + actor: Actor, + run: (client: IssueTracker, redmineUserId: number) => Promise, + ) => { + const link = await tracker.link(actor.userId); + + if (!link) { + throw new UserError( + 'Link your Redmine account first with "/redmine link".', + ); + } + + try { + return await run( + connect(secrets.decrypt(link.encryptedApiKey)), + link.redmineUserId, + ); + } catch (error) { + if (error instanceof IntegrationError) { + log.warn( + { kind: error.kind, userId: actor.userId }, + 'Redmine request failed', + ); + + throw new UserError(error.message); + } + + throw error; + } + }; + + const requireService = () => { + if (!service) { + throw new UserError( + 'Redmine notifications are not configured (REDMINE_API_KEY).', + ); + } + + return service; + }; + + const sendOnce = async ( + subscription: Subscription, + notification: Notification, + ) => { + if (!(await tracker.claimNotification(subscription.id, notification.key))) { + return; + } + + await messenger.send(subscription.channelId, { + content: notification.text.slice(0, 2000), + suppressEmbeds: true, + }); + }; + + const forEachSubscription = async ( + handle: (subscription: Subscription) => Promise, + afterId = 0, + ): Promise => { + const page = await tracker.subscriptions(afterId); + + await sequential(page, async (subscription) => { + try { + await handle(subscription); + } catch (error) { + log.warn( + { err: error, subscriptionId: subscription.id }, + 'Redmine subscription update failed', + ); + } + }); + + const last = page.at(-1); + + if (last !== undefined) { + await forEachSubscription(handle, last.id); + } + }; + + const pollSubscription = async ( + client: IssueTracker, + subscription: Subscription, + statuses: ReadonlyMap, + ) => { + const { issues } = await client.listIssues({ + projectId: subscription.projectId, + status: '*', + updatedSince: subscription.checkpoint, + sort: 'updated_on:asc', + limit: issuesPerPoll, + }); + let checkpoint = subscription.checkpoint; + + await sequential(issues, async (summary) => { + const issue = await client.getIssue(summary.id, true); + const notifications = issueNotifications( + issue, + subscription.checkpoint, + statuses, + issueUrl(issue.id), + ); + + await sequential(notifications, (notification) => + sendOnce(subscription, notification), + ); + + const updated = new Date(issue.updated_on); + + if (updated > checkpoint) { + checkpoint = updated; + } + }); + + if (checkpoint > subscription.checkpoint) { + await tracker.setCheckpoint(subscription.id, checkpoint); + } + }; + + const pollJob = defineJob({ + type: 'redmine:poll', + payload: z.object({}), + handle: async () => { + const client = requireService(); + const known = await client.listStatuses().catch(() => []); + const statuses = new Map(known.map((status) => [status.id, status])); + + await forEachSubscription((subscription) => + pollSubscription(client, subscription, statuses), + ); + + return { rescheduleAt: new Date(Date.now() + pollIntervalMs) }; + }, + }); + + const deadlineJob = defineJob({ + type: 'redmine:deadlines', + payload: z.object({}), + handle: async () => { + const client = requireService(); + const zone = deps.defaultTimezone; + const tomorrow = formatCalendarDay( + addCalendarDays(calendarDay(new Date(), zone), 1), + ); + + await forEachSubscription(async (subscription) => { + const { issues } = await client.listIssues({ + projectId: subscription.projectId, + dueDate: tomorrow, + limit: 50, + }); + const visible = issues.filter((issue) => issue.is_private !== true); + + await sequential(visible, (issue) => + sendOnce(subscription, { + key: `due:${issue.id}:${tomorrow}`, + text: [ + `⏳ Due tomorrow: [#${issue.id}](${issueUrl(issue.id)}) ${issue.subject}`, + issue.assigned_to?.name, + ] + .filter(Boolean) + .join(' · '), + }), + ); + }); + + return { rescheduleAt: nextDailyRun(zone, deadlineHour) }; + }, + }); + + const subscription = async (actor: Actor, identifier: string) => + asUser(actor, async (client) => { + const { projects } = await client.listProjects(0, 100); + const project = projects.find( + (p) => p.identifier === identifier || String(p.id) === identifier, + ); + + if (!project) { + throw new UserError( + `Project "${identifier}" not found among your projects.`, + ); + } + + return project; + }); + + return { + issueUrl, + jobs: service ? [pollJob, deadlineJob] : [], + start: async () => { + if (!service) { + return; + } + + await deps.scheduler.schedule( + pollJob, + {}, + { runAt: new Date(Date.now() + 10_000), key: 'redmine:poll' }, + ); + await deps.scheduler.schedule( + deadlineJob, + {}, + { + runAt: nextDailyRun(deps.defaultTimezone, deadlineHour), + key: 'redmine:deadlines', + }, + ); + }, + link: async (actor: Actor, apiKey: string) => { + let user: TrackerUser; + + try { + user = await connect(apiKey.trim()).currentUser(); + } catch (error) { + if (error instanceof IntegrationError) { + throw new UserError( + error.kind === 'auth' + ? 'Redmine did not accept that API key.' + : error.message, + ); + } + + throw error; + } + + await tracker.saveLink({ + userId: actor.userId, + redmineUserId: user.id, + redmineLogin: user.login, + encryptedApiKey: secrets.encrypt(apiKey.trim()), + }); + log.info( + { userId: actor.userId, redmineUserId: user.id }, + 'Redmine account linked', + ); + + return user; + }, + unlink: async (actor: Actor) => { + const removed = await tracker.unlink(actor.userId); + + log.info({ userId: actor.userId, removed }, 'Redmine account unlinked'); + + return removed; + }, + projects: (actor: Actor) => + asUser(actor, (client) => client.listProjects()), + issues: (actor: Actor, query: IssueQuery) => + asUser(actor, (client) => client.listIssues({ ...query, limit: 15 })), + issue: (actor: Actor, id: number) => + asUser(actor, (client) => client.getIssue(id)), + statuses: (actor: Actor) => + asUser(actor, (client) => client.listStatuses()), + createIssue: guard( + authz, + 'redmine:issue:create', + (actor, draft: IssueDraft) => + asUser(actor, (client, redmineUserId) => + client.createIssue({ + project_id: draft.project, + subject: draft.subject, + ...(draft.description !== undefined && { + description: draft.description, + }), + ...(draft.assignToMe === true && { assigned_to_id: redmineUserId }), + }), + ), + ), + updateIssue: guard( + authz, + 'redmine:issue:update', + (actor, id: number, changes: { statusId?: number; notes?: string }) => { + if (changes.statusId === undefined && changes.notes === undefined) { + throw new UserError('Give a new status or notes.'); + } + + return asUser(actor, (client) => + client.updateIssue(id, { + ...(changes.statusId !== undefined && { + status_id: changes.statusId, + }), + ...(changes.notes !== undefined && { notes: changes.notes }), + }), + ); + }, + ), + comment: guard( + authz, + 'redmine:issue:update', + (actor, id: number, notes: string) => + asUser(actor, (client) => client.updateIssue(id, { notes })), + ), + assign: guard( + authz, + 'redmine:issue:assign', + async (actor, id: number, memberId?: string) => { + const target = + memberId === undefined || memberId === actor.userId + ? undefined + : await tracker.link(memberId); + + if (memberId !== undefined && memberId !== actor.userId && !target) { + throw new UserError('That member has not linked a Redmine account.'); + } + + return asUser(actor, (client, redmineUserId) => + client.updateIssue(id, { + assigned_to_id: target?.redmineUserId ?? redmineUserId, + }), + ); + }, + ), + remind: async (actor: Actor, id: number, daysBefore = 1) => { + const issue = await asUser(actor, (client) => client.getIssue(id)); + const due = parseCalendarDay(issue.due_date ?? ''); + + if (!due) { + throw new UserError(`#${issue.id} has no due date.`); + } + + const timezone = await deps.timezone(actor.guildId); + const runAt = zonedTime(addCalendarDays(due, -daysBefore), 9, timezone); + + if (runAt.getTime() <= Date.now()) { + throw new UserError('That reminder time has already passed.'); + } + + return reminders.schedule({ + guildId: actor.guildId, + userId: actor.userId, + channelId: null, + message: `Redmine #${issue.id} "${issue.subject}" is due ${issue.due_date ?? ''}: ${issueUrl(issue.id)}`, + runAt, + recurrence: null, + timezone, + }); + }, + subscribe: guard( + authz, + 'redmine:subscription:manage', + async (actor, channelId: string, identifier: string) => { + const project = await subscription(actor, identifier); + + await requireService().listIssues({ projectId: project.id, limit: 1 }); + + const added = await tracker.subscribe({ + guildId: actor.guildId, + channelId, + projectId: project.id, + projectName: project.name, + createdBy: actor.userId, + }); + + log.info( + { + guildId: actor.guildId, + channelId, + projectId: project.id, + actorId: actor.userId, + }, + 'Redmine subscription added', + ); + + return { project, added }; + }, + ), + unsubscribe: guard( + authz, + 'redmine:subscription:manage', + async (actor, channelId: string, identifier: string) => { + const project = await subscription(actor, identifier); + + return { + project, + removed: await tracker.unsubscribe( + actor.guildId, + channelId, + project.id, + ), + }; + }, + ), + }; +} + +export type RedmineService = ReturnType; diff --git a/src/domain/index.ts b/src/domain/index.ts index 6960764..3a915e8 100644 --- a/src/domain/index.ts +++ b/src/domain/index.ts @@ -7,3 +7,4 @@ export * from './time'; export * from './poll'; export * from './movie'; export * from './birthday'; +export * from './issue'; diff --git a/src/domain/issue.ts b/src/domain/issue.ts new file mode 100644 index 0000000..a873643 --- /dev/null +++ b/src/domain/issue.ts @@ -0,0 +1,168 @@ +export type Named = { id: number; name: string }; + +export type TrackerUser = { + id: number; + login: string; + firstname?: string; + lastname?: string; +}; + +export type TrackerProject = { + id: number; + name: string; + identifier: string; + description?: string | null; +}; + +export type IssueStatus = Named & { is_closed?: boolean }; + +export type JournalDetail = { + property: string; + name: string; + old_value?: string | null; + new_value?: string | null; +}; + +export type Journal = { + id: number; + user?: Named; + notes?: string | null; + private_notes?: boolean; + created_on: string; + details: JournalDetail[]; +}; + +export type Issue = { + id: number; + project: Named; + tracker: Named; + status: IssueStatus; + priority: Named; + author: Named; + assigned_to?: Named; + subject: string; + description?: string | null; + due_date?: string | null; + done_ratio?: number; + is_private?: boolean; + created_on: string; + updated_on: string; + journals?: Journal[]; +}; + +export type IssueQuery = { + projectId?: number | string; + assignedToMe?: boolean; + status?: 'open' | 'closed' | '*'; + updatedSince?: Date; + dueDate?: string; + sort?: string; + offset?: number; + limit?: number; +}; + +export type IssueChanges = { + subject?: string; + description?: string; + status_id?: number; + assigned_to_id?: number; + notes?: string; +}; + +export type IntegrationErrorKind = + | 'auth' + | 'forbidden' + | 'not_found' + | 'validation' + | 'unavailable' + | 'invalid_response'; + +export class IntegrationError extends Error { + override readonly name = 'IntegrationError'; + + constructor( + readonly kind: IntegrationErrorKind, + message: string, + ) { + super(message); + } +} + +export type Notification = { key: string; text: string }; + +export function issueNotifications( + issue: Issue, + since: Date, + statuses: ReadonlyMap, + issueUrl: string, +): Notification[] { + if (issue.is_private === true) { + return []; + } + + const title = `[#${issue.id}](${issueUrl}) ${issue.subject}`; + const notifications: Notification[] = []; + + if (new Date(issue.created_on) >= since) { + const assignee = issue.assigned_to + ? `, assigned to ${issue.assigned_to.name}` + : ''; + + notifications.push({ + key: `issue:${issue.id}:created`, + text: `🆕 ${issue.tracker.name} ${title} by ${issue.author.name}${assignee}`, + }); + } + + for (const journal of issue.journals ?? []) { + if ( + new Date(journal.created_on) < since || + journal.private_notes === true + ) { + continue; + } + + const changes = journal.details.flatMap((detail) => { + if (detail.property !== 'attr') { + return []; + } + + if (detail.name === 'status_id') { + const name = (id?: string | null) => + statuses.get(Number(id))?.name ?? '?'; + + return [`status ${name(detail.old_value)} → ${name(detail.new_value)}`]; + } + + if (detail.name === 'assigned_to_id') { + const matches = + issue.assigned_to && + String(issue.assigned_to.id) === detail.new_value; + + return [ + matches === true + ? `assigned to ${issue.assigned_to?.name ?? ''}` + : 'assignee changed', + ]; + } + + return []; + }); + const notes = journal.notes?.trim() ?? ''; + + if (changes.length === 0 && notes === '') { + continue; + } + + const who = journal.user?.name ?? 'Someone'; + const comment = + notes === '' ? '' : `\n> ${notes.slice(0, 300).replaceAll('\n', '\n> ')}`; + + notifications.push({ + key: `journal:${journal.id}`, + text: `✏️ ${title}: ${[who, ...changes].join(' · ')}${comment}`, + }); + } + + return notifications; +} diff --git a/src/features/redmine/index.ts b/src/features/redmine/index.ts deleted file mode 100644 index 0f22d66..0000000 --- a/src/features/redmine/index.ts +++ /dev/null @@ -1,647 +0,0 @@ -import { - ChannelType, - EmbedBuilder, - InteractionContextType, - LabelBuilder, - MessageFlags, - ModalBuilder, - SlashCommandBuilder, - TextInputBuilder, - TextInputStyle, - type SlashCommandIntegerOption, -} from 'discord.js'; -import { respond, bySubcommand, deferred } from '~/infra/discord'; -import type { Config } from '~/config'; -import type { - AppContext, - CommandInteraction, - ComponentHandler, - Feature, - SlashCommand, -} from '~/infra/discord'; -import { getGuildTimezone } from '~/infra/db'; -import { - RedmineClient, - RedmineError, - type RedmineIssue, - type RedmineUser, -} from '~/infra/redmine'; -import { createSecretBox, type SecretBox } from '~/infra/crypto'; -import { - UserError, - addCalendarDays, - parseCalendarDay, - zonedTime, -} from '~/domain'; -import type { ReminderService } from '~/core/services'; -import { createNotificationJobs } from './notifications'; -import { - addSubscription, - deleteLink, - getLink, - removeSubscription, - saveLink, -} from './service'; - -type Handler = ( - interaction: CommandInteraction, - ctx: AppContext, -) => Promise; - -function withRedmineErrors(handler: Handler): Handler { - return async (interaction, ctx) => { - try { - await handler(interaction, ctx); - } catch (error) { - if (error instanceof RedmineError) { - ctx.log.warn( - { kind: error.kind, userId: interaction.user.id }, - 'Redmine request failed', - ); - throw new UserError(error.message); - } - - throw error; - } - }; -} - -const issueOption = (o: SlashCommandIntegerOption) => - o - .setName('issue') - .setDescription('Issue number') - .setRequired(true) - .setMinValue(1); - -const data = new SlashCommandBuilder() - .setName('redmine') - .setDescription('Redmine projects and issues') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub.setName('projects').setDescription('Projects you can see'), - ) - .addSubcommand((sub) => - sub - .setName('issues') - .setDescription('List issues') - .addStringOption((o) => - o.setName('project').setDescription('Project identifier'), - ) - .addBooleanOption((o) => - o.setName('mine').setDescription('Only issues assigned to me'), - ) - .addStringOption((o) => - o - .setName('status') - .setDescription('Status filter') - .addChoices( - { name: 'open', value: 'open' }, - { name: 'closed', value: 'closed' }, - { name: 'all', value: '*' }, - ), - ), - ) - .addSubcommandGroup((group) => - group - .setName('issue') - .setDescription('A single issue') - .addSubcommand((sub) => - sub - .setName('view') - .setDescription('Show an issue') - .addIntegerOption(issueOption), - ) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Create an issue') - .addStringOption((o) => - o - .setName('project') - .setDescription('Project identifier') - .setRequired(true), - ) - .addStringOption((o) => - o - .setName('subject') - .setDescription('Subject') - .setRequired(true) - .setMaxLength(255), - ) - .addStringOption((o) => - o - .setName('description') - .setDescription('Description') - .setMaxLength(4000), - ) - .addBooleanOption((o) => - o.setName('assign_to_me').setDescription('Assign it to me'), - ), - ) - .addSubcommand((sub) => - sub - .setName('update') - .setDescription('Change status or add notes') - .addIntegerOption(issueOption) - .addIntegerOption((o) => - o - .setName('status') - .setDescription('New status') - .setAutocomplete(true), - ) - .addStringOption((o) => - o.setName('notes').setDescription('Notes').setMaxLength(4000), - ), - ) - .addSubcommand((sub) => - sub - .setName('assign') - .setDescription('Assign an issue') - .addIntegerOption(issueOption) - .addUserOption((o) => - o.setName('member').setDescription('Linked member (default: you)'), - ), - ) - .addSubcommand((sub) => - sub - .setName('comment') - .setDescription('Comment on an issue') - .addIntegerOption(issueOption) - .addStringOption((o) => - o - .setName('text') - .setDescription('Comment') - .setRequired(true) - .setMaxLength(4000), - ), - ) - .addSubcommand((sub) => - sub - .setName('remind') - .setDescription('DM me before the due date') - .addIntegerOption(issueOption) - .addIntegerOption((o) => - o - .setName('days_before') - .setDescription('Days before (default 1)') - .setMinValue(0) - .setMaxValue(30), - ), - ), - ) - .addSubcommand((sub) => - sub - .setName('link') - .setDescription('Link your Redmine account with your API key'), - ) - .addSubcommand((sub) => - sub.setName('unlink').setDescription('Remove your stored Redmine key'), - ) - .addSubcommand((sub) => - sub - .setName('subscribe') - .setDescription('Post project updates in a channel') - .addStringOption((o) => - o - .setName('project') - .setDescription('Project identifier') - .setRequired(true), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Channel (default: here)') - .addChannelTypes(ChannelType.GuildText), - ), - ) - .addSubcommand((sub) => - sub - .setName('unsubscribe') - .setDescription('Stop project updates in a channel') - .addStringOption((o) => - o - .setName('project') - .setDescription('Project identifier') - .setRequired(true), - ) - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Channel (default: here)') - .addChannelTypes(ChannelType.GuildText), - ), - ); - -function issueLine(baseUrl: string, issue: RedmineIssue): string { - const assignee = issue.assigned_to ? ` · ${issue.assigned_to.name}` : ''; - - return `[#${issue.id}](<${baseUrl}issues/${issue.id}>) **${issue.subject}** — ${issue.status.name}${assignee}`; -} - -function issueEmbed(baseUrl: string, issue: RedmineIssue): EmbedBuilder { - return new EmbedBuilder() - .setTitle(`#${issue.id} ${issue.subject}`.slice(0, 256)) - .setURL(`${baseUrl}issues/${issue.id}`) - .setDescription((issue.description ?? '').slice(0, 1500) || null) - .addFields( - { name: 'Project', value: issue.project.name, inline: true }, - { name: 'Status', value: issue.status.name, inline: true }, - { name: 'Priority', value: issue.priority.name, inline: true }, - { name: 'Assignee', value: issue.assigned_to?.name ?? '—', inline: true }, - { name: 'Due', value: issue.due_date ?? '—', inline: true }, - ); -} - -export function createRedmineFeature( - config: Config, - reminders: ReminderService, -): Feature | undefined { - const base = config.REDMINE_BASE_URL; - - if (base === undefined) { - return undefined; - } - - if (config.CREDENTIAL_ENCRYPTION_KEY === undefined) { - throw new Error( - 'CREDENTIAL_ENCRYPTION_KEY is required when REDMINE_BASE_URL is set', - ); - } - - const baseUrl = base.endsWith('/') ? base : `${base}/`; - const box: SecretBox = createSecretBox(config.CREDENTIAL_ENCRYPTION_KEY); - const service = - config.REDMINE_API_KEY === undefined - ? undefined - : new RedmineClient(baseUrl, config.REDMINE_API_KEY); - const notifications = service && createNotificationJobs(service, baseUrl); - - async function clientFor( - ctx: AppContext, - userId: string, - ): Promise<{ client: RedmineClient; redmineUserId: number }> { - const link = await getLink(ctx.db, userId); - - if (!link) { - throw new UserError( - 'Link your Redmine account first with `/redmine link`.', - ); - } - - return { - client: new RedmineClient(baseUrl, box.decrypt(link.encryptedApiKey)), - redmineUserId: link.redmineUserId, - }; - } - - const requireService = (): RedmineClient => { - if (!service) { - throw new UserError( - 'Redmine notifications are not configured (REDMINE_API_KEY).', - ); - } - - return service; - }; - - const subscription = - (action: 'subscribe' | 'unsubscribe'): Handler => - async (interaction, ctx) => { - const channelId = - interaction.options.getChannel('channel')?.id ?? interaction.channelId; - const { client } = await clientFor(ctx, interaction.user.id); - const identifier = interaction.options.getString('project', true); - const { projects } = await client.listProjects(0, 100); - const project = projects.find( - (p) => p.identifier === identifier || String(p.id) === identifier, - ); - - if (!project) { - throw new UserError( - `Project "${identifier}" not found among your projects.`, - ); - } - - if (action === 'unsubscribe') { - const removed = await removeSubscription( - ctx.db, - interaction.guildId, - channelId, - project.id, - ); - - await respond( - interaction, - removed - ? `Unsubscribed <#${channelId}> from ${project.name}.` - : 'No such subscription.', - ); - - return; - } - - await requireService().listIssues({ projectId: project.id, limit: 1 }); - const added = await addSubscription(ctx.db, { - guildId: interaction.guildId, - channelId, - projectId: project.id, - projectName: project.name, - createdBy: interaction.user.id, - }); - - ctx.log.info( - { - guildId: interaction.guildId, - channelId, - projectId: project.id, - actorId: interaction.user.id, - }, - 'Redmine subscription added', - ); - await respond( - interaction, - added - ? `<#${channelId}> now gets updates for ${project.name}. Everyone who can read the channel will see them.` - : 'That channel is already subscribed.', - ); - }; - - const handlers: Record = { - projects: async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const { projects, total } = await client.listProjects(); - const lines = projects.map((p) => `\`${p.identifier}\` ${p.name}`); - - await respond( - interaction, - [ - ...lines, - total > projects.length ? `…and ${total - projects.length} more` : '', - ].join('\n') || 'No projects.', - ); - }, - issues: async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const status = interaction.options.getString('status'); - const project = interaction.options.getString('project'); - const { issues, total } = await client.listIssues({ - ...(project === null ? {} : { projectId: project }), - assignedToMe: interaction.options.getBoolean('mine') ?? false, - status: status === 'closed' || status === '*' ? status : 'open', - limit: 15, - }); - const lines = issues.map((issue) => issueLine(baseUrl, issue)); - - await respond( - interaction, - lines.length === 0 - ? 'No issues.' - : `${lines.join('\n')}\n${issues.length} of ${total}`.slice(0, 2000), - ); - }, - 'issue view': async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const issue = await client.getIssue( - interaction.options.getInteger('issue', true), - ); - - await respond(interaction, { embeds: [issueEmbed(baseUrl, issue)] }); - }, - 'issue create': async (interaction, ctx) => { - const { client, redmineUserId } = await clientFor( - ctx, - interaction.user.id, - ); - const description = interaction.options.getString('description'); - const issue = await client.createIssue({ - project_id: interaction.options.getString('project', true), - subject: interaction.options.getString('subject', true), - ...(description === null ? {} : { description }), - ...(interaction.options.getBoolean('assign_to_me') === true - ? { assigned_to_id: redmineUserId } - : {}), - }); - - await respond(interaction, `Created ${issueLine(baseUrl, issue)}`); - }, - 'issue update': async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const status = interaction.options.getInteger('status'); - const notes = interaction.options.getString('notes'); - - if (status === null && notes === null) { - throw new UserError('Give a new status or notes.'); - } - - const id = interaction.options.getInteger('issue', true); - - await client.updateIssue(id, { - ...(status === null ? {} : { status_id: status }), - ...(notes === null ? {} : { notes }), - }); - await respond(interaction, `Updated #${id}.`); - }, - 'issue assign': async (interaction, ctx) => { - const { client, redmineUserId } = await clientFor( - ctx, - interaction.user.id, - ); - const member = interaction.options.getUser('member'); - let assignee = redmineUserId; - - if (member && member.id !== interaction.user.id) { - const link = await getLink(ctx.db, member.id); - - if (!link) { - throw new UserError( - `${member.username} has not linked a Redmine account.`, - ); - } - - assignee = link.redmineUserId; - } - - const id = interaction.options.getInteger('issue', true); - - await client.updateIssue(id, { assigned_to_id: assignee }); - await respond(interaction, `Assigned #${id}.`); - }, - 'issue comment': async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const id = interaction.options.getInteger('issue', true); - - await client.updateIssue(id, { - notes: interaction.options.getString('text', true), - }); - await respond(interaction, `Commented on #${id}.`); - }, - 'issue remind': async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const issue = await client.getIssue( - interaction.options.getInteger('issue', true), - ); - - if (issue.due_date === undefined || issue.due_date === null) { - throw new UserError(`#${issue.id} has no due date.`); - } - - const timezone = await getGuildTimezone( - ctx.db, - interaction.guildId, - ctx.config.DEFAULT_TIMEZONE, - ); - const due = parseCalendarDay(issue.due_date); - - if (!due) { - throw new UserError(`#${issue.id} has an unreadable due date.`); - } - - const daysBefore = interaction.options.getInteger('days_before') ?? 1; - const runAt = zonedTime(addCalendarDays(due, -daysBefore), 9, timezone); - - if (runAt.getTime() <= Date.now()) { - throw new UserError('That reminder time has already passed.'); - } - - const reminder = await reminders.schedule({ - guildId: interaction.guildId, - userId: interaction.user.id, - channelId: null, - message: `Redmine #${issue.id} "${issue.subject}" is due ${issue.due_date}: ${baseUrl}issues/${issue.id}`, - runAt, - recurrence: null, - timezone, - }); - - await respond( - interaction, - `I will DM you (reminder #${reminder.id}).`, - ); - }, - link: async (interaction) => { - const key = new TextInputBuilder() - .setCustomId('key') - .setStyle(TextInputStyle.Short) - .setMinLength(20) - .setMaxLength(100); - - await interaction.showModal( - new ModalBuilder() - .setCustomId('redmine:link') - .setTitle('Link Redmine') - .addLabelComponents( - new LabelBuilder() - .setLabel('API key') - .setDescription( - 'Redmine → My account → API access key. Stored encrypted.', - ) - .setTextInputComponent(key), - ), - ); - }, - unlink: async (interaction, ctx) => { - const removed = await deleteLink(ctx.db, interaction.user.id); - - ctx.log.info( - { userId: interaction.user.id, removed }, - 'Redmine account unlinked', - ); - await respond( - interaction, - removed ? 'Your Redmine key is deleted.' : 'You had no linked account.', - ); - }, - subscribe: subscription('subscribe'), - unsubscribe: subscription('unsubscribe'), - }; - - const linkModal: ComponentHandler = { - prefix: 'redmine:link', - execute: async (interaction, _args, ctx) => { - if (!interaction.isModalSubmit()) { - return; - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const apiKey = interaction.fields.getTextInputValue('key').trim(); - let user: RedmineUser; - - try { - user = await new RedmineClient(baseUrl, apiKey).currentUser(); - } catch (error) { - if (error instanceof RedmineError) { - throw new UserError( - error.kind === 'auth' - ? 'Redmine did not accept that API key.' - : error.message, - ); - } - - throw error; - } - - await saveLink(ctx.db, { - userId: interaction.user.id, - redmineUserId: user.id, - redmineLogin: user.login, - encryptedApiKey: box.encrypt(apiKey), - }); - ctx.log.info( - { userId: interaction.user.id, redmineUserId: user.id }, - 'Redmine account linked', - ); - await interaction.editReply(`Linked to Redmine user **${user.login}**.`); - }, - }; - - const command: SlashCommand = { - data: data.toJSON(), - permissions: { - 'issue create': 'redmine:issue:create', - 'issue update': 'redmine:issue:update', - 'issue comment': 'redmine:issue:update', - 'issue assign': 'redmine:issue:assign', - subscribe: 'redmine:subscription:manage', - unsubscribe: 'redmine:subscription:manage', - }, - execute: bySubcommand( - Object.fromEntries( - Object.entries(handlers).map(([path, handler]) => [ - path, - path === 'link' ? handler : deferred(withRedmineErrors(handler)), - ]), - ), - ), - autocomplete: async (interaction, ctx) => { - const { client } = await clientFor(ctx, interaction.user.id); - const statuses = await client.listStatuses(); - - await interaction.respond( - statuses.slice(0, 25).map((s) => ({ name: s.name, value: s.id })), - ); - }, - }; - - return { - name: 'redmine', - permissions: [ - { - id: 'redmine:issue:create', - description: 'Create Redmine issues (Redmine permissions still apply)', - }, - { - id: 'redmine:issue:update', - description: 'Update and comment on Redmine issues', - }, - { id: 'redmine:issue:assign', description: 'Assign Redmine issues' }, - { - id: 'redmine:subscription:manage', - description: 'Subscribe channels to Redmine projects', - }, - ], - commands: [command], - components: [linkModal], - jobs: notifications?.jobs ?? [], - ...(notifications && { start: notifications.start }), - }; -} diff --git a/src/features/redmine/notifications.ts b/src/features/redmine/notifications.ts deleted file mode 100644 index 8dfedb5..0000000 --- a/src/features/redmine/notifications.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { MessageFlags } from 'discord.js'; -import { z } from 'zod'; -import { defineJob } from '~/infra/discord'; -import { sequential } from '~/lib'; -import type { AppContext } from '~/infra/discord'; -import type { RedmineClient, RedmineStatus } from '~/infra/redmine'; -import { - addCalendarDays, - calendarDay, - formatCalendarDay, - nextDailyRun, -} from '~/domain'; -import type { RedmineSubscription } from './schema'; -import { - claimNotification, - issueNotifications, - listSubscriptions, - setCheckpoint, - type Notification, -} from './service'; - -const pollIntervalMs = 2 * 60 * 1000; -const issuesPerPoll = 25; -const deadlineHour = 9; - -export const pollKey = 'redmine:poll'; -export const deadlineKey = 'redmine:deadlines'; - -type Source = { - redmine: RedmineClient; - baseUrl: string; - statuses: ReadonlyMap; -}; - -async function forEachSubscription( - ctx: AppContext, - handle: (subscription: RedmineSubscription) => Promise, - afterId = 0, -): Promise { - const page = await listSubscriptions(ctx.db, afterId); - - await sequential(page, async (subscription) => { - try { - await handle(subscription); - } catch (error) { - ctx.log.warn( - { err: error, subscriptionId: subscription.id }, - 'Redmine subscription update failed', - ); - } - }); - - const last = page.at(-1); - - if (last !== undefined) { - await forEachSubscription(ctx, handle, last.id); - } -} - -async function sendOnce( - ctx: AppContext, - subscription: RedmineSubscription, - notification: Notification, -) { - if (!(await claimNotification(ctx.db, subscription.id, notification.key))) { - return; - } - - const channel = await ctx.client.channels.fetch(subscription.channelId); - - if (channel?.isSendable() === true) { - await channel.send({ - content: notification.text.slice(0, 2000), - allowedMentions: { parse: [] }, - flags: MessageFlags.SuppressEmbeds, - }); - } -} - -async function pollSubscription( - ctx: AppContext, - source: Source, - subscription: RedmineSubscription, -): Promise { - const { redmine, baseUrl, statuses } = source; - const { issues } = await redmine.listIssues({ - projectId: subscription.projectId, - status: '*', - updatedSince: subscription.checkpoint, - sort: 'updated_on:asc', - limit: issuesPerPoll, - }); - let checkpoint = subscription.checkpoint; - - await sequential(issues, async (summary) => { - const issue = await redmine.getIssue(summary.id, true); - const url = new URL(`issues/${issue.id}`, baseUrl).href; - const notifications = issueNotifications( - issue, - subscription.checkpoint, - statuses, - url, - ); - - await sequential(notifications, (notification) => - sendOnce(ctx, subscription, notification), - ); - - const updated = new Date(issue.updated_on); - - if (updated > checkpoint) { - checkpoint = updated; - } - }); - - if (checkpoint > subscription.checkpoint) { - await setCheckpoint(ctx.db, subscription.id, checkpoint); - } -} - -export function createNotificationJobs( - redmine: RedmineClient, - baseUrl: string, -) { - const root = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; - - const pollJob = defineJob({ - type: 'redmine:poll', - payload: z.object({}), - handle: async (_payload, _info, ctx) => { - const known = await redmine.listStatuses().catch(() => []); - const statuses = new Map(known.map((status) => [status.id, status])); - - await forEachSubscription(ctx, (subscription) => - pollSubscription( - ctx, - { redmine, baseUrl: root, statuses }, - subscription, - ), - ); - - return { rescheduleAt: new Date(Date.now() + pollIntervalMs) }; - }, - }); - - const deadlineJob = defineJob({ - type: 'redmine:deadlines', - payload: z.object({}), - handle: async (_payload, _info, ctx) => { - const zone = ctx.config.DEFAULT_TIMEZONE; - const tomorrow = formatCalendarDay( - addCalendarDays(calendarDay(new Date(), zone), 1), - ); - - await forEachSubscription(ctx, async (subscription) => { - const { issues } = await redmine.listIssues({ - projectId: subscription.projectId, - dueDate: tomorrow, - limit: 50, - }); - - const visible = issues.filter((issue) => issue.is_private !== true); - - await sequential(visible, (issue) => { - const url = new URL(`issues/${issue.id}`, root).href; - const text = [ - `⏳ Due tomorrow: [#${issue.id}](${url}) ${issue.subject}`, - issue.assigned_to?.name, - ] - .filter(Boolean) - .join(' · '); - - return sendOnce(ctx, subscription, { - key: `due:${issue.id}:${tomorrow}`, - text, - }); - }); - }); - - return { rescheduleAt: nextDailyRun(zone, deadlineHour) }; - }, - }); - - return { - jobs: [pollJob, deadlineJob], - start: async (ctx: AppContext) => { - await ctx.scheduler.schedule( - pollJob, - {}, - { runAt: new Date(Date.now() + 10_000), key: pollKey }, - ); - await ctx.scheduler.schedule( - deadlineJob, - {}, - { - runAt: nextDailyRun(ctx.config.DEFAULT_TIMEZONE, deadlineHour), - key: deadlineKey, - }, - ); - }, - }; -} diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index 6f82571..f6c1d43 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -18,3 +18,5 @@ export * from './movies/model'; export * from './movies/repo'; export * from './birthdays/model'; export * from './birthdays/repo'; +export * from './redmine/model'; +export * from './redmine/repo'; diff --git a/src/features/redmine/schema.ts b/src/infra/db/redmine/model.ts similarity index 100% rename from src/features/redmine/schema.ts rename to src/infra/db/redmine/model.ts diff --git a/src/features/redmine/service.ts b/src/infra/db/redmine/repo.ts similarity index 53% rename from src/features/redmine/service.ts rename to src/infra/db/redmine/repo.ts index c937cc9..2e2ab21 100644 --- a/src/features/redmine/service.ts +++ b/src/infra/db/redmine/repo.ts @@ -1,12 +1,12 @@ import { and, asc, eq, gt } from 'drizzle-orm'; -import type { Db } from '~/infra/db'; -import type { RedmineIssue, RedmineStatus } from '~/infra/redmine'; +import type { TrackerRepository } from '~/core/ports'; +import type { Db } from '../client'; import { redmineLinks, redmineNotifications, redmineSubscriptions, type RedmineLink, -} from './schema'; +} from './model'; export async function saveLink( db: Db, @@ -109,81 +109,17 @@ export async function claimNotification( return rows.length > 0; } -export type Notification = { key: string; text: string }; - -export function issueNotifications( - issue: RedmineIssue, - since: Date, - statuses: ReadonlyMap, - issueUrl: string, -): Notification[] { - if (issue.is_private === true) { - return []; - } - - const title = `[#${issue.id}](${issueUrl}) ${issue.subject}`; - const notifications: Notification[] = []; - - if (new Date(issue.created_on) >= since) { - const assignee = issue.assigned_to - ? `, assigned to ${issue.assigned_to.name}` - : ''; - - notifications.push({ - key: `issue:${issue.id}:created`, - text: `🆕 ${issue.tracker.name} ${title} by ${issue.author.name}${assignee}`, - }); - } - - for (const journal of issue.journals ?? []) { - if ( - new Date(journal.created_on) < since || - journal.private_notes === true - ) { - continue; - } - - const changes = journal.details.flatMap((detail) => { - if (detail.property !== 'attr') { - return []; - } - - if (detail.name === 'status_id') { - const name = (id: string | null | undefined) => - statuses.get(Number(id))?.name ?? '?'; - - return [`status ${name(detail.old_value)} → ${name(detail.new_value)}`]; - } - - if (detail.name === 'assigned_to_id') { - const matches = - issue.assigned_to && - String(issue.assigned_to.id) === detail.new_value; - - return [ - matches === true - ? `assigned to ${issue.assigned_to?.name ?? ''}` - : 'assignee changed', - ]; - } - - return []; - }); - const notes = journal.notes?.trim() ?? ''; - - if (changes.length === 0 && notes === '') { - continue; - } - - const who = journal.user?.name ?? 'Someone'; - const comment = - notes === '' ? '' : `\n> ${notes.slice(0, 300).replaceAll('\n', '\n> ')}`; - - notifications.push({ - key: `journal:${journal.id}`, - text: `✏️ ${title}: ${[who, ...changes].join(' · ')}${comment}`, - }); - } - - return notifications; +export function createTrackerRepository(db: Db): TrackerRepository { + return { + saveLink: (link) => saveLink(db, link), + link: (userId) => getLink(db, userId), + unlink: (userId) => deleteLink(db, userId), + subscribe: (subscription) => addSubscription(db, subscription), + unsubscribe: (guildId, channelId, projectId) => + removeSubscription(db, guildId, channelId, projectId), + subscriptions: (afterId, limit) => listSubscriptions(db, afterId, limit), + setCheckpoint: (id, checkpoint) => setCheckpoint(db, id, checkpoint), + claimNotification: (subscriptionId, key) => + claimNotification(db, subscriptionId, key), + }; } diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index 72659ae..d8da0f0 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -7,3 +7,4 @@ export * from './events'; export * from './polls'; export * from './movies'; export * from './birthdays'; +export * from './redmine'; diff --git a/src/infra/discord/commands/redmine.ts b/src/infra/discord/commands/redmine.ts new file mode 100644 index 0000000..fdac713 --- /dev/null +++ b/src/infra/discord/commands/redmine.ts @@ -0,0 +1,436 @@ +import { + ChannelType, + EmbedBuilder, + InteractionContextType, + LabelBuilder, + MessageFlags, + ModalBuilder, + SlashCommandBuilder, + TextInputBuilder, + TextInputStyle, + type SlashCommandIntegerOption, +} from 'discord.js'; +import type { RedmineService } from '~/core/services'; +import { channelMention, discordTime, type Issue } from '~/domain'; +import { toActor } from '../actor'; +import { bySubcommand, deferred } from '../define'; +import type { + ComponentHandler, + CommandInteraction, + Feature, + SlashCommand, +} from '../module'; +import { respond } from '../router'; + +const issueOption = (o: SlashCommandIntegerOption) => + o + .setName('issue') + .setDescription('Issue number') + .setRequired(true) + .setMinValue(1); + +const data = new SlashCommandBuilder() + .setName('redmine') + .setDescription('Redmine projects and issues') + .setContexts(InteractionContextType.Guild) + .addSubcommand((sub) => + sub.setName('projects').setDescription('Projects you can see'), + ) + .addSubcommand((sub) => + sub + .setName('issues') + .setDescription('List issues') + .addStringOption((o) => + o.setName('project').setDescription('Project identifier'), + ) + .addBooleanOption((o) => + o.setName('mine').setDescription('Only issues assigned to me'), + ) + .addStringOption((o) => + o + .setName('status') + .setDescription('Status filter') + .addChoices( + { name: 'open', value: 'open' }, + { name: 'closed', value: 'closed' }, + { name: 'all', value: '*' }, + ), + ), + ) + .addSubcommandGroup((group) => + group + .setName('issue') + .setDescription('A single issue') + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('Show an issue') + .addIntegerOption(issueOption), + ) + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Create an issue') + .addStringOption((o) => + o + .setName('project') + .setDescription('Project identifier') + .setRequired(true), + ) + .addStringOption((o) => + o + .setName('subject') + .setDescription('Subject') + .setRequired(true) + .setMaxLength(255), + ) + .addStringOption((o) => + o + .setName('description') + .setDescription('Description') + .setMaxLength(4000), + ) + .addBooleanOption((o) => + o.setName('assign_to_me').setDescription('Assign it to me'), + ), + ) + .addSubcommand((sub) => + sub + .setName('update') + .setDescription('Change status or add notes') + .addIntegerOption(issueOption) + .addIntegerOption((o) => + o + .setName('status') + .setDescription('New status') + .setAutocomplete(true), + ) + .addStringOption((o) => + o.setName('notes').setDescription('Notes').setMaxLength(4000), + ), + ) + .addSubcommand((sub) => + sub + .setName('assign') + .setDescription('Assign an issue') + .addIntegerOption(issueOption) + .addUserOption((o) => + o.setName('member').setDescription('Linked member (default: you)'), + ), + ) + .addSubcommand((sub) => + sub + .setName('comment') + .setDescription('Comment on an issue') + .addIntegerOption(issueOption) + .addStringOption((o) => + o + .setName('text') + .setDescription('Comment') + .setRequired(true) + .setMaxLength(4000), + ), + ) + .addSubcommand((sub) => + sub + .setName('remind') + .setDescription('DM me before the due date') + .addIntegerOption(issueOption) + .addIntegerOption((o) => + o + .setName('days_before') + .setDescription('Days before (default 1)') + .setMinValue(0) + .setMaxValue(30), + ), + ), + ) + .addSubcommand((sub) => + sub + .setName('link') + .setDescription('Link your Redmine account with your API key'), + ) + .addSubcommand((sub) => + sub.setName('unlink').setDescription('Remove your stored Redmine key'), + ) + .addSubcommand((sub) => + sub + .setName('subscribe') + .setDescription('Post project updates in a channel') + .addStringOption((o) => + o + .setName('project') + .setDescription('Project identifier') + .setRequired(true), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Channel (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ) + .addSubcommand((sub) => + sub + .setName('unsubscribe') + .setDescription('Stop project updates in a channel') + .addStringOption((o) => + o + .setName('project') + .setDescription('Project identifier') + .setRequired(true), + ) + .addChannelOption((o) => + o + .setName('channel') + .setDescription('Channel (default: here)') + .addChannelTypes(ChannelType.GuildText), + ), + ); + +function issueLine(baseUrl: string, issue: Issue): string { + const assignee = issue.assigned_to ? ` · ${issue.assigned_to.name}` : ''; + + return `[#${issue.id}](<${baseUrl}issues/${issue.id}>) **${issue.subject}** — ${issue.status.name}${assignee}`; +} + +function issueEmbed(baseUrl: string, issue: Issue): EmbedBuilder { + return new EmbedBuilder() + .setTitle(`#${issue.id} ${issue.subject}`.slice(0, 256)) + .setURL(`${baseUrl}issues/${issue.id}`) + .setDescription((issue.description ?? '').slice(0, 1500) || null) + .addFields( + { name: 'Project', value: issue.project.name, inline: true }, + { name: 'Status', value: issue.status.name, inline: true }, + { name: 'Priority', value: issue.priority.name, inline: true }, + { name: 'Assignee', value: issue.assigned_to?.name ?? '—', inline: true }, + { name: 'Due', value: issue.due_date ?? '—', inline: true }, + ); +} + +type Handler = (interaction: CommandInteraction) => Promise; + +export function redmineCommands( + redmine: RedmineService, + baseUrl: string, +): Feature { + const root = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; + const actorOf = (interaction: CommandInteraction) => + toActor(interaction.member); + const channelOf = (interaction: CommandInteraction) => + interaction.options.getChannel('channel')?.id ?? interaction.channelId; + + const handlers: Record = { + projects: async (interaction) => { + const { projects, total } = await redmine.projects(actorOf(interaction)); + const lines = projects.map((p) => `"${p.identifier}" ${p.name}`); + const more = + total > projects.length ? [`…and ${total - projects.length} more`] : []; + + await respond( + interaction, + [...lines, ...more].join('\n') || 'No projects.', + ); + }, + issues: async (interaction) => { + const status = interaction.options.getString('status'); + const project = interaction.options.getString('project'); + const { issues, total } = await redmine.issues(actorOf(interaction), { + ...(project !== null && { projectId: project }), + assignedToMe: interaction.options.getBoolean('mine') ?? false, + status: status === 'closed' || status === '*' ? status : 'open', + }); + const lines = issues.map((issue) => issueLine(root, issue)); + + await respond( + interaction, + lines.length === 0 + ? 'No issues.' + : `${lines.join('\n')}\n${issues.length} of ${total}`.slice(0, 2000), + ); + }, + 'issue view': async (interaction) => { + const issue = await redmine.issue( + actorOf(interaction), + interaction.options.getInteger('issue', true), + ); + + await respond(interaction, { embeds: [issueEmbed(root, issue)] }); + }, + 'issue create': async (interaction) => { + const description = interaction.options.getString('description'); + const issue = await redmine.createIssue(actorOf(interaction), { + project: interaction.options.getString('project', true), + subject: interaction.options.getString('subject', true), + ...(description !== null && { description }), + assignToMe: interaction.options.getBoolean('assign_to_me') ?? false, + }); + + await respond(interaction, `Created ${issueLine(root, issue)}`); + }, + 'issue update': async (interaction) => { + const statusId = interaction.options.getInteger('status'); + const notes = interaction.options.getString('notes'); + const id = interaction.options.getInteger('issue', true); + + await redmine.updateIssue(actorOf(interaction), id, { + ...(statusId !== null && { statusId }), + ...(notes !== null && { notes }), + }); + await respond(interaction, `Updated #${id}.`); + }, + 'issue assign': async (interaction) => { + const id = interaction.options.getInteger('issue', true); + const member = interaction.options.getUser('member'); + + await redmine.assign( + actorOf(interaction), + id, + ...(member ? [member.id] : []), + ); + await respond(interaction, `Assigned #${id}.`); + }, + 'issue comment': async (interaction) => { + const id = interaction.options.getInteger('issue', true); + + await redmine.comment( + actorOf(interaction), + id, + interaction.options.getString('text', true), + ); + await respond(interaction, `Commented on #${id}.`); + }, + 'issue remind': async (interaction) => { + const reminder = await redmine.remind( + actorOf(interaction), + interaction.options.getInteger('issue', true), + interaction.options.getInteger('days_before') ?? 1, + ); + + await respond( + interaction, + `I will DM you ${discordTime(reminder.runAt, 'R')} (reminder #${reminder.id}).`, + ); + }, + unlink: async (interaction) => { + const removed = await redmine.unlink(actorOf(interaction)); + + await respond( + interaction, + removed ? 'Your Redmine key is deleted.' : 'You had no linked account.', + ); + }, + subscribe: async (interaction) => { + const channelId = channelOf(interaction); + const { project, added } = await redmine.subscribe( + actorOf(interaction), + channelId, + interaction.options.getString('project', true), + ); + + await respond( + interaction, + added + ? `${channelMention(channelId)} now gets updates for ${project.name}. Everyone who can read the channel will see them.` + : 'That channel is already subscribed.', + ); + }, + unsubscribe: async (interaction) => { + const channelId = channelOf(interaction); + const { project, removed } = await redmine.unsubscribe( + actorOf(interaction), + channelId, + interaction.options.getString('project', true), + ); + + await respond( + interaction, + removed + ? `Unsubscribed ${channelMention(channelId)} from ${project.name}.` + : 'No such subscription.', + ); + }, + }; + + const link: Handler = async (interaction) => { + const key = new TextInputBuilder() + .setCustomId('key') + .setStyle(TextInputStyle.Short) + .setMinLength(20) + .setMaxLength(100); + + await interaction.showModal( + new ModalBuilder() + .setCustomId('redmine:link') + .setTitle('Link Redmine') + .addLabelComponents( + new LabelBuilder() + .setLabel('API key') + .setDescription( + 'Redmine → My account → API access key. Stored encrypted.', + ) + .setTextInputComponent(key), + ), + ); + }; + + const linkModal: ComponentHandler = { + prefix: 'redmine:link', + execute: async (interaction) => { + if (!interaction.isModalSubmit()) { + return; + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + + const user = await redmine.link( + toActor(interaction.member), + interaction.fields.getTextInputValue('key'), + ); + + await respond(interaction, `Linked to Redmine user **${user.login}**.`); + }, + }; + + const command: SlashCommand = { + data: data.toJSON(), + execute: bySubcommand({ + link, + ...Object.fromEntries( + Object.entries(handlers).map(([path, handler]) => [ + path, + deferred(handler), + ]), + ), + }), + autocomplete: async (interaction) => { + const statuses = await redmine.statuses(toActor(interaction.member)); + + await interaction.respond( + statuses.slice(0, 25).map((s) => ({ name: s.name, value: s.id })), + ); + }, + }; + + return { + name: 'redmine', + permissions: [ + { + id: 'redmine:issue:create', + description: 'Create Redmine issues (Redmine permissions still apply)', + }, + { + id: 'redmine:issue:update', + description: 'Update and comment on Redmine issues', + }, + { id: 'redmine:issue:assign', description: 'Assign Redmine issues' }, + { + id: 'redmine:subscription:manage', + description: 'Subscribe channels to Redmine projects', + }, + ], + commands: [command], + components: [linkModal], + start: () => redmine.start(), + }; +} diff --git a/src/infra/redmine/client.ts b/src/infra/redmine/client.ts index 51815f5..27ff41f 100644 --- a/src/infra/redmine/client.ts +++ b/src/infra/redmine/client.ts @@ -1,34 +1,45 @@ import { z } from 'zod'; +import type { IssueTracker } from '~/core/ports'; +import { + IntegrationError, + type IntegrationErrorKind, + type Issue, + type IssueChanges, + type IssueQuery, + type IssueStatus, + type TrackerProject, + type TrackerUser, +} from '~/domain'; const named = z.object({ id: z.number(), name: z.string() }); const userSchema = z.object({ id: z.number(), login: z.string(), - firstname: z.string().optional(), - lastname: z.string().optional(), + firstname: z.string().exactOptional(), + lastname: z.string().exactOptional(), }); const projectSchema = z.object({ id: z.number(), name: z.string(), identifier: z.string(), - description: z.string().nullish(), + description: z.string().nullable().exactOptional(), }); const journalSchema = z.object({ id: z.number(), - user: named.optional(), - notes: z.string().nullish(), - private_notes: z.boolean().optional(), + user: named.exactOptional(), + notes: z.string().nullable().exactOptional(), + private_notes: z.boolean().exactOptional(), created_on: z.string(), details: z .array( z.object({ property: z.string(), name: z.string(), - old_value: z.string().nullish(), - new_value: z.string().nullish(), + old_value: z.string().nullable().exactOptional(), + new_value: z.string().nullable().exactOptional(), }), ) .default([]), @@ -38,85 +49,42 @@ const issueSchema = z.object({ id: z.number(), project: named, tracker: named, - status: named.extend({ is_closed: z.boolean().optional() }), + status: named.extend({ is_closed: z.boolean().exactOptional() }), priority: named, author: named, - assigned_to: named.optional(), + assigned_to: named.exactOptional(), subject: z.string(), - description: z.string().nullish(), - due_date: z.string().nullish(), - done_ratio: z.number().optional(), - is_private: z.boolean().optional(), + description: z.string().nullable().exactOptional(), + due_date: z.string().nullable().exactOptional(), + done_ratio: z.number().exactOptional(), + is_private: z.boolean().exactOptional(), created_on: z.string(), updated_on: z.string(), - journals: z.array(journalSchema).optional(), + journals: z.array(journalSchema).exactOptional(), }); const statusSchema = z.object({ id: z.number(), name: z.string(), - is_closed: z.boolean().optional(), + is_closed: z.boolean().exactOptional(), }); const projectsPage = z.object({ projects: z.array(projectSchema), - total_count: z.number().optional(), + total_count: z.number().exactOptional(), }); const issuesPage = z.object({ issues: z.array(issueSchema), - total_count: z.number().optional(), + total_count: z.number().exactOptional(), }); -export type RedmineUser = z.infer; -export type RedmineProject = z.infer; -export type RedmineIssue = z.infer; -export type RedmineJournal = z.infer; -export type RedmineStatus = z.infer; - -export type RedmineErrorKind = - | 'auth' - | 'forbidden' - | 'not_found' - | 'validation' - | 'unavailable' - | 'invalid_response'; - -export class RedmineError extends Error { - override readonly name = 'RedmineError'; - constructor( - readonly kind: RedmineErrorKind, - message: string, - ) { - super(message); - } -} - -export type IssueQuery = { - projectId?: number | string; - assignedToMe?: boolean; - status?: 'open' | 'closed' | '*'; - updatedSince?: Date; - dueDate?: string; - sort?: string; - offset?: number; - limit?: number; -}; - -export type IssueChanges = { - subject?: string; - description?: string; - status_id?: number; - assigned_to_id?: number; - notes?: string; -}; - type Request = { method?: 'GET' | 'POST' | 'PUT'; body?: unknown; query?: Record; }; -const messages: Record = { +const messages: Record = { 401: [ 'auth', 'Redmine rejected the API key. Link your account again with `/redmine link`.', @@ -127,7 +95,7 @@ const messages: Record = { const redmineTime = (date: Date) => `${date.toISOString().slice(0, 19)}Z`; -export class RedmineClient { +export class RedmineClient implements IssueTracker { constructor( private readonly baseUrl: string, private readonly apiKey: string, @@ -151,7 +119,7 @@ export class RedmineClient { } catch (error) { const retryable = method === 'GET' && - error instanceof RedmineError && + error instanceof IntegrationError && error.kind === 'unavailable'; if (!retryable) { @@ -181,7 +149,10 @@ export class RedmineClient { signal: AbortSignal.timeout(this.options.timeoutMs ?? 10_000), }); } catch { - throw new RedmineError('unavailable', 'Redmine did not respond in time.'); + throw new IntegrationError( + 'unavailable', + 'Redmine did not respond in time.', + ); } if (response.status === 422) { @@ -189,7 +160,7 @@ export class RedmineClient { .object({ errors: z.array(z.string()) }) .safeParse(await response.json().catch(() => null)); - throw new RedmineError( + throw new IntegrationError( 'validation', parsed.success ? parsed.data.errors.join('; ') @@ -200,11 +171,11 @@ export class RedmineClient { const known = messages[response.status]; if (known) { - throw new RedmineError(...known); + throw new IntegrationError(...known); } if (!response.ok) { - throw new RedmineError( + throw new IntegrationError( 'unavailable', `Redmine is unavailable (HTTP ${response.status}).`, ); @@ -225,7 +196,7 @@ export class RedmineClient { ); if (!parsed.success) { - throw new RedmineError( + throw new IntegrationError( 'invalid_response', 'Redmine sent a response I do not understand.', ); @@ -234,7 +205,7 @@ export class RedmineClient { return parsed.data; } - async currentUser(): Promise { + async currentUser(): Promise { const data = await this.get( 'users/current.json', z.object({ user: userSchema }), @@ -246,7 +217,7 @@ export class RedmineClient { async listProjects( offset = 0, limit = 25, - ): Promise<{ projects: RedmineProject[]; total: number }> { + ): Promise<{ projects: TrackerProject[]; total: number }> { const data = await this.get('projects.json', projectsPage, { offset: String(offset), limit: String(Math.min(limit, 100)), @@ -260,7 +231,7 @@ export class RedmineClient { async listIssues( query: IssueQuery = {}, - ): Promise<{ issues: RedmineIssue[]; total: number }> { + ): Promise<{ issues: Issue[]; total: number }> { const params: Record = { status_id: query.status ?? 'open', sort: query.sort ?? 'updated_on:desc', @@ -292,7 +263,7 @@ export class RedmineClient { }; } - async getIssue(id: number, withJournals = false): Promise { + async getIssue(id: number, withJournals = false): Promise { const query = withJournals ? { include: 'journals' } : undefined; const data = await this.get( `issues/${id}.json`, @@ -303,7 +274,7 @@ export class RedmineClient { return data.issue; } - async listStatuses(): Promise { + async listStatuses(): Promise { const data = await this.get( 'issue_statuses.json', z.object({ issue_statuses: z.array(statusSchema) }), @@ -314,7 +285,7 @@ export class RedmineClient { async createIssue( fields: IssueChanges & { project_id: number | string; subject: string }, - ): Promise { + ): Promise { const data = await this.request('issues.json', { method: 'POST', body: { issue: fields }, @@ -322,7 +293,7 @@ export class RedmineClient { const parsed = z.object({ issue: issueSchema }).safeParse(data); if (!parsed.success) { - throw new RedmineError( + throw new IntegrationError( 'invalid_response', 'Redmine created the issue but sent an unexpected response.', ); diff --git a/tests/core/services/redmine.test.ts b/tests/core/services/redmine.test.ts new file mode 100644 index 0000000..994595d --- /dev/null +++ b/tests/core/services/redmine.test.ts @@ -0,0 +1,141 @@ +import { randomBytes } from 'node:crypto'; +import { describe, expect, it, vi } from 'vitest'; +import type { IssueTracker, Scheduler } from '~/core/ports'; +import { createRedmineService, type ReminderService } from '~/core/services'; +import { IntegrationError, UserError, type Issue } from '~/domain'; +import { createSecretBox } from '~/infra/crypto'; +import { createTrackerRepository } from '~/infra/db'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { actor, allowAll, fakeMessenger, silentLog } from '../../fakes'; + +const since = new Date('2026-11-10T00:00:00Z'); +const issue: Issue = { + id: 42, + project: { id: 1, name: 'Web' }, + tracker: { id: 1, name: 'Bug' }, + status: { id: 2, name: 'In Progress' }, + priority: { id: 2, name: 'Normal' }, + author: { id: 3, name: 'Mari' }, + subject: 'Fix login', + created_on: '2026-11-11T10:00:00Z', + updated_on: '2026-11-12T10:00:00Z', + journals: [ + { id: 7, notes: 'hi', created_on: '2026-11-12T10:00:00Z', details: [] }, + ], +}; + +function tracker(overrides: Partial = {}): IssueTracker { + return { + currentUser: vi.fn(async () => ({ id: 5, login: 'mari' })), + listProjects: vi.fn(async () => ({ + projects: [{ id: 1, name: 'Web', identifier: 'web' }], + total: 1, + })), + listIssues: vi.fn(async () => ({ issues: [issue], total: 1 })), + getIssue: vi.fn(async () => issue), + listStatuses: vi.fn(async () => []), + createIssue: vi.fn(async () => issue), + updateIssue: vi.fn(async () => undefined), + ...overrides, + }; +} + +describe.skipIf(noDatabase)('redmine service', () => { + const setup = (client = tracker()) => { + const { messenger } = fakeMessenger(); + const connect = vi.fn(() => client); + const service = createRedmineService({ + baseUrl: 'https://r', + connect, + service: client, + tracker: createTrackerRepository(testDb()), + secrets: createSecretBox(randomBytes(32).toString('base64')), + reminders: {} as ReminderService, + scheduler: { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }, + messenger, + authz: allowAll, + log: silentLog, + defaultTimezone: 'Europe/Tallinn', + timezone: async () => 'Europe/Tallinn', + }); + + return { service, messenger, connect, client }; + }; + + it('requires a linked account and uses that key for user actions', async () => { + const { service, connect } = setup(); + const member = actor({ guildId: snowflake(), userId: snowflake() }); + + await expect(service.projects(member)).rejects.toThrow( + 'Link your Redmine account', + ); + await service.link(member, 'k'.repeat(40)); + await service.projects(member); + expect(connect).toHaveBeenLastCalledWith('k'.repeat(40)); + }); + + it('turns tracker failures into user-facing errors', async () => { + const failing = tracker({ + listProjects: vi.fn(async () => + { throw new IntegrationError('forbidden', 'Not allowed.'); }, + ), + }); + const { service } = setup(failing); + const member = actor({ guildId: snowflake(), userId: snowflake() }); + + await service.link(member, 'k'.repeat(40)); + await expect(service.projects(member)).rejects.toThrow(UserError); + }); + + it('notifies once per change and advances the checkpoint', async () => { + const { service, messenger } = setup(); + const repository = createTrackerRepository(testDb()); + const channelId = snowflake(); + + await repository.subscribe({ + guildId: snowflake(), + channelId, + projectId: 1, + projectName: 'Web', + createdBy: 'u', + }); + + const subscription = (await repository.subscriptions(0, 1000)).find( + (s) => s.channelId === channelId, + ); + + await repository.setCheckpoint(subscription?.id ?? 0, since); + + const [poll] = service.jobs; + const info = { id: 1, runAt: new Date(), attempt: 1 }; + const outcome = await poll?.run({}, info); + + await poll?.run({}, info); + + const ours = messenger.send.mock.calls.filter(([id]) => id === channelId); + + expect(ours).toHaveLength(2); + expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); + + const updated = (await repository.subscriptions(0, 1000)).find( + (s) => s.channelId === channelId, + ); + + expect(updated?.checkpoint.toISOString()).toBe('2026-11-12T10:00:00.000Z'); + }); + + it('keeps going when one subscription fails', async () => { + const { service } = setup( + tracker({ + listIssues: vi.fn(async () => { throw new Error('boom'); }), + }), + ); + + await expect( + service.jobs[0]?.run({}, { id: 1, runAt: new Date(), attempt: 1 }), + ).resolves.toBeDefined(); + }); +}); diff --git a/tests/domain/issue.test.ts b/tests/domain/issue.test.ts new file mode 100644 index 0000000..2b2d1a7 --- /dev/null +++ b/tests/domain/issue.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { issueNotifications, type Issue } from '~/domain'; + +const since = new Date('2026-11-10T00:00:00Z'); +const statuses = new Map([ + [1, { id: 1, name: 'New' }], + [2, { id: 2, name: 'In Progress' }], +]); +const issue = (overrides: Partial = {}): Issue => ({ + id: 42, + project: { id: 1, name: 'Web' }, + tracker: { id: 1, name: 'Bug' }, + status: { id: 2, name: 'In Progress' }, + priority: { id: 2, name: 'Normal' }, + author: { id: 3, name: 'Mari' }, + assigned_to: { id: 5, name: 'Jaan' }, + subject: 'Fix login', + created_on: '2026-11-11T10:00:00Z', + updated_on: '2026-11-12T10:00:00Z', + journals: [], + ...overrides, +}); +const journal = (id: number, overrides: object) => ({ + id, + user: { id: 3, name: 'Mari' }, + created_on: '2026-11-12T10:00:00Z', + details: [], + ...overrides, +}); + +describe('issueNotifications', () => { + it('reports new issues, status changes, assignments and comments', () => { + const notifications = issueNotifications( + issue({ + journals: [ + journal(1, { + details: [ + { + property: 'attr', + name: 'status_id', + old_value: '1', + new_value: '2', + }, + ], + }), + journal(2, { + details: [ + { + property: 'attr', + name: 'assigned_to_id', + old_value: null, + new_value: '5', + }, + ], + }), + journal(3, { notes: 'Looks good' }), + journal(4, { created_on: '2026-11-01T00:00:00Z', notes: 'old' }), + ], + }), + since, + statuses, + 'https://r/issues/42', + ); + + expect(notifications.map((n) => n.key)).toEqual([ + 'issue:42:created', + 'journal:1', + 'journal:2', + 'journal:3', + ]); + expect(notifications[1]?.text).toContain('status New → In Progress'); + expect(notifications[2]?.text).toContain('assigned to Jaan'); + expect(notifications[3]?.text).toContain('> Looks good'); + }); + + it('never reveals private issues or private notes', () => { + expect( + issueNotifications(issue({ is_private: true }), since, statuses, 'u'), + ).toEqual([]); + const notes = issueNotifications( + issue({ + created_on: '2026-01-01T00:00:00Z', + journals: [journal(9, { notes: 'secret', private_notes: true })], + }), + since, + statuses, + 'u', + ); + + expect(notes).toEqual([]); + }); +}); diff --git a/tests/features/redmine/redmine.test.ts b/tests/features/redmine/redmine.test.ts deleted file mode 100644 index 8460588..0000000 --- a/tests/features/redmine/redmine.test.ts +++ /dev/null @@ -1,198 +0,0 @@ -import type { ReminderService } from '~/core/services'; -import { randomBytes } from 'node:crypto'; -import { pino } from 'pino'; -import { describe, expect, it, vi } from 'vitest'; -import { noDatabase, snowflake, testDb } from '../../db'; -import type { Config } from '~/config'; -import type { AppContext } from '~/infra/discord'; -import type { RedmineClient, RedmineIssue } from '~/infra/redmine'; -import { createRedmineFeature } from '~/features/redmine'; -import { createNotificationJobs } from '~/features/redmine/notifications'; -import { - addSubscription, - issueNotifications, - listSubscriptions, -} from '~/features/redmine/service'; - -const since = new Date('2026-11-10T00:00:00Z'); -const statuses = new Map([ - [1, { id: 1, name: 'New' }], - [2, { id: 2, name: 'In Progress' }], -]); -const issue = (overrides: Partial = {}): RedmineIssue => ({ - id: 42, - project: { id: 1, name: 'Web' }, - tracker: { id: 1, name: 'Bug' }, - status: { id: 2, name: 'In Progress' }, - priority: { id: 2, name: 'Normal' }, - author: { id: 3, name: 'Mari' }, - assigned_to: { id: 5, name: 'Jaan' }, - subject: 'Fix login', - created_on: '2026-11-11T10:00:00Z', - updated_on: '2026-11-12T10:00:00Z', - journals: [], - ...overrides, -}); -const journal = (id: number, overrides: object) => ({ - id, - user: { id: 3, name: 'Mari' }, - created_on: '2026-11-12T10:00:00Z', - details: [], - ...overrides, -}); - -describe('issueNotifications', () => { - it('reports new issues, status changes, assignments and comments', () => { - const notifications = issueNotifications( - issue({ - journals: [ - journal(1, { - details: [ - { - property: 'attr', - name: 'status_id', - old_value: '1', - new_value: '2', - }, - ], - }), - journal(2, { - details: [ - { - property: 'attr', - name: 'assigned_to_id', - old_value: null, - new_value: '5', - }, - ], - }), - journal(3, { notes: 'Looks good' }), - journal(4, { created_on: '2026-11-01T00:00:00Z', notes: 'old' }), - ], - }), - since, - statuses, - 'https://r/issues/42', - ); - - expect(notifications.map((n) => n.key)).toEqual([ - 'issue:42:created', - 'journal:1', - 'journal:2', - 'journal:3', - ]); - expect(notifications[1]?.text).toContain('status New → In Progress'); - expect(notifications[2]?.text).toContain('assigned to Jaan'); - expect(notifications[3]?.text).toContain('> Looks good'); - }); - - it('never reveals private issues or private notes', () => { - expect( - issueNotifications(issue({ is_private: true }), since, statuses, 'u'), - ).toEqual([]); - const notes = issueNotifications( - issue({ - created_on: '2026-01-01T00:00:00Z', - journals: [journal(9, { notes: 'secret', private_notes: true })], - }), - since, - statuses, - 'u', - ); - - expect(notes).toEqual([]); - }); -}); - -describe('createRedmineFeature', () => { - it('is disabled without a base URL and requires an encryption key with one', () => { - expect( - createRedmineFeature({} as Config, {} as ReminderService), - ).toBeUndefined(); - expect(() => - createRedmineFeature( - { REDMINE_BASE_URL: 'https://r' } as Config, - {} as ReminderService, - ), - ).toThrow('CREDENTIAL_ENCRYPTION_KEY'); - const feature = createRedmineFeature( - { - REDMINE_BASE_URL: 'https://r', - CREDENTIAL_ENCRYPTION_KEY: randomBytes(32).toString('base64'), - } as Config, - {} as ReminderService, - ); - - expect(feature?.jobs).toEqual([]); - }); -}); - -describe.skipIf(noDatabase)('redmine polling', () => { - it('notifies once per change and advances the checkpoint', async () => { - const db = testDb(); - const channelId = snowflake(); - - await addSubscription(db, { - guildId: snowflake(), - channelId, - projectId: 1, - projectName: 'Web', - createdBy: 'u', - checkpoint: since, - }); - const full = issue({ journals: [journal(7, { notes: 'hi' })] }); - const redmine = { - listStatuses: vi.fn(async () => [...statuses.values()]), - listIssues: vi.fn(async () => ({ issues: [full], total: 1 })), - getIssue: vi.fn(async () => full), - } as unknown as RedmineClient; - const send = vi.fn(async () => undefined); - const ctx = { - db, - log: pino({ level: 'silent' }), - client: { - channels: { - fetch: async (id: string) => - id === channelId ? { isSendable: () => true, send } : null, - }, - }, - } as unknown as AppContext; - const [poll] = createNotificationJobs(redmine, 'https://r/').jobs; - const info = { id: 1, runAt: new Date(), attempt: 1 }; - - const outcome = await poll?.run({}, info, ctx); - - await poll?.run({}, info, ctx); - const ours = send.mock.calls.length; - - expect(ours).toBe(2); - expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); - const subscriptions = await listSubscriptions(db, 0, 1000); - - expect( - subscriptions - .find((s) => s.channelId === channelId) - ?.checkpoint.toISOString(), - ).toBe(full.updated_on.replace('Z', '.000Z')); - }); - - it('keeps going when one subscription fails', async () => { - const db = testDb(); - const redmine = { - listStatuses: vi.fn(async () => []), - listIssues: vi.fn(async () => { - throw new Error('boom'); - }), - } as unknown as RedmineClient; - const ctx = { - db, - log: pino({ level: 'silent' }), - client: { channels: { fetch: vi.fn() } }, - } as unknown as AppContext; - const [poll] = createNotificationJobs(redmine, 'https://r/').jobs; - - await expect( - poll?.run({}, { id: 1, runAt: new Date(), attempt: 1 }, ctx), - ).resolves.toBeDefined(); - }); -}); diff --git a/tests/infra/redmine/client.test.ts b/tests/infra/redmine/client.test.ts index 44cb650..6a73014 100644 --- a/tests/infra/redmine/client.test.ts +++ b/tests/infra/redmine/client.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; -import { RedmineClient, RedmineError } from '~/infra/redmine'; +import { IntegrationError } from '~/domain'; +import { RedmineClient } from '~/infra/redmine'; const issue = { id: 7, @@ -37,7 +38,7 @@ const kind = async (promise: Promise) => { try { await promise; } catch (error) { - return error instanceof RedmineError ? error.kind : 'other'; + return error instanceof IntegrationError ? error.kind : 'other'; } return 'none'; From 051526e095773726a3e4fb0efdf9ff351ff4d912 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 21:32:36 +0200 Subject: [PATCH 030/199] refactor: drop the transitional AppContext; run core jobs without Discord context --- eslint.config.ts | 2 +- src/app.ts | 24 +++------ src/infra/db/settings/repo.ts | 13 ----- src/infra/discord/define.ts | 30 ----------- src/infra/discord/errors.ts | 7 --- src/infra/discord/module.ts | 42 +-------------- src/infra/discord/registry.ts | 22 +------- src/infra/scheduler/index.ts | 2 +- .../scheduler/{scheduler.ts => runner.ts} | 53 ++++++++----------- tests/core/services/redmine.test.ts | 10 ++-- tests/infra/discord/registry.test.ts | 15 ++---- .../{scheduler.test.ts => runner.test.ts} | 53 ++++++++++--------- 12 files changed, 72 insertions(+), 201 deletions(-) rename src/infra/scheduler/{scheduler.ts => runner.ts} (65%) rename tests/infra/scheduler/{scheduler.test.ts => runner.test.ts} (82%) diff --git a/eslint.config.ts b/eslint.config.ts index a8c343f..6eefa88 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -410,7 +410,7 @@ export default defineConfig( }, { - files: ['src/lib/async.ts', 'src/infra/scheduler/scheduler.ts'], + files: ['src/lib/async.ts', 'src/infra/scheduler/runner.ts'], rules: { 'no-await-in-loop': 'off' }, }, diff --git a/src/app.ts b/src/app.ts index 98485f4..fc70037 100644 --- a/src/app.ts +++ b/src/app.ts @@ -34,7 +34,7 @@ import { } from '~/core/services'; import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; -import { createJobQueue, createScheduler } from '~/infra/scheduler'; +import { createJobQueue, createJobRunner } from '~/infra/scheduler'; import { systemClock, type Job } from '~/core/ports'; import { connectDatabase, @@ -222,7 +222,7 @@ export function compose(config: Config, log: Logger) { const registry = buildRegistry(features); - const runnerJobs = new Map(registry.jobs); + const runnerJobs = new Map>(); for (const job of jobs) { if (runnerJobs.has(job.type)) { @@ -254,20 +254,13 @@ export async function startApp( try { await runMigrations(database.db); - const scheduler = createScheduler( + const runner = createJobRunner( database.db, jobs, log.child({ component: 'scheduler' }), ); const ready = await waitForReady(client, config.DISCORD_TOKEN); - const ctx: AppContext = { - client: ready, - db: database.db, - log, - config, - authz, - scheduler, - }; + const ctx: AppContext = { log, authz }; for (const feature of registry.features) { for (const listener of feature.events ?? []) { @@ -292,10 +285,7 @@ export async function startApp( await Promise.all( registry.features.map(async (feature) => { try { - await feature.start?.({ - ...ctx, - log: log.child({ feature: feature.name }), - }); + await feature.start?.(); } catch (error) { log.error( { err: error, feature: feature.name }, @@ -304,7 +294,7 @@ export async function startApp( } }), ); - scheduler.start(ctx); + runner.start(); log.info( { user: ready.user.tag, features: registry.features.map((f) => f.name) }, 'Ready', @@ -312,7 +302,7 @@ export async function startApp( return async () => { client.removeAllListeners(Events.InteractionCreate); - await scheduler.stop(); + await runner.stop(); await client.destroy(); await database.close(); }; diff --git a/src/infra/db/settings/repo.ts b/src/infra/db/settings/repo.ts index 82c0bea..910ba68 100644 --- a/src/infra/db/settings/repo.ts +++ b/src/infra/db/settings/repo.ts @@ -11,19 +11,6 @@ export const guildSettings = pgTable('guild_settings', { .defaultNow(), }); -export async function getGuildTimezone( - db: Db, - guildId: string, - fallback: string, -): Promise { - const [row] = await db - .select({ timezone: guildSettings.timezone }) - .from(guildSettings) - .where(eq(guildSettings.guildId, guildId)); - - return row?.timezone ?? fallback; -} - export async function setGuildTimezone( db: Db, guildId: string, diff --git a/src/infra/discord/define.ts b/src/infra/discord/define.ts index 6900352..618e0fa 100644 --- a/src/infra/discord/define.ts +++ b/src/infra/discord/define.ts @@ -1,42 +1,12 @@ import { MessageFlags, type ClientEvents } from 'discord.js'; -import type { z } from 'zod'; -import { PermanentError } from '~/domain'; import { subcommandPath } from './router'; import type { AppContext, CommandInteraction, EventListener, - Job, - JobInfo, - JobOutcome, SlashCommand, } from './module'; -export function defineJob(definition: { - type: string; - payload: S; - maxAttempts?: number; - handle: ( - payload: z.infer, - info: JobInfo, - ctx: AppContext, - ) => Promise; -}): Job> { - return { - type: definition.type, - maxAttempts: definition.maxAttempts ?? 5, - run: async (raw, info, ctx) => { - const parsed = definition.payload.safeParse(raw); - - if (!parsed.success) { - throw new PermanentError(`Invalid payload: ${parsed.error.message}`); - } - - return (await definition.handle(parsed.data, info, ctx)) ?? null; - }, - }; -} - export function defineListener( event: K, handle: (ctx: AppContext, ...args: ClientEvents[K]) => Promise, diff --git a/src/infra/discord/errors.ts b/src/infra/discord/errors.ts index efe3ff5..9474269 100644 --- a/src/infra/discord/errors.ts +++ b/src/infra/discord/errors.ts @@ -1,5 +1,4 @@ import { DiscordAPIError, RESTJSONErrorCodes } from 'discord.js'; -import { PermanentError } from '~/domain'; const permanentCodes = new Set([ RESTJSONErrorCodes.UnknownChannel, @@ -17,12 +16,6 @@ export function isPermanentDiscordError(error: unknown): boolean { return error instanceof DiscordAPIError && permanentCodes.has(error.code); } -export function asJobError(error: unknown): unknown { - return isPermanentDiscordError(error) && error instanceof Error - ? new PermanentError(error.message) - : error; -} - export function isUnknownObject(error: unknown): boolean { return ( error instanceof DiscordAPIError && diff --git a/src/infra/discord/module.ts b/src/infra/discord/module.ts index 83ec038..4ca674a 100644 --- a/src/infra/discord/module.ts +++ b/src/infra/discord/module.ts @@ -8,36 +8,14 @@ import type { ModalSubmitInteraction, RESTPostAPIChatInputApplicationCommandsJSONBody, } from 'discord.js'; -import type { Db } from '~/infra/db'; -import type { Config } from '~/config'; -import type { Logger } from '~/infra/logging'; -import type { Authorizer } from '~/core/ports'; +import type { Logger, Authorizer } from '~/core/ports'; import type { Permission, PermissionDefinition } from '~/domain'; export type { Permission, PermissionDefinition } from '~/domain'; -export type ScheduleOptions = { - runAt: Date; - key?: string; - maxAttempts?: number; -}; - -export type Scheduler = { - schedule:

( - job: Job

, - payload: P, - options: ScheduleOptions, - ) => Promise; - cancel: (key: string) => Promise; -}; - export type AppContext = { - client: Client; - db: Db; log: Logger; - config: Config; authz: Authorizer; - scheduler: Scheduler; }; export type CommandInteraction = ChatInputCommandInteraction<'cached'>; @@ -72,27 +50,11 @@ export type EventListener = { attach: (client: Client, ctx: AppContext) => void; }; -export type JobInfo = { - id: number; - runAt: Date; - attempt: number; -}; - -export type JobOutcome = null | { rescheduleAt: Date }; - -export type Job

= { - type: string; - maxAttempts: number; - run: (raw: unknown, info: JobInfo, ctx: AppContext) => Promise; - payloadType?: P; -}; - export type Feature = { name: string; permissions?: readonly PermissionDefinition[]; commands?: readonly SlashCommand[]; components?: readonly ComponentHandler[]; events?: readonly EventListener[]; - jobs?: ReadonlyArray>; - start?: (ctx: AppContext) => Promise; + start?: () => Promise; }; diff --git a/src/infra/discord/registry.ts b/src/infra/discord/registry.ts index efcec4a..54367d0 100644 --- a/src/infra/discord/registry.ts +++ b/src/infra/discord/registry.ts @@ -1,7 +1,6 @@ import type { ComponentHandler, Feature, - Job, Permission, PermissionDefinition, SlashCommand, @@ -11,7 +10,6 @@ export type Registry = { features: readonly Feature[]; commands: ReadonlyMap; components: ReadonlyMap; - jobs: ReadonlyMap>; permissions: ReadonlyMap; }; @@ -34,7 +32,6 @@ export function buildRegistry(features: readonly Feature[]): Registry { const names = new Map(); const commands = new Map(); const components = new Map(); - const jobs = new Map>(); const permissions = new Map(); for (const feature of features) { @@ -51,10 +48,6 @@ export function buildRegistry(features: readonly Feature[]): Registry { addUnique(components, component.prefix, component, 'component prefix'); } - for (const job of feature.jobs ?? []) { - addUnique(jobs, job.type, job, 'job type'); - } - for (const permission of feature.permissions ?? []) { if (permissions.has(permission.id)) { throw new Error(`Duplicate permission "${permission.id}"`); @@ -64,7 +57,7 @@ export function buildRegistry(features: readonly Feature[]): Registry { } } - return { features, commands, components, jobs, permissions }; + return { features, commands, components, permissions }; } export function parseCustomId( @@ -78,16 +71,3 @@ export function parseCustomId( return { prefix: `${feature}:${action}`, args }; } - -export function customId( - prefix: string, - ...args: Array -): string { - const id = [prefix, ...args].join(':'); - - if (id.length > 100) { - throw new Error(`Custom ID exceeds 100 characters: ${id}`); - } - - return id; -} diff --git a/src/infra/scheduler/index.ts b/src/infra/scheduler/index.ts index 252b474..a4c109e 100644 --- a/src/infra/scheduler/index.ts +++ b/src/infra/scheduler/index.ts @@ -1,2 +1,2 @@ -export * from './scheduler'; export * from './queue'; +export * from './runner'; diff --git a/src/infra/scheduler/scheduler.ts b/src/infra/scheduler/runner.ts similarity index 65% rename from src/infra/scheduler/scheduler.ts rename to src/infra/scheduler/runner.ts index dc5d010..7ecc605 100644 --- a/src/infra/scheduler/scheduler.ts +++ b/src/infra/scheduler/runner.ts @@ -1,19 +1,18 @@ import { setTimeout as sleep } from 'node:timers/promises'; import type { Db, JobRow } from '~/infra/db'; import { PermanentError } from '~/domain'; -import type { AppContext, Job, Scheduler } from '~/infra/discord'; -import type { Logger } from '~/infra/logging'; -import { cancelJob, claimDueJobs, finishJob, upsertJob } from '~/infra/db'; +import type { Job, Logger } from '~/core/ports'; +import { claimDueJobs, finishJob } from '~/infra/db'; -export type SchedulerOptions = { +export type RunnerOptions = { pollIntervalMs?: number; batchSize?: number; leaseMs?: number; }; -export type SchedulerRuntime = Scheduler & { - tick: (ctx: AppContext) => Promise; - start: (ctx: AppContext) => void; +export type JobRunner = { + tick: () => Promise; + start: () => void; stop: () => Promise; }; @@ -23,12 +22,12 @@ export function retryDelayMs(attempt: number): number { return Math.min(30_000 * 2 ** (attempt - 1), maxBackoffMs); } -export function createScheduler( +export function createJobRunner( db: Db, jobs: ReadonlyMap>, log: Logger, - options: SchedulerOptions = {}, -): SchedulerRuntime { + options: RunnerOptions = {}, +): JobRunner { const pollIntervalMs = options.pollIntervalMs ?? 5000; const batchSize = options.batchSize ?? 10; const leaseMs = options.leaseMs ?? 5 * 60 * 1000; @@ -36,7 +35,7 @@ export function createScheduler( const abort = new AbortController(); let loop: Promise | undefined; - async function execute(row: JobRow, ctx: AppContext): Promise { + async function execute(row: JobRow): Promise { const job = jobs.get(row.type); const jobLog = log.child({ jobId: row.id, jobType: row.type }); @@ -54,11 +53,11 @@ export function createScheduler( } try { - const outcome = await job.run( - row.payload, - { id: row.id, runAt: row.runAt, attempt: row.attempts }, - { ...ctx, log: jobLog }, - ); + const outcome = await job.run(row.payload, { + id: row.id, + runAt: row.runAt, + attempt: row.attempts, + }); await finishJob( db, @@ -90,20 +89,20 @@ export function createScheduler( } } - async function tick(ctx: AppContext): Promise { + async function tick(): Promise { const rows = await claimDueJobs(db, { types, limit: batchSize, leaseMs }); - await Promise.all(rows.map((row) => execute(row, ctx))); + await Promise.all(rows.map((row) => execute(row))); return rows.length; } - async function run(ctx: AppContext): Promise { + async function run(): Promise { while (!abort.signal.aborted) { let claimed = 0; try { - claimed = await tick(ctx); + claimed = await tick(); } catch (error) { log.error({ err: error }, 'Scheduler tick failed'); } @@ -117,19 +116,9 @@ export function createScheduler( } return { - schedule: async (job, payload, scheduleOptions) => { - await upsertJob(db, { - type: job.type, - payload, - runAt: scheduleOptions.runAt, - key: scheduleOptions.key, - maxAttempts: scheduleOptions.maxAttempts ?? job.maxAttempts, - }); - }, - cancel: (key) => cancelJob(db, key), tick, - start: (ctx) => { - loop ??= run(ctx); + start: () => { + loop ??= run(); }, stop: async () => { abort.abort(); diff --git a/tests/core/services/redmine.test.ts b/tests/core/services/redmine.test.ts index 994595d..afcb799 100644 --- a/tests/core/services/redmine.test.ts +++ b/tests/core/services/redmine.test.ts @@ -79,9 +79,9 @@ describe.skipIf(noDatabase)('redmine service', () => { it('turns tracker failures into user-facing errors', async () => { const failing = tracker({ - listProjects: vi.fn(async () => - { throw new IntegrationError('forbidden', 'Not allowed.'); }, - ), + listProjects: vi.fn(async () => { + throw new IntegrationError('forbidden', 'Not allowed.'); + }), }); const { service } = setup(failing); const member = actor({ guildId: snowflake(), userId: snowflake() }); @@ -130,7 +130,9 @@ describe.skipIf(noDatabase)('redmine service', () => { it('keeps going when one subscription fails', async () => { const { service } = setup( tracker({ - listIssues: vi.fn(async () => { throw new Error('boom'); }), + listIssues: vi.fn(async () => { + throw new Error('boom'); + }), }), ); diff --git a/tests/infra/discord/registry.test.ts b/tests/infra/discord/registry.test.ts index 0c749d2..b3bec16 100644 --- a/tests/infra/discord/registry.test.ts +++ b/tests/infra/discord/registry.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; import type { Feature } from '~/infra/discord'; -import { buildRegistry, customId, parseCustomId } from '~/infra/discord'; +import { controlId } from '~/domain'; +import { buildRegistry, parseCustomId } from '~/infra/discord'; const noop = async () => undefined; -const noopJob = async () => null; const command = (name: string) => ({ data: { name, description: name }, execute: noop, @@ -41,13 +41,6 @@ describe('buildRegistry', () => { { name: 'b', components: [{ prefix: 'x:y', execute: noop }] }, ], ], - [ - 'job type', - [ - { name: 'a', jobs: [{ type: 'j', maxAttempts: 1, run: noopJob }] }, - { name: 'b', jobs: [{ type: 'j', maxAttempts: 1, run: noopJob }] }, - ], - ], [ 'permission', [ @@ -70,7 +63,7 @@ describe('buildRegistry', () => { describe('custom IDs', () => { it('round-trips prefix and arguments', () => { - expect(parseCustomId(customId('polls:vote', 12, 'x'))).toEqual({ + expect(parseCustomId(controlId('polls:vote', 12, 'x'))).toEqual({ prefix: 'polls:vote', args: ['12', 'x'], }); @@ -78,6 +71,6 @@ describe('custom IDs', () => { }); it('enforces the Discord length limit', () => { - expect(() => customId('a:b', 'x'.repeat(100))).toThrow('100 characters'); + expect(() => controlId('a:b', 'x'.repeat(100))).toThrow('100 characters'); }); }); diff --git a/tests/infra/scheduler/scheduler.test.ts b/tests/infra/scheduler/runner.test.ts similarity index 82% rename from tests/infra/scheduler/scheduler.test.ts rename to tests/infra/scheduler/runner.test.ts index 1386294..9da1866 100644 --- a/tests/infra/scheduler/scheduler.test.ts +++ b/tests/infra/scheduler/runner.test.ts @@ -4,9 +4,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod'; import { noDatabase, testDb } from '../../db'; import { PermanentError } from '~/domain'; -import { defineJob } from '~/infra/discord'; -import type { AppContext } from '~/infra/discord'; -import { createScheduler, retryDelayMs } from '~/infra/scheduler'; +import { defineJob } from '~/core/services'; +import { + createJobQueue, + createJobRunner, + retryDelayMs, +} from '~/infra/scheduler'; import { scheduledJobs, claimDueJobs } from '~/infra/db'; const log = pino({ level: 'silent' }); @@ -27,10 +30,12 @@ describe.skipIf(noDatabase)('scheduler', () => { throw new Error('unreachable'); } - const scheduler = createScheduler(db, new Map([[job.type, job]]), log); - const ctx = { db, log } as unknown as AppContext; + const scheduler = { + ...createJobQueue(db), + ...createJobRunner(db, new Map([[job.type, job]]), log), + }; - return { db, scheduler, ctx }; + return { db, scheduler }; }; const past = () => new Date(Date.now() - 1000); @@ -50,7 +55,7 @@ describe.skipIf(noDatabase)('scheduler', () => { }); it('runs due jobs once and marks them done', async () => { - const { scheduler, ctx } = setup(); + const { scheduler } = setup(); handle.mockResolvedValue(null); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'a' }); @@ -60,40 +65,40 @@ describe.skipIf(noDatabase)('scheduler', () => { { runAt: new Date(Date.now() + 60_000), key: 'b' }, ); - expect(await scheduler.tick(ctx)).toBe(1); - expect(await scheduler.tick(ctx)).toBe(0); + expect(await scheduler.tick()).toBe(1); + expect(await scheduler.tick()).toBe(0); expect(handle).toHaveBeenCalledExactlyOnceWith({ n: 1 }); expect((await row('a'))?.status).toBe('done'); expect((await row('b'))?.status).toBe('pending'); }); it('replaces a pending job scheduled with the same key', async () => { - const { scheduler, ctx } = setup(); + const { scheduler } = setup(); handle.mockResolvedValue(null); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'same' }); await scheduler.schedule(job, { n: 2 }, { runAt: past(), key: 'same' }); - await scheduler.tick(ctx); + await scheduler.tick(); expect(handle).toHaveBeenCalledExactlyOnceWith({ n: 2 }); }); it('does not run cancelled jobs', async () => { - const { scheduler, ctx } = setup(); + const { scheduler } = setup(); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'c' }); await scheduler.cancel('c'); - expect(await scheduler.tick(ctx)).toBe(0); + expect(await scheduler.tick()).toBe(0); expect((await row('c'))?.status).toBe('cancelled'); }); it('retries transient failures with backoff, then fails', async () => { - const { db: database, scheduler, ctx } = setup(); + const { db: database, scheduler } = setup(); handle.mockRejectedValue(new Error('discord down')); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'r' }); for (let attempt = 1; attempt <= 3; attempt++) { - await scheduler.tick(ctx); + await scheduler.tick(); const current = await row('r'); expect(current?.attempts).toBe(attempt); @@ -114,7 +119,7 @@ describe.skipIf(noDatabase)('scheduler', () => { }); it('does not retry permanent failures or invalid payloads', async () => { - const { db: database, scheduler, ctx } = setup(); + const { db: database, scheduler } = setup(); handle.mockRejectedValue(new PermanentError('user blocked DMs')); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'p' }); @@ -124,19 +129,19 @@ describe.skipIf(noDatabase)('scheduler', () => { runAt: past(), key: 'bad', }); - await scheduler.tick(ctx); + await scheduler.tick(); expect((await row('p'))?.status).toBe('failed'); expect((await row('bad'))?.status).toBe('failed'); expect(handle).toHaveBeenCalledOnce(); }); it('reschedules recurring jobs', async () => { - const { scheduler, ctx } = setup(); + const { scheduler } = setup(); const next = new Date(Date.now() + 86_400_000); handle.mockResolvedValue({ rescheduleAt: next }); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'rec' }); - await scheduler.tick(ctx); + await scheduler.tick(); const current = await row('rec'); expect(current?.status).toBe('pending'); @@ -145,7 +150,7 @@ describe.skipIf(noDatabase)('scheduler', () => { }); it('recovers jobs whose lease expired after a crash', async () => { - const { db: database, scheduler, ctx } = setup(); + const { db: database, scheduler } = setup(); handle.mockResolvedValue(null); await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'crash' }); @@ -154,12 +159,12 @@ describe.skipIf(noDatabase)('scheduler', () => { limit: 10, leaseMs: 60_000, }); - expect(await scheduler.tick(ctx)).toBe(0); + expect(await scheduler.tick()).toBe(0); await database .update(scheduledJobs) .set({ lockedUntil: sql`now() - interval '1 second'` }) .where(eq(scheduledJobs.key, 'crash')); - expect(await scheduler.tick(ctx)).toBe(1); + expect(await scheduler.tick()).toBe(1); expect((await row('crash'))?.status).toBe('done'); }); @@ -186,7 +191,7 @@ describe.skipIf(noDatabase)('scheduler', () => { }); it('leaves jobs of unregistered types untouched', async () => { - const { db: database, scheduler, ctx } = setup(); + const { db: database, scheduler } = setup(); await database.insert(scheduledJobs).values({ type: 'disabled:feature', @@ -194,7 +199,7 @@ describe.skipIf(noDatabase)('scheduler', () => { runAt: past(), key: 'off', }); - expect(await scheduler.tick(ctx)).toBe(0); + expect(await scheduler.tick()).toBe(0); expect((await row('off'))?.status).toBe('pending'); }); }); From 9b39869ac40b413abe483c375b60788a1a88f941 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 21:33:00 +0200 Subject: [PATCH 031/199] docs: describe the ports and adapters layout --- README.md | 106 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 64 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 9797d78..fff73e4 100644 --- a/README.md +++ b/README.md @@ -171,51 +171,72 @@ published outside the Compose network. Back up the `pgdata` volume. ## Architecture +Ports and adapters. Business logic never imports discord.js, drizzle or an +HTTP client; it talks to ports, and adapters implement them. + ``` src/ - index.ts entry point: config, logging, signals - app.ts composition root: the list of features - core/ no feature-specific logic - feature.ts the Feature contract and shared types - registry.ts collects features, rejects duplicates - discord/ client, interaction router, error boundary - permissions/ RBAC storage and the Authorizer - scheduler/ persistent job scheduler - features// index.ts is the public API; service.ts and schema.ts - hold persistence and logic and may not import discord.js - integrations/redmine typed HTTP client, no Discord code - shared/ time parsing, encryption, error types -drizzle/ SQL migrations + index.ts entry point: config, logging, signals + app.ts composition root: builds adapters, services, commands + config/ validated environment + domain/ pure types and rules: actors, permissions, messages, + time, polls, birthdays, issues + lib/ generic helpers + core/ + ports/ contracts: Messenger, Directory, Calendar, Scheduler, + IssueTracker, SecretBox and one repository per area + services/ use cases (roles, reminders, events, polls, ...), each + created from its ports, with permission guards + infra/ + db// drizzle model and repository adapters + discord/ discord.js client, router, outbound adapters and the + thin slash-command adapters in commands/ + scheduler/ job queue (Scheduler port) and the job runner + redmine/ Redmine adapter for the IssueTracker port + crypto/ AES-256-GCM SecretBox + logging/ pino +tests/ mirrors src/ +drizzle/ SQL migrations ``` -- **Features** declare commands, components (custom ID prefix - `feature:action`), event listeners, jobs and permissions. The router - dispatches by name and prefix, so it never changes when features are added. -- **Cross-feature use** goes through public `index.ts` exports only (enforced - by ESLint): movies use `createPoll` and `createEvent`, Redmine uses - `createReminder`. -- **Scheduler:** jobs live in `scheduled_jobs`. Workers claim due jobs with - `FOR UPDATE SKIP LOCKED` and a lease, so a crash mid-job leads to a retry - after the lease expires. Delivery is at-least-once, and handlers re-check - current state. Where a duplicate Discord message would be worse than a +- **Boundaries are linted.** Modules import each other only through their + barrel (`~/core/services`, never `~/core/services/roles`). The domain + depends on nothing, core depends only on the domain, and only + `infra/discord` may import discord.js. +- **Services take an `Actor`** (guild, user, roles, administrator), not a + Discord member, and enforce permissions themselves. Any adapter that can + produce an actor (Discord now, a web UI later) gets the same rules. +- **Messages are transport-neutral** (`domain/message.ts`): content, embeds, + mentions and controls. `infra/discord/render.ts` turns them into discord.js + payloads. +- **Cross-service use is explicit**: movies get the poll and event services, + Redmine gets the reminder service. +- **Scheduler:** jobs live in `scheduled_jobs`. The runner claims due jobs + with `FOR UPDATE SKIP LOCKED` and a lease, so a crash mid-job leads to a + retry after the lease expires. Delivery is at-least-once, and handlers + re-check current state. Where a duplicate message would be worse than a missed one (announcements, birthdays, Redmine notifications), the handler - records the send in the database before posting. Each handler decides what - lateness means: late reminders are still delivered, overdue polls close, and - announcements more than an hour late are skipped and marked failed. - Transient failures retry with backoff; permanent Discord errors (closed - DMs, deleted channels) do not. - -### Adding a feature - -1. Create `src/features//`, with `schema.ts` for tables, `service.ts` - for database logic, and `index.ts` exporting a `Feature`. -2. Add it to the list in `src/app.ts`. -3. `pnpm db:generate` if you added tables, then `pnpm commands:register`. - -Declare permissions in the feature and attach them per subcommand with -`permissions: { create: 'thing:create' }`. Prefix custom IDs with the feature -name and keep any state the component needs in the database, so buttons keep -working after restarts. + records the send before posting. Each handler decides what lateness means: + late reminders are still delivered, overdue polls close, and announcements + more than an hour late are skipped. Permanent delivery failures (closed DMs, + deleted channels) are not retried. + +### Adding a feature or integration + +1. Domain rules go in `src/domain/.ts`. +2. The contracts it needs go in `src/core/ports/.ts`. Reuse `Messenger`, + `Directory` and `Scheduler` where they fit. +3. The use cases go in `src/core/services/.ts` as + `createService(deps)`, guarded with `guard(authz, 'area:action', ...)`. + Background work is a `defineJob` in the service's `jobs`. +4. Adapters: a drizzle repository in `src/infra/db//`, plus + `src/infra/discord/commands/.ts` for slash commands. A new external + system (another tracker, a calendar, a chat platform) is a new adapter + implementing an existing port. +5. Wire it in `src/app.ts`, then run `pnpm db:generate` and + `pnpm commands:register`. +6. Tests: `tests/domain`, `tests/core/services` (real Postgres plus the fakes in + `tests/fakes.ts`) and `tests/infra`. ## Known limitations @@ -229,7 +250,8 @@ working after restarts. issues changed within the same second could keep the checkpoint from moving. - Birthday announcements are not sent for days the bot was entirely offline. - User-facing text is English (the legacy panel and birthday wishes are - Estonian). Strings sit in the Discord layer of each feature, ready for - localisation. + Estonian). +- The web UI and PSA composer are not built yet. The services already take an + `Actor`, so a web adapter can reuse them unchanged. - Native Discord polls are not used, because bot polls must persist and work with movie nights. From dc611615a71d3e62cbb2256134bfbe70b148edc1 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 22:33:44 +0200 Subject: [PATCH 032/199] feat(lib): escaping html template helper --- src/lib/html.ts | 51 ++++++++++++++++++++++++++++++++++++++++++ src/lib/index.ts | 1 + tests/lib/html.test.ts | 16 +++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 src/lib/html.ts create mode 100644 tests/lib/html.test.ts diff --git a/src/lib/html.ts b/src/lib/html.ts new file mode 100644 index 0000000..bce17eb --- /dev/null +++ b/src/lib/html.ts @@ -0,0 +1,51 @@ +const marker = Symbol('html'); + +export type Html = { readonly [marker]: true; readonly value: string }; + +const escapes: Record = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', +}; + +export const escapeHtml = (text: string) => + text.replaceAll(/[&<>"']/g, (character) => escapes[character] ?? character); + +export const raw = (value: string): Html => ({ [marker]: true, value }); + +const isHtml = (value: unknown): value is Html => + typeof value === 'object' && value !== null && marker in value; + +type Value = + Html | string | number | boolean | null | undefined | readonly Value[]; + +const isList = (value: Value): value is readonly Value[] => + Array.isArray(value); + +function render(value: Value): string { + if (isList(value)) { + return value.map((item) => render(item)).join(''); + } + + if (isHtml(value)) { + return value.value; + } + + if (value === null || value === undefined || value === false) { + return ''; + } + + return escapeHtml(String(value)); +} + +export function html(strings: TemplateStringsArray, ...values: Value[]): Html { + return raw( + strings.reduce( + (out, part, index) => + out + part + (index < values.length ? render(values[index]) : ''), + '', + ), + ); +} diff --git a/src/lib/index.ts b/src/lib/index.ts index 780df27..a9f221e 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -1 +1,2 @@ export * from './async'; +export * from './html'; diff --git a/tests/lib/html.test.ts b/tests/lib/html.test.ts new file mode 100644 index 0000000..7e02ba0 --- /dev/null +++ b/tests/lib/html.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { html, raw } from '~/lib'; + +describe('html', () => { + it('escapes interpolated values but not nested html', () => { + const name = ''; + + expect(html`

${name}

`.value).toBe( + '

<script>"x"</script>

', + ); + const inner = html`${'a&b'}`; + + expect(html`
${inner}
`.value).toBe('
a&b
'); + expect(html`${[raw(''), 'x', null, false]}`.value).toBe('x'); + }); +}); From 56a3b6e63de588b6d09ce8d747e79bc5c0c8095e Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 22:33:44 +0200 Subject: [PATCH 033/199] feat(web): authenticator port with local operator and Discord OAuth adapters --- src/core/ports/auth.ts | 9 ++++ src/core/ports/index.ts | 1 + src/infra/web/auth.ts | 80 ++++++++++++++++++++++++++++++++++++ tests/infra/web/auth.test.ts | 49 ++++++++++++++++++++++ 4 files changed, 139 insertions(+) create mode 100644 src/core/ports/auth.ts create mode 100644 src/infra/web/auth.ts create mode 100644 tests/infra/web/auth.test.ts diff --git a/src/core/ports/auth.ts b/src/core/ports/auth.ts new file mode 100644 index 0000000..558f73e --- /dev/null +++ b/src/core/ports/auth.ts @@ -0,0 +1,9 @@ +import type { Actor } from '~/domain'; + +export type WebRequest = { + headers: Readonly>; +}; + +export type Authenticator = { + authenticate: (request: WebRequest) => Promise; +}; diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 42708fd..29d4633 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -13,3 +13,4 @@ export type * from './polls'; export type * from './movies'; export type * from './birthdays'; export type * from './issues'; +export type * from './auth'; diff --git a/src/infra/web/auth.ts b/src/infra/web/auth.ts new file mode 100644 index 0000000..0e2d401 --- /dev/null +++ b/src/infra/web/auth.ts @@ -0,0 +1,80 @@ +import { z } from 'zod'; +import type { Authenticator, Directory } from '~/core/ports'; +import type { Actor } from '~/domain'; + +export function localOperator(actor: () => Promise): Authenticator { + return { authenticate: actor }; +} + +const tokenResponse = z.object({ + access_token: z.string(), + token_type: z.string(), +}); +const userResponse = z.object({ id: z.string() }); +const discordApi = 'https://discord.com/api/v10'; + +export type DiscordOAuthOptions = { + clientId: string; + clientSecret: string; + redirectUri: string; + guildId: string; + directory: Directory; + fetch?: typeof fetch; +}; + +export function createDiscordOAuth(options: DiscordOAuthOptions) { + const request = options.fetch ?? fetch; + + return { + authorizeUrl: (state: string) => { + const url = new URL('https://discord.com/oauth2/authorize'); + + url.search = new URLSearchParams({ + client_id: options.clientId, + redirect_uri: options.redirectUri, + response_type: 'code', + scope: 'identify', + state, + }).toString(); + + return url.href; + }, + actorFor: async (code: string): Promise => { + const token = await request(`${discordApi}/oauth2/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + client_id: options.clientId, + client_secret: options.clientSecret, + grant_type: 'authorization_code', + code, + redirect_uri: options.redirectUri, + }), + signal: AbortSignal.timeout(10_000), + }); + const parsedToken = tokenResponse.safeParse( + await token.json().catch(() => null), + ); + + if (!token.ok || !parsedToken.success) { + return undefined; + } + + const me = await request(`${discordApi}/users/@me`, { + headers: { + Authorization: `${parsedToken.data.token_type} ${parsedToken.data.access_token}`, + }, + signal: AbortSignal.timeout(10_000), + }); + const parsedUser = userResponse.safeParse( + await me.json().catch(() => null), + ); + + if (!me.ok || !parsedUser.success) { + return undefined; + } + + return options.directory.member(options.guildId, parsedUser.data.id); + }, + }; +} diff --git a/tests/infra/web/auth.test.ts b/tests/infra/web/auth.test.ts new file mode 100644 index 0000000..b9d2fe1 --- /dev/null +++ b/tests/infra/web/auth.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createDiscordOAuth } from '~/infra/web'; +import { actor, fakeDirectory } from '../../fakes'; + +describe('Discord OAuth adapter', () => { + it('builds an authorize URL and turns a code into a guild actor', async () => { + const directory = fakeDirectory(); + const member = actor({ userId: '42' }); + + directory.member.mockResolvedValue(member); + + const fetch = vi + .fn() + .mockResolvedValueOnce( + Response.json({ access_token: 't', token_type: 'Bearer' }), + ) + .mockResolvedValueOnce(Response.json({ id: '42' })); + const oauth = createDiscordOAuth({ + clientId: 'c', + clientSecret: 's', + redirectUri: 'http://localhost/cb', + guildId: 'g', + directory, + fetch, + }); + + expect(oauth.authorizeUrl('state')).toContain('scope=identify'); + expect(await oauth.actorFor('code')).toBe(member); + expect(directory.member).toHaveBeenCalledWith('g', '42'); + }); + + it('returns nothing when Discord rejects the code', async () => { + const fetch = vi + .fn() + .mockResolvedValue( + Response.json({ error: 'invalid_grant' }, { status: 400 }), + ); + const oauth = createDiscordOAuth({ + clientId: 'c', + clientSecret: 's', + redirectUri: 'r', + guildId: 'g', + directory: fakeDirectory(), + fetch, + }); + + expect(await oauth.actorFor('bad')).toBeUndefined(); + }); +}); From e3522059540a13fddd60414691e33d90e614633a Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 22:33:44 +0200 Subject: [PATCH 034/199] feat(web): web UI with PSA composer, events, polls, permissions and settings --- src/infra/web/app.ts | 884 ++++++++++++++++++++++++++++++++++++ src/infra/web/index.ts | 4 + src/infra/web/layout.ts | 71 +++ src/infra/web/preview.ts | 71 +++ src/infra/web/server.ts | 36 ++ tests/infra/web/app.test.ts | 240 ++++++++++ 6 files changed, 1306 insertions(+) create mode 100644 src/infra/web/app.ts create mode 100644 src/infra/web/index.ts create mode 100644 src/infra/web/layout.ts create mode 100644 src/infra/web/preview.ts create mode 100644 src/infra/web/server.ts create mode 100644 tests/infra/web/app.test.ts diff --git a/src/infra/web/app.ts b/src/infra/web/app.ts new file mode 100644 index 0000000..5d7a02e --- /dev/null +++ b/src/infra/web/app.ts @@ -0,0 +1,884 @@ +import { randomBytes, randomUUID } from 'node:crypto'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { + Authenticator, + ChannelInfo, + Directory, + Logger, +} from '~/core/ports'; +import type { + AnnouncementService, + EventService, + PermissionService, + PollService, + SettingsService, +} from '~/core/services'; +import { UserError, type Actor, type RoleInfo } from '~/domain'; +import { html, raw, type Html } from '~/lib'; +import { page, type Flash } from './layout'; +import { messagePreview, type Names } from './preview'; + +export type WebServices = { + announcements: AnnouncementService; + events: EventService; + polls: PollService; + permissions: PermissionService; + settings: SettingsService; +}; + +type Deps = { + guildId: string; + auth: Authenticator; + directory: Directory; + services: WebServices; + log: Logger; +}; + +type Form = URLSearchParams; + +type Context = { + actor: Actor; + form: Form; + path: string; + flash: Flash; + csrf: Html; + guild: { channels: ChannelInfo[]; roles: RoleInfo[]; names: Names }; +}; + +type Result = { status?: number; body: Html } | { redirect: string }; + +type Route = { + method: 'GET' | 'POST'; + pattern: RegExp; + handle: (context: Context, params: string[]) => Promise; +}; + +const maxBodyBytes = 64 * 1024; + +const date = (value: Date | null) => + value === null ? '' : value.toISOString().slice(0, 16).replace('T', ' '); + +const field = (form: Form, name: string) => { + const value = form.get(name)?.trim() ?? ''; + + return value === '' ? undefined : value; +}; + +const location = (path: string, flash: Flash) => { + const query = new URLSearchParams(Object.entries(flash)).toString(); + + return query === '' ? path : `${path}?${query}`; +}; + +const redirect = (path: string, flash: Flash): Result => ({ + redirect: location(path, flash), +}); + +function channelSelect(context: Context, name = 'channelId') { + return html``; +} + +function mentionPicker(context: Context, selected: readonly string[] = []) { + const roles = context.guild.roles.filter( + (role) => !role.everyone && !role.managed, + ); + + return html`
+ Mention + + ${roles.map( + (role) => + html``, + )} +
`; +} + +const psaActions = (context: Context, psa: { id: number; status: string }) => { + if (!['draft', 'failed', 'scheduled'].includes(psa.status)) { + return html``; + } + + const publish = button( + context, + ['', 'psa', psa.id, 'publish'].join('/'), + 'Publish', + ); + const cancel = button( + context, + ['', 'psa', psa.id, 'cancel'].join('/'), + 'Cancel', + ); + + return html`${publish} ${cancel}`; +}; + +const button = (context: Context, action: string, label: string) => + html`
+ ${context.csrf} +
`; + +function psaDraft(context: Context) { + return { + channelId: field(context.form, 'channelId') ?? '', + title: field(context.form, 'title') ?? '', + content: context.form.get('content') ?? '', + embed: context.form.get('embed') === '1', + mentionRoleIds: context.form.getAll('role'), + mentionEveryone: context.form.get('everyone') === '1', + }; +} + +function psaForm(context: Context, preview?: Html) { + const draft = psaDraft(context); + + return html`
+ ${context.csrf} ${channelSelect(context)} + + + + ${mentionPicker(context, draft.mentionRoleIds)} + +
+ + + + +
+
+ ${preview ?? ''}`; +} + +export function createWebApp(deps: Deps) { + const { services, directory, log } = deps; + const csrfToken = randomBytes(24).toString('hex'); + + const guildData = async () => { + const [channels, roles] = await Promise.all([ + directory.channels(deps.guildId), + directory.roles(deps.guildId), + ]); + + return { + channels, + roles, + names: { + roles: new Map(roles.map((role) => [role.id, role.name])), + channels: new Map( + channels.map((channel) => [channel.id, channel.name]), + ), + }, + }; + }; + + const channelName = (context: Context, id: string) => + `#${context.guild.names.channels.get(id) ?? id}`; + + const routes: Route[] = [ + { + method: 'GET', + pattern: /^\/$/, + handle: async (context) => { + const [announcements, events, polls] = await Promise.all([ + services.announcements.list(deps.guildId), + services.events.upcoming(deps.guildId), + services.polls.open(deps.guildId), + ]); + const pending = announcements.filter( + (a) => a.status === 'scheduled' || a.status === 'draft', + ); + + return { + body: page( + 'Overview', + context.path, + context.flash, + html``, + ), + }; + }, + }, + { + method: 'GET', + pattern: /^\/psa$/, + handle: async (context) => { + const list = await services.announcements.list(deps.guildId); + + return { + body: page( + 'Public service announcements', + context.path, + context.flash, + html` ${psaForm(context)} +

Recent

+ + + + + + + + + + + + + ${list.map( + (a) => + html` + + + + + + + `, + )} + +
#StatusChannelTitleWhen
${a.id}${a.status}${channelName(context, a.channelId)}${a.title ?? a.content.slice(0, 60)}${date(a.publishedAt ?? a.scheduledAt)}${psaActions(context, a)}
`, + ), + }; + }, + }, + { + method: 'POST', + pattern: /^\/psa$/, + handle: async (context) => { + const action = context.form.get('action'); + const draft = psaDraft(context); + + if (action === 'preview') { + const view = services.announcements.view({ + ...draft, + title: draft.title === '' ? null : draft.title, + id: 0, + guildId: deps.guildId, + authorId: context.actor.userId, + status: 'draft', + scheduledAt: null, + publishedAt: null, + messageId: null, + failure: null, + createdAt: new Date(), + }); + + return { + body: page( + 'Public service announcements', + '/psa', + context.flash, + psaForm( + context, + html`

Preview

+ ${messagePreview(view, context.guild.names)}`, + ), + ), + }; + } + + const created = await services.announcements.draft( + context.actor, + draft, + ); + + if (action === 'publish') { + await services.announcements.publish(context.actor, created.id); + + return redirect('/psa', { notice: `PSA #${created.id} published.` }); + } + + if (action === 'schedule') { + const scheduled = await services.announcements.schedule( + context.actor, + created.id, + field(context.form, 'when') ?? '', + ); + + return redirect('/psa', { + notice: `PSA #${created.id} scheduled for ${date(scheduled.scheduledAt)} UTC.`, + }); + } + + return redirect('/psa', { notice: `Draft #${created.id} saved.` }); + }, + }, + { + method: 'POST', + pattern: /^\/psa\/(\d+)\/(publish|cancel)$/, + handle: async (context, [id = '', action]) => { + await (action === 'publish' + ? services.announcements.publish(context.actor, Number(id)) + : services.announcements.cancel(context.actor, Number(id))); + + return redirect('/psa', { + notice: `PSA #${id} ${action === 'publish' ? 'published' : 'cancelled'}.`, + }); + }, + }, + { + method: 'GET', + pattern: /^\/events$/, + handle: async (context) => { + const upcoming = await services.events.upcoming(deps.guildId); + + return { + body: page( + 'Events', + context.path, + context.flash, + html`
+ ${context.csrf} + + + + + + ${channelSelect(context)} + + + +
+
+ + + + + + + + + + + + ${upcoming.map( + (e) => + html` + + + + + + `, + )} + +
#TitleStartsChannel
${e.id}${e.title}${date(e.startsAt)} UTC${channelName(context, e.channelId)} + ${button(context, `/events/${e.id}/cancel`, 'Cancel')} +
`, + ), + }; + }, + }, + { + method: 'POST', + pattern: /^\/events$/, + handle: async (context) => { + const optional = [ + 'end', + 'description', + 'location', + 'reminders', + ] as const; + const capacity = field(context.form, 'capacity'); + const event = await services.events.create(context.actor, { + title: field(context.form, 'title') ?? '', + start: field(context.form, 'start') ?? '', + channelId: field(context.form, 'channelId') ?? '', + native: context.form.get('native') === '1', + ...(capacity !== undefined && { capacity: Number(capacity) }), + ...Object.fromEntries( + optional.flatMap((name) => { + const value = field(context.form, name); + + return value === undefined ? [] : [[name, value]]; + }), + ), + }); + + return redirect('/events', { notice: `Event #${event.id} created.` }); + }, + }, + { + method: 'POST', + pattern: /^\/events\/(\d+)\/cancel$/, + handle: async (context, [id = '']) => { + await services.events.cancel(context.actor, Number(id)); + + return redirect('/events', { notice: `Event #${id} cancelled.` }); + }, + }, + { + method: 'GET', + pattern: /^\/polls$/, + handle: async (context) => { + const open = await services.polls.open(deps.guildId); + + return { + body: page( + 'Polls', + context.path, + context.flash, + html`
+ ${context.csrf} + + + ${channelSelect(context)} + + + + +
+
+ + + + + + + + + + + ${open.map( + (p) => + html` + + + + + `, + )} + +
#QuestionCloses
${p.id}${p.question}${date(p.closesAt)} + ${button(context, `/polls/${p.id}/close`, 'Close')} +
`, + ), + }; + }, + }, + { + method: 'POST', + pattern: /^\/polls$/, + handle: async (context) => { + const closes = field(context.form, 'closes'); + const poll = await services.polls.create(context.actor, { + question: field(context.form, 'question') ?? '', + options: (context.form.get('options') ?? '') + .split('\n') + .filter((line) => line.trim() !== ''), + channelId: field(context.form, 'channelId') ?? '', + multiple: context.form.get('multiple') === '1', + anonymous: context.form.get('anonymous') === '1', + showResults: + context.form.get('results') === 'closed' ? 'closed' : 'live', + ...(closes !== undefined && { closes }), + }); + + return redirect('/polls', { notice: `Poll #${poll.id} started.` }); + }, + }, + { + method: 'POST', + pattern: /^\/polls\/(\d+)\/close$/, + handle: async (context, [id = '']) => { + await services.polls.close(context.actor, Number(id)); + + return redirect('/polls', { notice: `Poll #${id} closed.` }); + }, + }, + { + method: 'GET', + pattern: /^\/permissions$/, + handle: async (context) => { + const grants = await services.permissions.list(context.actor); + const roleName = (id: string) => + context.guild.names.roles.get(id) ?? id; + + return { + body: page( + 'Permissions', + context.path, + context.flash, + html`

Discord administrators hold every permission.

+
+ ${context.csrf} + + +
+ +
+
+ + + + + + + + + + ${grants.map( + (g) => + html` + + + + `, + )} + +
RolePermission
@${roleName(g.roleId)}${g.permission} +
+ ${context.csrf} +
+
`, + ), + }; + }, + }, + { + method: 'POST', + pattern: /^\/permissions$/, + handle: async (context) => { + const action = + context.form.get('action') === 'revoke' ? 'revoke' : 'grant'; + const permission = field(context.form, 'permission') ?? ''; + const changed = await services.permissions[action]( + context.actor, + field(context.form, 'roleId') ?? '', + permission, + ); + + const verb = action === 'grant' ? 'Granted' : 'Revoked'; + + return redirect('/permissions', { + notice: changed ? `${verb} ${permission}.` : 'Nothing changed.', + }); + }, + }, + { + method: 'GET', + pattern: /^\/settings$/, + handle: async (context) => { + const zone = await services.settings.timezone(deps.guildId); + const now = new Date().toLocaleString('en-GB', { timeZone: zone }); + + return { + body: page( + 'Settings', + context.path, + context.flash, + html`
+ ${context.csrf} + +
+
+

+ Times you type in this UI and in Discord use this timezone. It + is now ${now} there. +

`, + ), + }; + }, + }, + { + method: 'POST', + pattern: /^\/settings$/, + handle: async (context) => { + await services.settings.setTimezone( + context.actor, + field(context.form, 'timezone') ?? '', + ); + + return redirect('/settings', { notice: 'Saved.' }); + }, + }, + ]; + + const readForm = (request: IncomingMessage): Promise
=> + new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let size = 0; + + request.on('data', (chunk: Buffer) => { + size += chunk.length; + + if (size > maxBodyBytes) { + reject(new UserError('That form is too large.')); + request.destroy(); + } else { + chunks.push(chunk); + } + }); + request.on('end', () => { + resolve(new URLSearchParams(Buffer.concat(chunks).toString('utf8'))); + }); + request.on('error', reject); + }); + + const send = ( + response: ServerResponse, + status: number, + body: string, + headers: Record = {}, + ) => { + response.writeHead(status, { + 'Content-Type': 'text/html; charset=utf-8', + 'Content-Security-Policy': + "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'", + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'same-origin', + ...headers, + }); + response.end(body); + }; + + const sameOrigin = (request: IncomingMessage) => { + const origin = request.headers.origin; + + return ( + origin === undefined || new URL(origin).host === request.headers.host + ); + }; + + const findRoute = (method: string, path: string) => + routes + .map((route) => ({ + route, + params: route.method === method ? route.pattern.exec(path) : null, + })) + .find((candidate) => candidate.params !== null); + + const plain = ( + response: ServerResponse, + status: number, + title: string, + body: Html, + ) => { + send(response, status, page(title, '', {}, body).value); + }; + + const actorFor = (request: IncomingMessage) => + deps.auth.authenticate({ + headers: Object.fromEntries( + Object.entries(request.headers).map(([name, value]) => [ + name, + Array.isArray(value) ? value.join(', ') : value, + ]), + ), + }); + + const serve = async ( + request: IncomingMessage, + response: ServerResponse, + url: URL, + ): Promise => { + const method = request.method === 'POST' ? 'POST' : 'GET'; + const match = findRoute(method, url.pathname); + + if (!match?.params) { + plain( + response, + 404, + 'Not found', + html`

Back to the overview

`, + ); + + return; + } + + const actor = await actorFor(request); + + if (!actor) { + plain( + response, + 401, + 'Sign in required', + html`

Sign-in is not set up.

`, + ); + + return; + } + + const form = + method === 'POST' ? await readForm(request) : new URLSearchParams(); + + if ( + method === 'POST' && + (!sameOrigin(request) || form.get('csrf') !== csrfToken) + ) { + plain( + response, + 403, + 'Forbidden', + html`

This form expired. Reload the page and try again.

`, + ); + + return; + } + + const flash: Flash = Object.fromEntries( + ['notice', 'error'].flatMap((key) => { + const value = url.searchParams.get(key); + + return value === null ? [] : [[key, value]]; + }), + ); + const result = await match.route.handle( + { + actor, + form, + path: url.pathname, + flash, + csrf: html``, + guild: await guildData(), + }, + match.params.slice(1), + ); + + if ('redirect' in result) { + send(response, 303, '', { Location: result.redirect }); + } else { + send(response, result.status ?? 200, result.body.value); + } + }; + + return { + handle: async ( + request: IncomingMessage, + response: ServerResponse, + ): Promise => { + const url = new URL(request.url ?? '/', 'http://localhost'); + + try { + await serve(request, response, url); + } catch (error) { + if (error instanceof UserError) { + const section = url.pathname.split('/').slice(0, 2).join('/') || '/'; + + send(response, 303, '', { + Location: location(section, { error: error.message }), + }); + + return; + } + + const ref = randomUUID().slice(0, 8); + + log.error( + { err: error, ref, path: url.pathname }, + 'Web request failed', + ); + plain( + response, + 500, + 'Something went wrong', + html`

Reference: ${ref}

`, + ); + } + }, + }; +} + +export type WebApp = ReturnType; diff --git a/src/infra/web/index.ts b/src/infra/web/index.ts new file mode 100644 index 0000000..484336f --- /dev/null +++ b/src/infra/web/index.ts @@ -0,0 +1,4 @@ +export * from './app'; +export * from './auth'; +export * from './preview'; +export * from './server'; diff --git a/src/infra/web/layout.ts b/src/infra/web/layout.ts new file mode 100644 index 0000000..aa7a6e2 --- /dev/null +++ b/src/infra/web/layout.ts @@ -0,0 +1,71 @@ +import { html, raw, type Html } from '~/lib'; + +const style = ` +body { font: 15px/1.5 system-ui, sans-serif; max-width: 60rem; margin: 0 auto; padding: 1rem; color: #1f2328; } +nav { display: flex; gap: 1rem; padding-bottom: .75rem; border-bottom: 1px solid #d0d7de; margin-bottom: 1rem; } +nav a { color: #0969da; text-decoration: none; } +nav a[aria-current] { font-weight: 600; color: #1f2328; } +form { display: grid; gap: .6rem; max-width: 40rem; margin-bottom: 1.5rem; } +label { display: grid; gap: .2rem; font-weight: 500; } +fieldset { border: 1px solid #d0d7de; border-radius: 6px; } +fieldset label { display: inline-flex; gap: .35rem; font-weight: 400; margin-right: 1rem; } +input, select, textarea, button { font: inherit; padding: .35rem .5rem; border: 1px solid #d0d7de; border-radius: 6px; } +button { background: #f6f8fa; cursor: pointer; } +button.primary { background: #1f883d; color: #fff; border-color: #1f883d; } +table { border-collapse: collapse; width: 100%; margin-bottom: 1.5rem; } +th, td { text-align: left; padding: .4rem; border-bottom: 1px solid #d0d7de; vertical-align: top; } +td form { display: inline; margin: 0; } +.notice { padding: .5rem .75rem; border-radius: 6px; background: #dafbe1; } +.error { padding: .5rem .75rem; border-radius: 6px; background: #ffebe9; } +.discord { background: #313338; color: #dbdee1; padding: .75rem 1rem; border-radius: 8px; max-width: 36rem; } +.embed { border-left: 4px solid; background: #2b2d31; padding: .5rem .75rem; border-radius: 4px; margin-top: .5rem; } +.mention { background: #3c4270; color: #c9cdfb; border-radius: 3px; padding: 0 .15rem; } +`; + +const sections = [ + ['/', 'Overview'], + ['/psa', 'PSAs'], + ['/events', 'Events'], + ['/polls', 'Polls'], + ['/permissions', 'Permissions'], + ['/settings', 'Settings'], +] as const; + +export type Flash = { notice?: string; error?: string }; + +export function page( + title: string, + path: string, + flash: Flash, + body: Html, +): Html { + return html` + + + + + ${title} · LAPbot + + + + +
+

${title}

+ ${flash.notice === undefined ? '' : html`

${flash.notice}

`} + ${flash.error === undefined ? '' : html``} + ${body} +
+ + `; +} diff --git a/src/infra/web/preview.ts b/src/infra/web/preview.ts new file mode 100644 index 0000000..54837b1 --- /dev/null +++ b/src/infra/web/preview.ts @@ -0,0 +1,71 @@ +import type { Message } from '~/domain'; +import { html, type Html } from '~/lib'; + +export type Names = { + roles: ReadonlyMap; + channels: ReadonlyMap; +}; + +const lineBreak = html`
`; + +const token = /(<@&\d+>|<@\d+>|<#\d+>|@everyone|\*\*[^*]+\*\*)/; + +function inline(text: string, names: Names): Html { + return html`${text.split(token).map((part) => { + const role = /^<@&(\d+)>$/.exec(part)?.[1]; + const user = /^<@(\d+)>$/.exec(part)?.[1]; + const channel = /^<#(\d+)>$/.exec(part)?.[1]; + + if (role !== undefined) { + return html`@${names.roles.get(role) ?? 'unknown role'}`; + } + + if (user !== undefined) { + return html`@user`; + } + + if (channel !== undefined) { + return html`#${names.channels.get(channel) ?? 'channel'}`; + } + + if (part === '@everyone') { + return html`@everyone`; + } + + if (part.startsWith('**') && part.endsWith('**')) { + return html`${part.slice(2, -2)}`; + } + + return html`${part}`; + })}`; +} + +const lines = (text: string, names: Names) => + text + .split('\n') + .map( + (line, index) => + html`${index > 0 ? lineBreak : ''}${inline(line, names)}`, + ); + +export function messagePreview(message: Message, names: Names): Html { + return html`
+ ${message.content === undefined || message.content === '' ? '' : html`

${lines(message.content, names)}

`} + ${(message.embeds ?? []).map( + (embed) => + html`
+ ${embed.title === undefined ? '' : html`${embed.title}`} + ${embed.description === undefined ? '' : html`

${lines(embed.description, names)}

`} + ${(embed.fields ?? []).map((field) => html`

${field.name}
${lines(field.value, names)}

`)} + ${embed.footer === undefined ? '' : html`${embed.footer}`} +
`, + )} +
`; +} diff --git a/src/infra/web/server.ts b/src/infra/web/server.ts new file mode 100644 index 0000000..899097a --- /dev/null +++ b/src/infra/web/server.ts @@ -0,0 +1,36 @@ +import { createServer } from 'node:http'; +import type { Logger } from '~/core/ports'; +import type { WebApp } from './app'; + +export async function startWebServer( + app: WebApp, + options: { port: number; host: string; log: Logger }, +): Promise<() => Promise> { + const server = createServer((request, response) => { + app.handle(request, response).catch((error: unknown) => { + options.log.error({ err: error }, 'Web handler crashed'); + response.destroy(); + }); + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(options.port, options.host, resolve); + }); + options.log.info( + { host: options.host, port: options.port }, + 'Web UI listening', + ); + + return () => + new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + server.closeAllConnections(); + }); +} diff --git a/tests/infra/web/app.test.ts b/tests/infra/web/app.test.ts new file mode 100644 index 0000000..0ce7f9c --- /dev/null +++ b/tests/infra/web/app.test.ts @@ -0,0 +1,240 @@ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import type { Scheduler } from '~/core/ports'; +import { + createAnnouncementService, + createAuthorizer, + createEventService, + createPermissionService, + createPollService, + createSettingsService, +} from '~/core/services'; +import { + createAnnouncementRepository, + createEventRepository, + createGrantRepository, + createPollRepository, + createSettingsRepository, +} from '~/infra/db'; +import type { Permission, PermissionDefinition } from '~/domain'; +import { createWebApp, localOperator } from '~/infra/web'; +import { noDatabase, snowflake, testDb } from '../../db'; +import { + actor, + fakeDirectory, + fakeMessenger, + role, + silentLog, +} from '../../fakes'; + +const teamId = '123456789012345678'; + +describe.skipIf(noDatabase)('web UI', () => { + const guildId = snowflake(); + const { messenger } = fakeMessenger(); + const directory = fakeDirectory([role({ id: teamId, name: 'Team' })]); + let server: Server; + let base = ''; + + directory.channels.mockResolvedValue([ + { id: 'general', name: 'general', kind: 'text' }, + ]); + + beforeAll(async () => { + const db = testDb(); + const scheduler = { + schedule: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + }; + const authz = createAuthorizer(createGrantRepository(db)); + const settings = createSettingsService({ + settings: createSettingsRepository(db), + authz, + defaultTimezone: 'Europe/Tallinn', + }); + const timezone = (id: string) => settings.timezone(id); + const shared = { + scheduler, + messenger, + directory, + authz, + log: silentLog, + timezone, + }; + const app = createWebApp({ + guildId, + auth: localOperator(async () => actor({ guildId, administrator: true })), + directory, + log: silentLog, + services: { + announcements: createAnnouncementService({ + ...shared, + announcements: createAnnouncementRepository(db), + clock: { now: () => new Date() }, + }), + events: createEventService({ + ...shared, + events: createEventRepository(db), + calendar: { upsert: async () => 'n', remove: async () => undefined }, + }), + polls: createPollService({ + ...shared, + polls: createPollRepository(db), + }), + permissions: createPermissionService({ + grants: createGrantRepository(db), + directory, + authz, + log: silentLog, + known: () => + new Map([ + [ + 'event:create', + { id: 'event:create', description: 'Create events' }, + ], + ]), + }), + settings, + }, + }); + + server = createServer( + (request, response) => void app.handle(request, response), + ); + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', resolve); + }); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + afterAll( + () => + new Promise((resolve) => { + server.close(() => { + resolve(); + }); + }), + ); + + const csrf = async (path: string) => { + const page = await (await fetch(`${base}${path}`)).text(); + + return /name="csrf" value="([0-9a-f]+)"/.exec(page)?.[1] ?? ''; + }; + + const post = (path: string, fields: Record) => { + const body = new URLSearchParams(); + + for (const [name, value] of Object.entries(fields)) { + for (const item of [value].flat()) { + body.append(name, item); + } + } + + return fetch(`${base}${path}`, { + method: 'POST', + body, + redirect: 'manual', + }); + }; + + it('renders the PSA composer with channels and mentionable roles', async () => { + const response = await fetch(`${base}/psa`); + const page = await response.text(); + + expect(response.status).toBe(200); + expect(page).toContain('#general'); + expect(page).toContain('@Team'); + expect(response.headers.get('content-security-policy')).toContain( + "default-src 'none'", + ); + }); + + it('rejects forms without the CSRF token', async () => { + const response = await post('/psa', { + channelId: 'general', + content: 'x', + action: 'publish', + }); + + expect(response.status).toBe(403); + expect(messenger.send).not.toHaveBeenCalled(); + }); + + it('previews without posting, escaping user text', async () => { + const response = await post('/psa', { + csrf: await csrf('/psa'), + channelId: 'general', + title: 'Hi', + content: `Meeting <@&${teamId}> **now**`, + role: teamId, + embed: '1', + action: 'preview', + }); + const page = await response.text(); + + expect(page).toContain('<b>Hi</b>'); + expect(page).toMatch(/class="mention"\s*>@Team { + const response = await post('/psa', { + csrf: await csrf('/psa'), + channelId: 'general', + title: 'Hackathon', + content: 'Sign up today', + role: teamId, + embed: '1', + action: 'publish', + }); + + expect(response.status).toBe(303); + expect(response.headers.get('location')).toContain('published'); + expect(messenger.send).toHaveBeenCalledWith( + 'general', + expect.objectContaining({ + content: `<@&${teamId}>`, + mentions: { everyone: false, roles: [teamId] }, + }), + ); + }); + + it('shows service errors as a message instead of failing', async () => { + const response = await post('/psa', { + csrf: await csrf('/psa'), + channelId: 'general', + content: ' ', + action: 'draft', + }); + + expect(response.status).toBe(303); + expect( + decodeURIComponent(response.headers.get('location') ?? ''), + ).toContain('error='); + }); + + it('creates polls and changes settings', async () => { + const poll = await post('/polls', { + csrf: await csrf('/polls'), + question: 'Lunch?', + options: 'Pizza\nSushi', + channelId: 'general', + }); + const timezone = await post('/settings', { + csrf: await csrf('/settings'), + timezone: 'Europe/Helsinki', + }); + + expect(poll.status).toBe(303); + expect(timezone.status).toBe(303); + expect(await (await fetch(`${base}/settings`)).text()).toContain( + 'Europe/Helsinki', + ); + }); + + it('returns 404 for unknown pages', async () => { + expect((await fetch(`${base}/nope`)).status).toBe(404); + }); +}); From 21033d57f7f1b02aef0eb0d08ee8df252e1c6ece Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 22:33:44 +0200 Subject: [PATCH 035/199] feat(web): start the web UI with the bot when WEB_PORT is set --- src/app.ts | 73 +++++++++++++++++++++++++++++++++++++++++++++-- src/config/env.ts | 13 ++++++++- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/app.ts b/src/app.ts index fc70037..01e5eec 100644 --- a/src/app.ts +++ b/src/app.ts @@ -35,7 +35,14 @@ import { import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; import { createJobQueue, createJobRunner } from '~/infra/scheduler'; -import { systemClock, type Job } from '~/core/ports'; +import { systemClock, type Directory, type Job } from '~/core/ports'; +import type { Actor } from '~/domain'; +import { + createWebApp, + localOperator, + startWebServer, + type WebServices, +} from '~/infra/web'; import { connectDatabase, createAnnouncementRepository, @@ -232,13 +239,61 @@ export function compose(config: Config, log: Logger) { runnerJobs.set(job.type, job); } - return { database, client, authz, registry, jobs: runnerJobs }; + return { + database, + client, + authz, + registry, + directory, + jobs: runnerJobs, + web: { announcements, events, polls, permissions, settings }, + }; } export function createRegistry(config: Config, log: Logger): Registry { return compose(config, log).registry; } +async function startWeb( + config: Config, + deps: { + directory: Directory; + services: WebServices; + botUserId: string; + log: Logger; + }, +): Promise<() => Promise> { + const guildId = config.DISCORD_GUILD_ID; + + if (config.WEB_PORT === undefined || guildId === undefined) { + return () => Promise.resolve(); + } + + const operator = async (): Promise => { + const bot = await deps.directory.member(guildId, deps.botUserId); + + if (!bot) { + throw new Error('The bot is not a member of DISCORD_GUILD_ID'); + } + + return { ...bot, administrator: true }; + }; + + const app = createWebApp({ + guildId, + auth: localOperator(operator), + directory: deps.directory, + services: deps.services, + log: deps.log, + }); + + return startWebServer(app, { + port: config.WEB_PORT, + host: config.WEB_HOST, + log: deps.log, + }); +} + function waitForReady(client: Client, token: string): Promise> { return new Promise((resolve, reject) => { client.once(Events.ClientReady, resolve); @@ -250,7 +305,10 @@ export async function startApp( config: Config, log: Logger, ): Promise<() => Promise> { - const { database, client, authz, registry, jobs } = compose(config, log); + const { database, client, authz, registry, directory, jobs, web } = compose( + config, + log, + ); try { await runMigrations(database.db); @@ -295,6 +353,14 @@ export async function startApp( }), ); runner.start(); + + const stopWeb = await startWeb(config, { + directory, + services: web, + botUserId: ready.user.id, + log: log.child({ component: 'web' }), + }); + log.info( { user: ready.user.tag, features: registry.features.map((f) => f.name) }, 'Ready', @@ -302,6 +368,7 @@ export async function startApp( return async () => { client.removeAllListeners(Events.InteractionCreate); + await stopWeb(); await runner.stop(); await client.destroy(); await database.close(); diff --git a/src/config/env.ts b/src/config/env.ts index 1201583..c5cfe3d 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -39,12 +39,23 @@ const envSchema = z.object({ 'must be 32 bytes encoded as base64', ), ), + + WEB_PORT: optional(z.coerce.number().int().min(1).max(65_535)), + WEB_HOST: z.string().default('127.0.0.1'), }); export type Config = z.infer; +const checkedSchema = envSchema.refine( + (env) => env.WEB_PORT === undefined || env.DISCORD_GUILD_ID !== undefined, + { + message: 'DISCORD_GUILD_ID is required when WEB_PORT is set', + path: ['DISCORD_GUILD_ID'], + }, +); + export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { - const result = envSchema.safeParse(env); + const result = checkedSchema.safeParse(env); if (!result.success) { throw new Error(`Invalid configuration:\n${z.prettifyError(result.error)}`); From e1de0a4b441633179d6c8fa02ab239a8590ba880 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 22:33:44 +0200 Subject: [PATCH 036/199] test: check commands against the 4000 character registration limit --- tests/app.test.ts | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/app.test.ts b/tests/app.test.ts index d682592..e238285 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -7,7 +7,11 @@ import { describe, expect, it } from 'vitest'; import { createRegistry } from '~/app'; import type { Config } from '~/config'; -const config = { DEFAULT_TIMEZONE: 'Europe/Tallinn' } as Config; +const config = { + DEFAULT_TIMEZONE: 'Europe/Tallinn', + REDMINE_BASE_URL: 'https://redmine.example', + CREDENTIAL_ENCRYPTION_KEY: Buffer.alloc(32).toString('base64'), +} as Config; function problems( path: string, @@ -49,6 +53,25 @@ function problems( return found; } +type Counted = { + name: string; + description?: string; + options?: readonly Counted[]; + choices?: ReadonlyArray<{ name: string; value: string | number }>; +}; + +function characters(node: Counted): number { + return ( + node.name.length + + (node.description?.length ?? 0) + + (node.choices ?? []).reduce( + (sum, choice) => sum + choice.name.length + String(choice.value).length, + 0, + ) + + (node.options ?? []).reduce((sum, option) => sum + characters(option), 0) + ); +} + describe('composition root', () => { const registry = createRegistry(config, pino({ level: 'silent' })); @@ -67,6 +90,15 @@ describe('composition root', () => { ); }); + it('keeps every command under the 4000 character limit', () => { + const sizes = [...registry.commands.values()].map((c) => ({ + name: c.data.name, + size: characters(c.data as Counted), + })); + + expect(sizes.filter(({ size }) => size > 4000)).toEqual([]); + }); + it('only requires permissions that some feature declares', () => { const declared = new Set(registry.permissions.keys()); const used = [...registry.commands.values()].flatMap((c) => From bc3eec8f125ccd3fbe504c408c834b810ad432a8 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Sun, 15 Nov 2026 22:33:44 +0200 Subject: [PATCH 037/199] docs: web UI setup and Compose port on loopback --- .env.example | 6 ++++++ README.md | 25 +++++++++++++++++++++++-- compose.yaml | 3 +++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index aece95f..bcba311 100644 --- a/.env.example +++ b/.env.example @@ -25,5 +25,11 @@ REDMINE_BASE_URL= REDMINE_API_KEY= CREDENTIAL_ENCRYPTION_KEY= +# Web UI (PSAs, events, polls, permissions, settings). Off unless WEB_PORT is +# set; requires DISCORD_GUILD_ID. There is no sign-in yet: anyone who can reach +# the port acts as an administrator, so keep it on localhost. +WEB_PORT= +WEB_HOST=127.0.0.1 + # Used by compose.yaml for the bundled PostgreSQL. POSTGRES_PASSWORD= diff --git a/README.md b/README.md index fff73e4..9f8d6b4 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,27 @@ birthday channel) live in the database and win over environment defaults | `/permissions grant/revoke/list/check` | `permissions:manage` | | `/settings timezone` | viewing is open; changing needs `settings:manage` | +## Web UI + +Set `WEB_PORT` (and `DISCORD_GUILD_ID`) to start a small web UI next to the bot: +. It covers: + +- **PSAs:** write an announcement, choose one channel and exactly which roles + (or @everyone) it mentions, preview it as Discord will show it, then publish + now, schedule it, or save a draft. +- **Events, polls, permissions and the server timezone.** + +The UI uses the same services as the slash commands, so the same rules apply: +it only posts where the bot can post, and only mentionable roles can be pinged +unless the bot may mention everyone. + +**There is no sign-in yet.** Whoever can open the page acts as a server +administrator, which is why it listens on `127.0.0.1` only (Compose publishes +it on the host's loopback). Reach it from elsewhere through an SSH tunnel, not +a public proxy. Sign-in plugs in through the `Authenticator` port; +`createDiscordOAuth` in `src/infra/web/auth.ts` is a Discord OAuth2 adapter +that is written and tested but not connected yet. + ## Permissions The bot has its own action-based permissions (`event:create`, `poll:manage`, @@ -195,6 +216,7 @@ src/ redmine/ Redmine adapter for the IssueTracker port crypto/ AES-256-GCM SecretBox logging/ pino + web/ server-rendered web UI and the Authenticator adapters tests/ mirrors src/ drizzle/ SQL migrations ``` @@ -251,7 +273,6 @@ drizzle/ SQL migrations - Birthday announcements are not sent for days the bot was entirely offline. - User-facing text is English (the legacy panel and birthday wishes are Estonian). -- The web UI and PSA composer are not built yet. The services already take an - `Actor`, so a web adapter can reuse them unchanged. +- The web UI has no sign-in yet (see [Web UI](#web-ui)). - Native Discord polls are not used, because bot polls must persist and work with movie nights. diff --git a/compose.yaml b/compose.yaml index 1fa3686..3162494 100644 --- a/compose.yaml +++ b/compose.yaml @@ -5,6 +5,9 @@ services: env_file: .env environment: DATABASE_URL: postgres://lapbot:${POSTGRES_PASSWORD:-lapbot}@postgres:5432/lapbot + WEB_HOST: 0.0.0.0 + ports: + - '127.0.0.1:${WEB_PORT:-3000}:${WEB_PORT:-3000}' depends_on: postgres: condition: service_healthy From 5858d520fe1eaf9be43b00b643fbada2766a0ef8 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:08:24 +0200 Subject: [PATCH 038/199] fix(discord): explain when the bot is not a member of the server --- src/infra/discord/router.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/infra/discord/router.ts b/src/infra/discord/router.ts index 900f2b8..e5c9af9 100644 --- a/src/infra/discord/router.ts +++ b/src/infra/discord/router.ts @@ -149,7 +149,10 @@ export function createInteractionHandler( if (interaction.isRepliable()) { await interaction .reply({ - content: 'Please use me inside the server.', + content: + interaction.guildId === null + ? 'Please use me inside the server.' + : 'I am not a member of this server yet. Ask an admin to invite me with the "bot" scope.', flags: MessageFlags.Ephemeral, }) .catch(ignore); From cc4cee7f8363016eff11bc91c1ea4cf1db5bff8b Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:13:37 +0200 Subject: [PATCH 039/199] feat(announcements): pick any number of roles to mention in the create form --- src/infra/discord/commands/announcements.ts | 27 +++++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts index 81c9328..bb49e35 100644 --- a/src/infra/discord/commands/announcements.ts +++ b/src/infra/discord/commands/announcements.ts @@ -3,6 +3,7 @@ import { InteractionContextType, LabelBuilder, ModalBuilder, + RoleSelectMenuBuilder, SlashCommandBuilder, TextInputBuilder, TextInputStyle, @@ -81,8 +82,8 @@ const data = new SlashCommandBuilder() .addBooleanOption((o) => o.setName('embed').setDescription('Post as an embed (default yes)'), ) - .addRoleOption((o) => - o.setName('mention').setDescription('Role to mention'), + .addBooleanOption((o) => + o.setName('everyone').setDescription('Mention @everyone'), ), ) .addSubcommand((sub) => @@ -141,8 +142,8 @@ export function announcementCommands( return; } - const [channelId = '', embed, role = '-'] = args; - const everyone = role === interaction.guildId; + const [channelId = '', embed, everyone] = args; + const roles = interaction.fields.getSelectedRoles('mentions'); const announcement = await announcements.draft( toActor(interaction.member), { @@ -150,8 +151,8 @@ export function announcementCommands( title: interaction.fields.getTextInputValue('title'), content: interaction.fields.getTextInputValue('content'), embed: embed === '1', - mentionRoleIds: role === '-' || everyone ? [] : [role], - mentionEveryone: everyone, + mentionRoleIds: roles ? [...roles.keys()] : [], + mentionEveryone: everyone === '1', }, ); @@ -203,8 +204,9 @@ export function announcementCommands( execute: bySubcommand({ create: async (interaction) => { const channel = interaction.options.getChannel('channel', true); - const role = interaction.options.getRole('mention'); const embed = interaction.options.getBoolean('embed') ?? true; + const everyone = + interaction.options.getBoolean('everyone') ?? false; await interaction.showModal( contentModal( @@ -212,9 +214,18 @@ export function announcementCommands( 'announcements:create', channel.id, embed ? 1 : 0, - role?.id ?? '-', + everyone ? 1 : 0, ), 'New announcement', + ).addLabelComponents( + new LabelBuilder() + .setLabel('Mention roles') + .setRoleSelectMenuComponent( + new RoleSelectMenuBuilder() + .setCustomId('mentions') + .setRequired(false) + .setMaxValues(25), + ), ), ); }, From 84cc1965c60dd6757beeebdb8a4741c06faa8d73 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:16:40 +0200 Subject: [PATCH 040/199] feat(announcements): choose @everyone in the create form instead of a command option --- src/infra/discord/commands/announcements.ts | 27 +++++++++++---------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts index bb49e35..70a1635 100644 --- a/src/infra/discord/commands/announcements.ts +++ b/src/infra/discord/commands/announcements.ts @@ -4,6 +4,7 @@ import { LabelBuilder, ModalBuilder, RoleSelectMenuBuilder, + StringSelectMenuBuilder, SlashCommandBuilder, TextInputBuilder, TextInputStyle, @@ -81,9 +82,6 @@ const data = new SlashCommandBuilder() ) .addBooleanOption((o) => o.setName('embed').setDescription('Post as an embed (default yes)'), - ) - .addBooleanOption((o) => - o.setName('everyone').setDescription('Mention @everyone'), ), ) .addSubcommand((sub) => @@ -142,7 +140,7 @@ export function announcementCommands( return; } - const [channelId = '', embed, everyone] = args; + const [channelId = '', embed] = args; const roles = interaction.fields.getSelectedRoles('mentions'); const announcement = await announcements.draft( toActor(interaction.member), @@ -152,7 +150,9 @@ export function announcementCommands( content: interaction.fields.getTextInputValue('content'), embed: embed === '1', mentionRoleIds: roles ? [...roles.keys()] : [], - mentionEveryone: everyone === '1', + mentionEveryone: interaction.fields + .getStringSelectValues('everyone') + .includes('everyone'), }, ); @@ -205,17 +205,10 @@ export function announcementCommands( create: async (interaction) => { const channel = interaction.options.getChannel('channel', true); const embed = interaction.options.getBoolean('embed') ?? true; - const everyone = - interaction.options.getBoolean('everyone') ?? false; await interaction.showModal( contentModal( - controlId( - 'announcements:create', - channel.id, - embed ? 1 : 0, - everyone ? 1 : 0, - ), + controlId('announcements:create', channel.id, embed ? 1 : 0), 'New announcement', ).addLabelComponents( new LabelBuilder() @@ -226,6 +219,14 @@ export function announcementCommands( .setRequired(false) .setMaxValues(25), ), + new LabelBuilder() + .setLabel('Mention everyone') + .setStringSelectMenuComponent( + new StringSelectMenuBuilder() + .setCustomId('everyone') + .setRequired(false) + .addOptions({ label: '@everyone', value: 'everyone' }), + ), ), ); }, From 35af563122b4760af09a0b4743a7a79cd4456053 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:32:59 +0200 Subject: [PATCH 041/199] refactor(web): drop the unconnected Discord OAuth adapter --- README.md | 4 +- src/infra/web/auth.ts | 76 +----------------------------------- tests/infra/web/auth.test.ts | 49 ----------------------- 3 files changed, 2 insertions(+), 127 deletions(-) delete mode 100644 tests/infra/web/auth.test.ts diff --git a/README.md b/README.md index 9f8d6b4..c1c3ed3 100644 --- a/README.md +++ b/README.md @@ -81,9 +81,7 @@ unless the bot may mention everyone. **There is no sign-in yet.** Whoever can open the page acts as a server administrator, which is why it listens on `127.0.0.1` only (Compose publishes it on the host's loopback). Reach it from elsewhere through an SSH tunnel, not -a public proxy. Sign-in plugs in through the `Authenticator` port; -`createDiscordOAuth` in `src/infra/web/auth.ts` is a Discord OAuth2 adapter -that is written and tested but not connected yet. +a public proxy. Sign-in plugs in through the `Authenticator` port. ## Permissions diff --git a/src/infra/web/auth.ts b/src/infra/web/auth.ts index 0e2d401..8436088 100644 --- a/src/infra/web/auth.ts +++ b/src/infra/web/auth.ts @@ -1,80 +1,6 @@ -import { z } from 'zod'; -import type { Authenticator, Directory } from '~/core/ports'; +import type { Authenticator } from '~/core/ports'; import type { Actor } from '~/domain'; export function localOperator(actor: () => Promise): Authenticator { return { authenticate: actor }; } - -const tokenResponse = z.object({ - access_token: z.string(), - token_type: z.string(), -}); -const userResponse = z.object({ id: z.string() }); -const discordApi = 'https://discord.com/api/v10'; - -export type DiscordOAuthOptions = { - clientId: string; - clientSecret: string; - redirectUri: string; - guildId: string; - directory: Directory; - fetch?: typeof fetch; -}; - -export function createDiscordOAuth(options: DiscordOAuthOptions) { - const request = options.fetch ?? fetch; - - return { - authorizeUrl: (state: string) => { - const url = new URL('https://discord.com/oauth2/authorize'); - - url.search = new URLSearchParams({ - client_id: options.clientId, - redirect_uri: options.redirectUri, - response_type: 'code', - scope: 'identify', - state, - }).toString(); - - return url.href; - }, - actorFor: async (code: string): Promise => { - const token = await request(`${discordApi}/oauth2/token`, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - client_id: options.clientId, - client_secret: options.clientSecret, - grant_type: 'authorization_code', - code, - redirect_uri: options.redirectUri, - }), - signal: AbortSignal.timeout(10_000), - }); - const parsedToken = tokenResponse.safeParse( - await token.json().catch(() => null), - ); - - if (!token.ok || !parsedToken.success) { - return undefined; - } - - const me = await request(`${discordApi}/users/@me`, { - headers: { - Authorization: `${parsedToken.data.token_type} ${parsedToken.data.access_token}`, - }, - signal: AbortSignal.timeout(10_000), - }); - const parsedUser = userResponse.safeParse( - await me.json().catch(() => null), - ); - - if (!me.ok || !parsedUser.success) { - return undefined; - } - - return options.directory.member(options.guildId, parsedUser.data.id); - }, - }; -} diff --git a/tests/infra/web/auth.test.ts b/tests/infra/web/auth.test.ts deleted file mode 100644 index b9d2fe1..0000000 --- a/tests/infra/web/auth.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { createDiscordOAuth } from '~/infra/web'; -import { actor, fakeDirectory } from '../../fakes'; - -describe('Discord OAuth adapter', () => { - it('builds an authorize URL and turns a code into a guild actor', async () => { - const directory = fakeDirectory(); - const member = actor({ userId: '42' }); - - directory.member.mockResolvedValue(member); - - const fetch = vi - .fn() - .mockResolvedValueOnce( - Response.json({ access_token: 't', token_type: 'Bearer' }), - ) - .mockResolvedValueOnce(Response.json({ id: '42' })); - const oauth = createDiscordOAuth({ - clientId: 'c', - clientSecret: 's', - redirectUri: 'http://localhost/cb', - guildId: 'g', - directory, - fetch, - }); - - expect(oauth.authorizeUrl('state')).toContain('scope=identify'); - expect(await oauth.actorFor('code')).toBe(member); - expect(directory.member).toHaveBeenCalledWith('g', '42'); - }); - - it('returns nothing when Discord rejects the code', async () => { - const fetch = vi - .fn() - .mockResolvedValue( - Response.json({ error: 'invalid_grant' }, { status: 400 }), - ); - const oauth = createDiscordOAuth({ - clientId: 'c', - clientSecret: 's', - redirectUri: 'r', - guildId: 'g', - directory: fakeDirectory(), - fetch, - }); - - expect(await oauth.actorFor('bad')).toBeUndefined(); - }); -}); From 291100d55b7916bc2ef44c193416f733bf9a6a06 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:37:31 +0200 Subject: [PATCH 042/199] refactor(settings): drop the per-server timezone in favour of DEFAULT_TIMEZONE --- .env.example | 1 - README.md | 9 +- drizzle.config.ts | 6 +- drizzle/0002_drop_guild_settings.sql | 1 + drizzle/meta/0002_snapshot.json | 1717 +++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/app.ts | 29 +- src/core/ports/index.ts | 1 - src/core/ports/settings.ts | 4 - src/core/services/announcements.ts | 8 +- src/core/services/birthdays.ts | 20 +- src/core/services/events.ts | 4 +- src/core/services/index.ts | 1 - src/core/services/movies.ts | 17 +- src/core/services/polls.ts | 6 +- src/core/services/redmine.ts | 19 +- src/core/services/reminders.ts | 4 +- src/core/services/settings.ts | 25 - src/infra/db/index.ts | 1 - src/infra/db/settings/repo.ts | 40 - src/infra/discord/commands/index.ts | 1 - src/infra/discord/commands/settings.ts | 46 - src/infra/web/app.ts | 42 - src/infra/web/layout.ts | 1 - tests/core/services/announcements.test.ts | 2 +- tests/core/services/birthdays.test.ts | 4 +- tests/core/services/events.test.ts | 2 +- tests/core/services/movies.test.ts | 2 +- tests/core/services/polls.test.ts | 2 +- tests/core/services/redmine.test.ts | 3 +- tests/core/services/reminders.test.ts | 2 +- tests/infra/web/app.test.ts | 21 +- 32 files changed, 1780 insertions(+), 268 deletions(-) create mode 100644 drizzle/0002_drop_guild_settings.sql create mode 100644 drizzle/meta/0002_snapshot.json delete mode 100644 src/core/ports/settings.ts delete mode 100644 src/core/services/settings.ts delete mode 100644 src/infra/db/settings/repo.ts delete mode 100644 src/infra/discord/commands/settings.ts diff --git a/.env.example b/.env.example index bcba311..60b04b7 100644 --- a/.env.example +++ b/.env.example @@ -8,7 +8,6 @@ DISCORD_APPLICATION_ID= DISCORD_GUILD_ID= LOG_LEVEL=info -# Fallback when a server has not run /settings timezone. DEFAULT_TIMEZONE=Europe/Tallinn # Legacy reaction role panel. Leave ROLE_SELECTION_CHANNEL_ID empty to disable. diff --git a/README.md b/README.md index c1c3ed3..e30e428 100644 --- a/README.md +++ b/README.md @@ -44,9 +44,9 @@ All settings come from environment variables (see `.env.example`), validated at startup. Only `DISCORD_TOKEN` and `DATABASE_URL` are required; each optional feature asks only for what it needs. -Precedence: settings changed at runtime with bot commands (server timezone, -birthday channel) live in the database and win over environment defaults -(`DEFAULT_TIMEZONE`). Everything else is environment-only. +Times are read and shown in `DEFAULT_TIMEZONE`. The birthday channel is set +with `/birthday settings` and lives in the database; everything else is +environment-only. ## Commands @@ -62,7 +62,6 @@ birthday channel) live in the database and win over environment defaults | `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | | `/redmine …` | see [Redmine](#redmine) | | `/permissions grant/revoke/list/check` | `permissions:manage` | -| `/settings timezone` | viewing is open; changing needs `settings:manage` | ## Web UI @@ -72,7 +71,7 @@ Set `WEB_PORT` (and `DISCORD_GUILD_ID`) to start a small web UI next to the bot: - **PSAs:** write an announcement, choose one channel and exactly which roles (or @everyone) it mentions, preview it as Discord will show it, then publish now, schedule it, or save a draft. -- **Events, polls, permissions and the server timezone.** +- **Events, polls and permissions.** The UI uses the same services as the slash commands, so the same rules apply: it only posts where the bot can post, and only mentionable roles can be pinged diff --git a/drizzle.config.ts b/drizzle.config.ts index 62e2463..e5322b4 100644 --- a/drizzle.config.ts +++ b/drizzle.config.ts @@ -2,10 +2,6 @@ import { defineConfig } from 'drizzle-kit'; export default defineConfig({ dialect: 'postgresql', - schema: [ - './src/infra/db/**/model.ts', - './src/infra/db/settings/repo.ts', - './src/features/*/schema.ts', - ], + schema: './src/infra/db/**/model.ts', out: './drizzle', }); diff --git a/drizzle/0002_drop_guild_settings.sql b/drizzle/0002_drop_guild_settings.sql new file mode 100644 index 0000000..28ef84e --- /dev/null +++ b/drizzle/0002_drop_guild_settings.sql @@ -0,0 +1 @@ +DROP TABLE "guild_settings" CASCADE; \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..2e42fd6 --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,1717 @@ +{ + "id": "6b7a9249-b1fe-49c6-b481-737e127b7a0d", + "prevId": "cf5229cd-07d2-448d-b523-395d91e5660c", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embed": { + "name": "embed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_jobs": { + "name": "scheduled_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "job_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "scheduled_jobs_due_idx": { + "name": "scheduled_jobs_due_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_jobs_lease_idx": { + "name": "scheduled_jobs_lease_idx", + "columns": [ + { + "expression": "locked_until", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "scheduled_jobs_key_unique": { + "name": "scheduled_jobs_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_links": { + "name": "redmine_links", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "redmine_user_id": { + "name": "redmine_user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redmine_login": { + "name": "redmine_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "linked_at": { + "name": "linked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "publishing", + "published", + "cancelled", + "failed" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.job_status": { + "name": "job_status", + "schema": "public", + "values": [ + "pending", + "running", + "done", + "failed", + "cancelled" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 9121daa..a4902d8 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1794764495086, "tag": "0001_announcement_mentions", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1794821716333, + "tag": "0002_drop_guild_settings", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index 01e5eec..bf7194d 100644 --- a/src/app.ts +++ b/src/app.ts @@ -16,7 +16,6 @@ import { reminderCommands, roleCommands, permissionCommands, - settingsCommands, } from '~/infra/discord'; import { createAnnouncementService, @@ -29,7 +28,6 @@ import { createPermissionService, createReminderService, createRoleService, - createSettingsService, type LegacyPanel, } from '~/core/services'; import type { AppContext, Feature, Registry } from '~/infra/discord'; @@ -55,7 +53,6 @@ import { createPollRepository, createReminderRepository, createRolePanelRepository, - createSettingsRepository, runMigrations, } from '~/infra/db'; import { createSecretBox } from '~/infra/crypto'; @@ -81,7 +78,7 @@ function legacyPanel(config: Config): LegacyPanel | undefined { type RedmineDeps = Omit< Parameters[0], - 'baseUrl' | 'connect' | 'service' | 'tracker' | 'secrets' | 'defaultTimezone' + 'baseUrl' | 'connect' | 'service' | 'tracker' | 'secrets' > & { db: Db }; function createRedmine(config: Config, { db, ...deps }: RedmineDeps) { @@ -109,7 +106,6 @@ function createRedmine(config: Config, { db, ...deps }: RedmineDeps) { : connect(config.REDMINE_API_KEY), tracker: createTrackerRepository(db), secrets: createSecretBox(config.CREDENTIAL_ENCRYPTION_KEY), - defaultTimezone: config.DEFAULT_TIMEZONE, }); } @@ -128,11 +124,7 @@ export function compose(config: Config, log: Logger) { log: log.child({ service: 'roles' }), legacy: legacyPanel(config), }); - const settings = createSettingsService({ - settings: createSettingsRepository(database.db), - authz, - defaultTimezone: config.DEFAULT_TIMEZONE, - }); + const timezone = config.DEFAULT_TIMEZONE; const scheduler = createJobQueue(database.db); const reminders = createReminderService({ reminders: createReminderRepository(database.db), @@ -140,7 +132,7 @@ export function compose(config: Config, log: Logger) { messenger, directory, authz, - timezone: (guildId) => settings.timezone(guildId), + timezone, }); const announcements = createAnnouncementService({ announcements: createAnnouncementRepository(database.db), @@ -150,7 +142,7 @@ export function compose(config: Config, log: Logger) { authz, log: log.child({ service: 'announcements' }), clock: systemClock, - timezone: (guildId) => settings.timezone(guildId), + timezone, }); const events = createEventService({ events: createEventRepository(database.db), @@ -160,7 +152,7 @@ export function compose(config: Config, log: Logger) { directory, authz, log: log.child({ service: 'events' }), - timezone: (guildId) => settings.timezone(guildId), + timezone, }); const polls = createPollService({ polls: createPollRepository(database.db), @@ -169,14 +161,14 @@ export function compose(config: Config, log: Logger) { directory, authz, log: log.child({ service: 'polls' }), - timezone: (guildId) => settings.timezone(guildId), + timezone, }); const movies = createMovieService({ movies: createMovieRepository(database.db), polls, events, authz, - timezone: (guildId) => settings.timezone(guildId), + timezone, }); const birthdays = createBirthdayService({ birthdays: createBirthdayRepository(database.db), @@ -185,7 +177,7 @@ export function compose(config: Config, log: Logger) { directory, authz, log: log.child({ service: 'birthdays' }), - timezone: (guildId) => settings.timezone(guildId), + timezone, }); const jobs: Array> = [ ...birthdays.jobs, @@ -204,7 +196,6 @@ export function compose(config: Config, log: Logger) { const features: Feature[] = [ roleCommands(roles), permissionCommands(permissions), - settingsCommands(settings), reminderCommands(reminders), announcementCommands(announcements), eventCommands(events), @@ -219,7 +210,7 @@ export function compose(config: Config, log: Logger) { messenger, authz, log, - timezone: (guildId) => settings.timezone(guildId), + timezone, }); if (redmine) { @@ -246,7 +237,7 @@ export function compose(config: Config, log: Logger) { registry, directory, jobs: runnerJobs, - web: { announcements, events, polls, permissions, settings }, + web: { announcements, events, polls, permissions }, }; } diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 29d4633..204c3a8 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -4,7 +4,6 @@ export * from './clock'; export type * from './logger'; export type * from './scheduler'; export type * from './secrets'; -export type * from './settings'; export type * from './roles'; export type * from './reminders'; export type * from './announcements'; diff --git a/src/core/ports/settings.ts b/src/core/ports/settings.ts deleted file mode 100644 index 6144359..0000000 --- a/src/core/ports/settings.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type SettingsRepository = { - timezone: (guildId: string) => Promise; - setTimezone: (guildId: string, timezone: string) => Promise; -}; diff --git a/src/core/services/announcements.ts b/src/core/services/announcements.ts index 42affce..f7b1387 100644 --- a/src/core/services/announcements.ts +++ b/src/core/services/announcements.ts @@ -87,7 +87,7 @@ type Deps = { authz: Authorizer; log: Logger; clock: Clock; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createAnnouncementService(deps: Deps) { @@ -299,11 +299,7 @@ export function createAnnouncementService(deps: Deps) { 'announcement:schedule', async (actor, id: number, when: string) => { const announcement = await requireOwnGuild(actor, id); - const runAt = parseFutureWhen( - when, - await deps.timezone(actor.guildId), - clock.now(), - ); + const runAt = parseFutureWhen(when, deps.timezone, clock.now()); await checkTargets(actor, announcement); diff --git a/src/core/services/birthdays.ts b/src/core/services/birthdays.ts index 5598a05..11e76c2 100644 --- a/src/core/services/birthdays.ts +++ b/src/core/services/birthdays.ts @@ -50,7 +50,7 @@ type Deps = { directory: Directory; authz: Authorizer; log: Logger; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createBirthdayService(deps: Deps) { @@ -84,8 +84,7 @@ export function createBirthdayService(deps: Deps) { roleId: string, userIds: string[], ) => { - const zone = await timezone(settings.guildId); - const midnight = nextDailyRun(zone, 0); + const midnight = nextDailyRun(timezone, 0); await sequential(userIds, async (userId) => { try { @@ -142,8 +141,7 @@ export function createBirthdayService(deps: Deps) { return null; } - const zone = await timezone(guildId); - const today = calendarDay(new Date(), zone); + const today = calendarDay(new Date(), timezone); const userIds = await birthdays.claim(guildId, today); if (userIds.length > 0) { @@ -154,7 +152,7 @@ export function createBirthdayService(deps: Deps) { } } - return { rescheduleAt: nextDailyRun(zone, settings.hour) }; + return { rescheduleAt: nextDailyRun(timezone, settings.hour) }; }, }); @@ -214,10 +212,7 @@ export function createBirthdayService(deps: Deps) { : undefined; }, upcoming: async (guildId: string) => - birthdays.upcoming( - guildId, - calendarDay(new Date(), await timezone(guildId)), - ), + birthdays.upcoming(guildId, calendarDay(new Date(), timezone)), configure: guard( authz, 'birthday:manage', @@ -230,14 +225,13 @@ export function createBirthdayService(deps: Deps) { } const settings = await resolveSettings(actor, change); - const zone = await timezone(actor.guildId); await birthdays.saveSettings(settings); await scheduler.schedule( dailyJob, { guildId: actor.guildId }, { - runAt: nextDailyRun(zone, settings.hour), + runAt: nextDailyRun(timezone, settings.hour), key: dailyKey(actor.guildId), }, ); @@ -248,7 +242,7 @@ export function createBirthdayService(deps: Deps) { const role = settings.roleId === null ? '' : ' with a role for the day'; - return `Birthdays are announced in ${channelMention(settings.channelId)} at ${settings.hour}:00 (${zone})${role}.`; + return `Birthdays are announced in ${channelMention(settings.channelId)} at ${settings.hour}:00 (${timezone})${role}.`; }, ), }; diff --git a/src/core/services/events.ts b/src/core/services/events.ts index bdf0913..eb38f18 100644 --- a/src/core/services/events.ts +++ b/src/core/services/events.ts @@ -174,7 +174,7 @@ type Deps = { directory: Directory; authz: Authorizer; log: Logger; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createEventService(deps: Deps) { @@ -365,7 +365,7 @@ export function createEventService(deps: Deps) { const timezone = request.timezone === undefined - ? await deps.timezone(actor.guildId) + ? deps.timezone : requireZone(request.timezone); const event = await publish( { diff --git a/src/core/services/index.ts b/src/core/services/index.ts index c527a82..2890b58 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -1,7 +1,6 @@ export * from './authorization'; export * from './guard'; export * from './jobs'; -export * from './settings'; export * from './roles'; export * from './reminders'; export * from './announcements'; diff --git a/src/core/services/movies.ts b/src/core/services/movies.ts index 81f9ec7..ecb3db7 100644 --- a/src/core/services/movies.ts +++ b/src/core/services/movies.ts @@ -25,7 +25,7 @@ type Deps = { polls: PollService; events: EventService; authz: Authorizer; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createMovieService(deps: Deps) { @@ -106,10 +106,7 @@ export function createMovieService(deps: Deps) { ); } - const closesAt = parseFutureWhen( - request.closes ?? '2d', - await timezone(actor.guildId), - ); + const closesAt = parseFutureWhen(request.closes ?? '2d', timezone); return polls.publish(actor, { guildId: actor.guildId, @@ -127,15 +124,14 @@ export function createMovieService(deps: Deps) { ), night: guard(authz, 'movie:manage', async (actor, night: MovieNight) => { const { movie, pollId } = await pick(actor, night.movieId); - const zone = await timezone(actor.guildId); - const startsAt = parseFutureWhen(night.start, zone); + const startsAt = parseFutureWhen(night.start, timezone); const event = await events.publish(actor, { guildId: actor.guildId, title: `🎬 Movie night: ${movieLabel(movie)}`.slice(0, 200), description: movie.note, startsAt, endsAt: null, - timezone: zone, + timezone, location: night.location ?? null, organizerId: actor.userId, channelId: night.channelId, @@ -159,10 +155,7 @@ export function createMovieService(deps: Deps) { 'movie:manage', async (actor, id: number, date?: string) => { const movie = await movies.find(actor.guildId, id); - const at = - date === undefined - ? new Date() - : parseWhen(date, await timezone(actor.guildId)); + const at = date === undefined ? new Date() : parseWhen(date, timezone); await movies.markWatched(actor.guildId, movie.id, at); diff --git a/src/core/services/polls.ts b/src/core/services/polls.ts index caf22ef..a2e660d 100644 --- a/src/core/services/polls.ts +++ b/src/core/services/polls.ts @@ -120,7 +120,7 @@ type Deps = { directory: Directory; authz: Authorizer; log: Logger; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createPollService(deps: Deps) { @@ -229,8 +229,6 @@ export function createPollService(deps: Deps) { create: async (actor: Actor, request: PollRequest) => { await authz.require(actor, 'poll:create'); - const zone = await deps.timezone(actor.guildId); - return publish(actor, { guildId: actor.guildId, channelId: request.channelId, @@ -243,7 +241,7 @@ export function createPollService(deps: Deps) { closesAt: request.closes === undefined ? null - : parseFutureWhen(request.closes, zone), + : parseFutureWhen(request.closes, deps.timezone), }); }, vote, diff --git a/src/core/services/redmine.ts b/src/core/services/redmine.ts index 52af81b..ca2afd4 100644 --- a/src/core/services/redmine.ts +++ b/src/core/services/redmine.ts @@ -52,8 +52,7 @@ type Deps = { messenger: Messenger; authz: Authorizer; log: Logger; - defaultTimezone: string; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createRedmineService(deps: Deps) { @@ -209,9 +208,8 @@ export function createRedmineService(deps: Deps) { payload: z.object({}), handle: async () => { const client = requireService(); - const zone = deps.defaultTimezone; const tomorrow = formatCalendarDay( - addCalendarDays(calendarDay(new Date(), zone), 1), + addCalendarDays(calendarDay(new Date(), deps.timezone), 1), ); await forEachSubscription(async (subscription) => { @@ -235,7 +233,7 @@ export function createRedmineService(deps: Deps) { ); }); - return { rescheduleAt: nextDailyRun(zone, deadlineHour) }; + return { rescheduleAt: nextDailyRun(deps.timezone, deadlineHour) }; }, }); @@ -272,7 +270,7 @@ export function createRedmineService(deps: Deps) { deadlineJob, {}, { - runAt: nextDailyRun(deps.defaultTimezone, deadlineHour), + runAt: nextDailyRun(deps.timezone, deadlineHour), key: 'redmine:deadlines', }, ); @@ -389,8 +387,11 @@ export function createRedmineService(deps: Deps) { throw new UserError(`#${issue.id} has no due date.`); } - const timezone = await deps.timezone(actor.guildId); - const runAt = zonedTime(addCalendarDays(due, -daysBefore), 9, timezone); + const runAt = zonedTime( + addCalendarDays(due, -daysBefore), + 9, + deps.timezone, + ); if (runAt.getTime() <= Date.now()) { throw new UserError('That reminder time has already passed.'); @@ -403,7 +404,7 @@ export function createRedmineService(deps: Deps) { message: `Redmine #${issue.id} "${issue.subject}" is due ${issue.due_date ?? ''}: ${issueUrl(issue.id)}`, runAt, recurrence: null, - timezone, + timezone: deps.timezone, }); }, subscribe: guard( diff --git a/src/core/services/reminders.ts b/src/core/services/reminders.ts index db212c7..7869e20 100644 --- a/src/core/services/reminders.ts +++ b/src/core/services/reminders.ts @@ -38,7 +38,7 @@ type Deps = { messenger: Messenger; directory: Directory; authz: Authorizer; - timezone: (guildId: string) => Promise; + timezone: string; }; export function createReminderService(deps: Deps) { @@ -145,7 +145,7 @@ export function createReminderService(deps: Deps) { const zone = request.timezone === undefined - ? await timezone(actor.guildId) + ? timezone : requireZone(request.timezone); const recurrence: Recurrence | null = recurrences.find((r) => r === request.repeat) ?? null; diff --git a/src/core/services/settings.ts b/src/core/services/settings.ts deleted file mode 100644 index 0d8c397..0000000 --- a/src/core/services/settings.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { requireZone } from '~/domain'; -import type { Authorizer, SettingsRepository } from '~/core/ports'; -import { guard } from './guard'; - -type Deps = { - settings: SettingsRepository; - authz: Authorizer; - defaultTimezone: string; -}; - -export function createSettingsService({ - settings, - authz, - defaultTimezone, -}: Deps) { - return { - timezone: async (guildId: string) => - (await settings.timezone(guildId)) ?? defaultTimezone, - setTimezone: guard(authz, 'settings:manage', (actor, zone: string) => - settings.setTimezone(actor.guildId, requireZone(zone)), - ), - }; -} - -export type SettingsService = ReturnType; diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index f6c1d43..26727b6 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -3,7 +3,6 @@ export * from './jobs/model'; export * from './jobs/repo'; export * from './permissions/model'; export * from './permissions/repo'; -export * from './settings/repo'; export * from './roles/model'; export * from './roles/repo'; export * from './reminders/model'; diff --git a/src/infra/db/settings/repo.ts b/src/infra/db/settings/repo.ts deleted file mode 100644 index 910ba68..0000000 --- a/src/infra/db/settings/repo.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { SettingsRepository } from '~/core/ports'; -import { eq } from 'drizzle-orm'; -import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -import type { Db } from '../client'; - -export const guildSettings = pgTable('guild_settings', { - guildId: text('guild_id').primaryKey(), - timezone: text('timezone'), - updatedAt: timestamp('updated_at', { withTimezone: true }) - .notNull() - .defaultNow(), -}); - -export async function setGuildTimezone( - db: Db, - guildId: string, - timezone: string, -): Promise { - await db - .insert(guildSettings) - .values({ guildId, timezone }) - .onConflictDoUpdate({ - target: guildSettings.guildId, - set: { timezone, updatedAt: new Date() }, - }); -} - -export function createSettingsRepository(db: Db): SettingsRepository { - return { - timezone: async (guildId) => { - const [row] = await db - .select({ timezone: guildSettings.timezone }) - .from(guildSettings) - .where(eq(guildSettings.guildId, guildId)); - - return row?.timezone ?? undefined; - }, - setTimezone: (guildId, timezone) => setGuildTimezone(db, guildId, timezone), - }; -} diff --git a/src/infra/discord/commands/index.ts b/src/infra/discord/commands/index.ts index d8da0f0..d8eff3d 100644 --- a/src/infra/discord/commands/index.ts +++ b/src/infra/discord/commands/index.ts @@ -1,5 +1,4 @@ export * from './permissions'; -export * from './settings'; export * from './roles'; export * from './reminders'; export * from './announcements'; diff --git a/src/infra/discord/commands/settings.ts b/src/infra/discord/commands/settings.ts deleted file mode 100644 index d90d934..0000000 --- a/src/infra/discord/commands/settings.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { InteractionContextType, SlashCommandBuilder } from 'discord.js'; -import type { SettingsService } from '~/core/services'; -import { toActor } from '../actor'; -import { bySubcommand } from '../define'; -import type { Feature } from '../module'; -import { respond } from '../router'; - -const data = new SlashCommandBuilder() - .setName('settings') - .setDescription('Server-wide bot settings') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('timezone') - .setDescription('View or set the server timezone used for schedules') - .addStringOption((o) => - o.setName('zone').setDescription('IANA timezone, e.g. Europe/Tallinn'), - ), - ); - -export function settingsCommands(settings: SettingsService): Feature { - return { - name: 'settings', - permissions: [ - { id: 'settings:manage', description: 'Change server-wide bot settings' }, - ], - commands: [ - { - data: data.toJSON(), - execute: bySubcommand({ - timezone: async (interaction) => { - const zone = interaction.options.getString('zone'); - - if (zone !== null) { - await settings.setTimezone(toActor(interaction.member), zone); - } - - const current = await settings.timezone(interaction.guildId); - - await respond(interaction, `Server timezone: **${current}**`); - }, - }), - }, - ], - }; -} diff --git a/src/infra/web/app.ts b/src/infra/web/app.ts index 5d7a02e..2024163 100644 --- a/src/infra/web/app.ts +++ b/src/infra/web/app.ts @@ -11,7 +11,6 @@ import type { EventService, PermissionService, PollService, - SettingsService, } from '~/core/services'; import { UserError, type Actor, type RoleInfo } from '~/domain'; import { html, raw, type Html } from '~/lib'; @@ -23,7 +22,6 @@ export type WebServices = { events: EventService; polls: PollService; permissions: PermissionService; - settings: SettingsService; }; type Deps = { @@ -654,46 +652,6 @@ export function createWebApp(deps: Deps) { }); }, }, - { - method: 'GET', - pattern: /^\/settings$/, - handle: async (context) => { - const zone = await services.settings.timezone(deps.guildId); - const now = new Date().toLocaleString('en-GB', { timeZone: zone }); - - return { - body: page( - 'Settings', - context.path, - context.flash, - html` - ${context.csrf} - -
- -

- Times you type in this UI and in Discord use this timezone. It - is now ${now} there. -

`, - ), - }; - }, - }, - { - method: 'POST', - pattern: /^\/settings$/, - handle: async (context) => { - await services.settings.setTimezone( - context.actor, - field(context.form, 'timezone') ?? '', - ); - - return redirect('/settings', { notice: 'Saved.' }); - }, - }, ]; const readForm = (request: IncomingMessage): Promise
=> diff --git a/src/infra/web/layout.ts b/src/infra/web/layout.ts index aa7a6e2..65d7bbe 100644 --- a/src/infra/web/layout.ts +++ b/src/infra/web/layout.ts @@ -28,7 +28,6 @@ const sections = [ ['/events', 'Events'], ['/polls', 'Polls'], ['/permissions', 'Permissions'], - ['/settings', 'Settings'], ] as const; export type Flash = { notice?: string; error?: string }; diff --git a/tests/core/services/announcements.test.ts b/tests/core/services/announcements.test.ts index 2586ae7..3e2079b 100644 --- a/tests/core/services/announcements.test.ts +++ b/tests/core/services/announcements.test.ts @@ -76,7 +76,7 @@ describe.skipIf(noDatabase)('announcement service', () => { authz: allowAll, log: silentLog, clock: { now: () => options.now ?? new Date() }, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); return { diff --git a/tests/core/services/birthdays.test.ts b/tests/core/services/birthdays.test.ts index 7004a68..49d4270 100644 --- a/tests/core/services/birthdays.test.ts +++ b/tests/core/services/birthdays.test.ts @@ -151,7 +151,7 @@ describe.skipIf(noDatabase)('birthdays', () => { directory: fakeDirectory(), authz: allowAll, log: silentLog, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); const admin = actor({ guildId: snowflake(), userId: snowflake() }); const now = calendarDay(new Date(), 'Europe/Tallinn'); @@ -183,7 +183,7 @@ describe.skipIf(noDatabase)('birthdays', () => { directory: fakeDirectory(), authz: allowAll, log: silentLog, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); const owner = actor({ guildId: snowflake(), userId: snowflake() }); diff --git a/tests/core/services/events.test.ts b/tests/core/services/events.test.ts index 9081b0e..c959fe7 100644 --- a/tests/core/services/events.test.ts +++ b/tests/core/services/events.test.ts @@ -141,7 +141,7 @@ describe.skipIf(noDatabase)('event service', () => { directory: fakeDirectory(), authz: allowAll, log: silentLog, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); return { diff --git a/tests/core/services/movies.test.ts b/tests/core/services/movies.test.ts index 832b738..ddd3974 100644 --- a/tests/core/services/movies.test.ts +++ b/tests/core/services/movies.test.ts @@ -36,7 +36,7 @@ describe.skipIf(noDatabase)('movie service', () => { directory: fakeDirectory(), authz: allowAll, log: silentLog, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }; const pollRepository = createPollRepository(testDb()); const polls = createPollService({ ...shared, polls: pollRepository }); diff --git a/tests/core/services/polls.test.ts b/tests/core/services/polls.test.ts index 64bcca4..922df15 100644 --- a/tests/core/services/polls.test.ts +++ b/tests/core/services/polls.test.ts @@ -100,7 +100,7 @@ describe.skipIf(noDatabase)('poll service', () => { directory: fakeDirectory(), authz: allowAll, log: silentLog, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); return { diff --git a/tests/core/services/redmine.test.ts b/tests/core/services/redmine.test.ts index afcb799..71d00f8 100644 --- a/tests/core/services/redmine.test.ts +++ b/tests/core/services/redmine.test.ts @@ -58,8 +58,7 @@ describe.skipIf(noDatabase)('redmine service', () => { messenger, authz: allowAll, log: silentLog, - defaultTimezone: 'Europe/Tallinn', - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); return { service, messenger, connect, client }; diff --git a/tests/core/services/reminders.test.ts b/tests/core/services/reminders.test.ts index a7a4961..4ee0ee5 100644 --- a/tests/core/services/reminders.test.ts +++ b/tests/core/services/reminders.test.ts @@ -28,7 +28,7 @@ describe.skipIf(noDatabase)('reminder service', () => { messenger, directory: fakeDirectory(), authz, - timezone: async () => 'Europe/Tallinn', + timezone: 'Europe/Tallinn', }); const [deliver] = service.jobs; diff --git a/tests/infra/web/app.test.ts b/tests/infra/web/app.test.ts index 0ce7f9c..e577bb1 100644 --- a/tests/infra/web/app.test.ts +++ b/tests/infra/web/app.test.ts @@ -8,14 +8,12 @@ import { createEventService, createPermissionService, createPollService, - createSettingsService, } from '~/core/services'; import { createAnnouncementRepository, createEventRepository, createGrantRepository, createPollRepository, - createSettingsRepository, } from '~/infra/db'; import type { Permission, PermissionDefinition } from '~/domain'; import { createWebApp, localOperator } from '~/infra/web'; @@ -48,19 +46,13 @@ describe.skipIf(noDatabase)('web UI', () => { cancel: vi.fn(async () => undefined), }; const authz = createAuthorizer(createGrantRepository(db)); - const settings = createSettingsService({ - settings: createSettingsRepository(db), - authz, - defaultTimezone: 'Europe/Tallinn', - }); - const timezone = (id: string) => settings.timezone(id); const shared = { scheduler, messenger, directory, authz, log: silentLog, - timezone, + timezone: 'Europe/Tallinn', }; const app = createWebApp({ guildId, @@ -95,7 +87,6 @@ describe.skipIf(noDatabase)('web UI', () => { ], ]), }), - settings, }, }); @@ -215,23 +206,15 @@ describe.skipIf(noDatabase)('web UI', () => { ).toContain('error='); }); - it('creates polls and changes settings', async () => { + it('creates polls', async () => { const poll = await post('/polls', { csrf: await csrf('/polls'), question: 'Lunch?', options: 'Pizza\nSushi', channelId: 'general', }); - const timezone = await post('/settings', { - csrf: await csrf('/settings'), - timezone: 'Europe/Helsinki', - }); expect(poll.status).toBe(303); - expect(timezone.status).toBe(303); - expect(await (await fetch(`${base}/settings`)).text()).toContain( - 'Europe/Helsinki', - ); }); it('returns 404 for unknown pages', async () => { From 67bc5209a80788ade04fc8d20be4a524252ffc5b Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:42:52 +0200 Subject: [PATCH 043/199] refactor(redmine): keep only channel notifications on the service key Drops /redmine link and the per-user issue commands, the encrypted key store and CREDENTIAL_ENCRYPTION_KEY. REDMINE_API_KEY is now required when REDMINE_BASE_URL is set. --- .env.example | 9 +- README.md | 40 +- drizzle/0003_drop_redmine_links.sql | 1 + drizzle/meta/0003_snapshot.json | 1673 +++++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/app.ts | 65 +- src/config/env.ts | 31 +- src/core/ports/index.ts | 1 - src/core/ports/issues.ts | 24 +- src/core/ports/secrets.ts | 4 - src/core/services/redmine.ts | 259 +--- src/domain/issue.ts | 23 +- src/infra/crypto/index.ts | 1 - src/infra/crypto/secret-box.ts | 55 - src/infra/db/redmine/model.ts | 11 - src/infra/db/redmine/repo.ts | 44 +- src/infra/discord/commands/redmine.ts | 354 +----- src/infra/redmine/client.ts | 114 +- tests/app.test.ts | 2 +- tests/core/services/redmine.test.ts | 41 +- tests/infra/crypto/secret-box.test.ts | 30 - tests/infra/redmine/client.test.ts | 34 +- 22 files changed, 1827 insertions(+), 996 deletions(-) create mode 100644 drizzle/0003_drop_redmine_links.sql create mode 100644 drizzle/meta/0003_snapshot.json delete mode 100644 src/core/ports/secrets.ts delete mode 100644 src/infra/crypto/index.ts delete mode 100644 src/infra/crypto/secret-box.ts delete mode 100644 tests/infra/crypto/secret-box.test.ts diff --git a/.env.example b/.env.example index 60b04b7..0b3c6a4 100644 --- a/.env.example +++ b/.env.example @@ -16,15 +16,12 @@ TARKVARA_ROLE_ID= HELPDESK_ROLE_ID= KULTUUR_ROLE_ID= -# Redmine (optional). Setting REDMINE_BASE_URL enables the feature and then -# requires CREDENTIAL_ENCRYPTION_KEY. REDMINE_API_KEY is a restricted service -# account used only for channel notifications. -# Generate a key with: openssl rand -base64 32 +# Redmine channel notifications (optional). Setting REDMINE_BASE_URL enables +# them and requires REDMINE_API_KEY, a restricted service account. REDMINE_BASE_URL= REDMINE_API_KEY= -CREDENTIAL_ENCRYPTION_KEY= -# Web UI (PSAs, events, polls, permissions, settings). Off unless WEB_PORT is +# Web UI (PSAs, events, polls, permissions). Off unless WEB_PORT is # set; requires DISCORD_GUILD_ID. There is no sign-in yet: anyone who can reach # the port acts as an administrator, so keep it on localhost. WEB_PORT= diff --git a/README.md b/README.md index e30e428..3a42879 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ environment-only. | `/birthday set/remove/view/upcoming`, `/birthday settings` | everyone; settings need `birthday:manage` | | `/poll create/list/results/close/cancel` | create needs `poll:create`; creator or `poll:manage` manages | | `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | -| `/redmine …` | see [Redmine](#redmine) | +| `/redmine subscribe/unsubscribe` | `redmine:subscription:manage` | | `/permissions grant/revoke/list/check` | `permissions:manage` | ## Web UI @@ -97,8 +97,7 @@ The bot has its own action-based permissions (`event:create`, `poll:manage`, grant only permissions they hold themselves, only to roles below their own highest role, and never `permissions:manage`. - Permissions are checked again on every button and menu press, not just when - the message was created. Discord role hierarchy and Redmine's own - permissions always apply on top. + the message was created. Discord role hierarchy always applies on top. - Every grant and revoke is logged. ## Role panels and migrating from reactions @@ -124,27 +123,17 @@ above the bot cannot be put on a panel. ## Redmine -Set `REDMINE_BASE_URL` and `CREDENTIAL_ENCRYPTION_KEY` -(`openssl rand -base64 32`) to enable it. - -- Each member runs `/redmine link` and pastes their own Redmine API key - (_My account → API access key_; the REST API must be enabled by a Redmine - admin). The key is checked against Redmine, then stored encrypted - (AES-256-GCM) with a key that never enters the database. `/redmine unlink` - deletes it. -- Every user action (`projects`, `issues`, `issue view/create/update/assign/comment`) - uses that member's own key, so Redmine decides what they can see and change. - The bot permissions `redmine:issue:create`, `redmine:issue:update` and - `redmine:issue:assign` are an additional gate, never a bypass. -- `/redmine issue remind` sets a personal DM reminder before an issue's due date. -- **Notifications:** with `REDMINE_API_KEY` (a dedicated, restricted service - account) set, `/redmine subscribe project:` posts new issues, - status changes, assignments and comments to a channel, plus a daily "due - tomorrow" digest. The bot polls every two minutes and asks only for issues - updated since each subscription's stored checkpoint. Private issues and - private notes are never posted. Anyone who can read the channel sees the - updates, so subscribe only channels whose audience may see the project. - Standard Redmine has no webhooks, so polling is the mechanism. +Set `REDMINE_BASE_URL` and `REDMINE_API_KEY` (a dedicated, restricted service +account) to enable it. + +`/redmine subscribe project:` posts new issues, status changes, +assignments and comments to a channel, plus a daily "due tomorrow" digest +(`/redmine unsubscribe` stops it; both need `redmine:subscription:manage`). +The bot polls every two minutes and asks only for issues updated since each +subscription's stored checkpoint. Private issues and private notes are never +posted. Anyone who can read the channel sees the updates, so subscribe only +channels whose audience may see the project. Standard Redmine has no +webhooks, so polling is the mechanism. ## Development @@ -228,8 +217,7 @@ drizzle/ SQL migrations - **Messages are transport-neutral** (`domain/message.ts`): content, embeds, mentions and controls. `infra/discord/render.ts` turns them into discord.js payloads. -- **Cross-service use is explicit**: movies get the poll and event services, - Redmine gets the reminder service. +- **Cross-service use is explicit**: movies get the poll and event services. - **Scheduler:** jobs live in `scheduled_jobs`. The runner claims due jobs with `FOR UPDATE SKIP LOCKED` and a lease, so a crash mid-job leads to a retry after the lease expires. Delivery is at-least-once, and handlers diff --git a/drizzle/0003_drop_redmine_links.sql b/drizzle/0003_drop_redmine_links.sql new file mode 100644 index 0000000..6557b06 --- /dev/null +++ b/drizzle/0003_drop_redmine_links.sql @@ -0,0 +1 @@ +DROP TABLE "redmine_links" CASCADE; \ No newline at end of file diff --git a/drizzle/meta/0003_snapshot.json b/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..49fa6b6 --- /dev/null +++ b/drizzle/meta/0003_snapshot.json @@ -0,0 +1,1673 @@ +{ + "id": "bfc4bd90-b9f9-45da-b76c-d469c18c353b", + "prevId": "6b7a9249-b1fe-49c6-b481-737e127b7a0d", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embed": { + "name": "embed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_jobs": { + "name": "scheduled_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "job_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "scheduled_jobs_due_idx": { + "name": "scheduled_jobs_due_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_jobs_lease_idx": { + "name": "scheduled_jobs_lease_idx", + "columns": [ + { + "expression": "locked_until", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_jobs\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "scheduled_jobs_key_unique": { + "name": "scheduled_jobs_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "publishing", + "published", + "cancelled", + "failed" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.job_status": { + "name": "job_status", + "schema": "public", + "values": [ + "pending", + "running", + "done", + "failed", + "cancelled" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index a4902d8..3d6dea7 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1794821716333, "tag": "0002_drop_guild_settings", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1794822022773, + "tag": "0003_drop_redmine_links", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index bf7194d..a12d94a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -48,14 +48,12 @@ import { createBirthdayRepository, createGrantRepository, createTrackerRepository, - type Db, createMovieRepository, createPollRepository, createReminderRepository, createRolePanelRepository, runMigrations, } from '~/infra/db'; -import { createSecretBox } from '~/infra/crypto'; import { RedmineClient } from '~/infra/redmine'; function legacyPanel(config: Config): LegacyPanel | undefined { @@ -76,39 +74,6 @@ function legacyPanel(config: Config): LegacyPanel | undefined { return { channelId, roles }; } -type RedmineDeps = Omit< - Parameters[0], - 'baseUrl' | 'connect' | 'service' | 'tracker' | 'secrets' -> & { db: Db }; - -function createRedmine(config: Config, { db, ...deps }: RedmineDeps) { - const baseUrl = config.REDMINE_BASE_URL; - - if (baseUrl === undefined) { - return null; - } - - if (config.CREDENTIAL_ENCRYPTION_KEY === undefined) { - throw new Error( - 'CREDENTIAL_ENCRYPTION_KEY is required when REDMINE_BASE_URL is set', - ); - } - - const connect = (apiKey: string) => new RedmineClient(baseUrl, apiKey); - - return createRedmineService({ - ...deps, - baseUrl, - connect, - service: - config.REDMINE_API_KEY === undefined - ? undefined - : connect(config.REDMINE_API_KEY), - tracker: createTrackerRepository(db), - secrets: createSecretBox(config.CREDENTIAL_ENCRYPTION_KEY), - }); -} - export function compose(config: Config, log: Logger) { const database = connectDatabase(config.DATABASE_URL); const client = createClient(); @@ -203,18 +168,26 @@ export function compose(config: Config, log: Logger) { pollCommands(polls), movieCommands(movies), ]; - const redmine = createRedmine(config, { - db: database.db, - reminders, - scheduler, - messenger, - authz, - log, - timezone, - }); - if (redmine) { - features.push(redmineCommands(redmine, config.REDMINE_BASE_URL ?? '')); + if ( + config.REDMINE_BASE_URL !== undefined && + config.REDMINE_API_KEY !== undefined + ) { + const redmine = createRedmineService({ + baseUrl: config.REDMINE_BASE_URL, + client: new RedmineClient( + config.REDMINE_BASE_URL, + config.REDMINE_API_KEY, + ), + tracker: createTrackerRepository(database.db), + scheduler, + messenger, + authz, + log, + timezone, + }); + + features.push(redmineCommands(redmine)); jobs.push(...redmine.jobs); } diff --git a/src/config/env.ts b/src/config/env.ts index c5cfe3d..503ffa8 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -31,14 +31,6 @@ const envSchema = z.object({ REDMINE_BASE_URL: optional(z.url()), REDMINE_API_KEY: optional(z.string().min(1)), - CREDENTIAL_ENCRYPTION_KEY: optional( - z - .string() - .refine( - (key) => Buffer.from(key, 'base64').length === 32, - 'must be 32 bytes encoded as base64', - ), - ), WEB_PORT: optional(z.coerce.number().int().min(1).max(65_535)), WEB_HOST: z.string().default('127.0.0.1'), @@ -46,13 +38,22 @@ const envSchema = z.object({ export type Config = z.infer; -const checkedSchema = envSchema.refine( - (env) => env.WEB_PORT === undefined || env.DISCORD_GUILD_ID !== undefined, - { - message: 'DISCORD_GUILD_ID is required when WEB_PORT is set', - path: ['DISCORD_GUILD_ID'], - }, -); +const checkedSchema = envSchema + .refine( + (env) => env.WEB_PORT === undefined || env.DISCORD_GUILD_ID !== undefined, + { + message: 'DISCORD_GUILD_ID is required when WEB_PORT is set', + path: ['DISCORD_GUILD_ID'], + }, + ) + .refine( + (env) => + env.REDMINE_BASE_URL === undefined || env.REDMINE_API_KEY !== undefined, + { + message: 'REDMINE_API_KEY is required when REDMINE_BASE_URL is set', + path: ['REDMINE_API_KEY'], + }, + ); export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const result = checkedSchema.safeParse(env); diff --git a/src/core/ports/index.ts b/src/core/ports/index.ts index 204c3a8..688ea22 100644 --- a/src/core/ports/index.ts +++ b/src/core/ports/index.ts @@ -3,7 +3,6 @@ export type * from './chat'; export * from './clock'; export type * from './logger'; export type * from './scheduler'; -export type * from './secrets'; export type * from './roles'; export type * from './reminders'; export type * from './announcements'; diff --git a/src/core/ports/issues.ts b/src/core/ports/issues.ts index aa96ef5..a606160 100644 --- a/src/core/ports/issues.ts +++ b/src/core/ports/issues.ts @@ -1,14 +1,6 @@ -import type { - Issue, - IssueChanges, - IssueQuery, - IssueStatus, - TrackerProject, - TrackerUser, -} from '~/domain'; +import type { Issue, IssueQuery, IssueStatus, TrackerProject } from '~/domain'; export type IssueTracker = { - currentUser: () => Promise; listProjects: ( offset?: number, limit?: number, @@ -18,17 +10,6 @@ export type IssueTracker = { ) => Promise<{ issues: Issue[]; total: number }>; getIssue: (id: number, withJournals?: boolean) => Promise; listStatuses: () => Promise; - createIssue: ( - fields: IssueChanges & { project_id: number | string; subject: string }, - ) => Promise; - updateIssue: (id: number, changes: IssueChanges) => Promise; -}; - -export type TrackerLink = { - userId: string; - redmineUserId: number; - redmineLogin: string; - encryptedApiKey: string; }; export type Subscription = { @@ -42,9 +23,6 @@ export type Subscription = { }; export type TrackerRepository = { - saveLink: (link: TrackerLink) => Promise; - link: (userId: string) => Promise; - unlink: (userId: string) => Promise; subscribe: ( subscription: Omit, ) => Promise; diff --git a/src/core/ports/secrets.ts b/src/core/ports/secrets.ts deleted file mode 100644 index 7f75e88..0000000 --- a/src/core/ports/secrets.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type SecretBox = { - encrypt: (plaintext: string) => string; - decrypt: (sealed: string) => string; -}; diff --git a/src/core/services/redmine.ts b/src/core/services/redmine.ts index ca2afd4..8197cce 100644 --- a/src/core/services/redmine.ts +++ b/src/core/services/redmine.ts @@ -6,14 +6,9 @@ import { IntegrationError, issueNotifications, nextDailyRun, - parseCalendarDay, UserError, - zonedTime, - type Actor, - type IssueQuery, type IssueStatus, type Notification, - type TrackerUser, } from '~/domain'; import type { Authorizer, @@ -21,33 +16,21 @@ import type { Logger, Messenger, Scheduler, - SecretBox, Subscription, TrackerRepository, } from '~/core/ports'; import { sequential } from '~/lib'; import { guard } from './guard'; import { defineJob } from './jobs'; -import type { ReminderService } from './reminders'; const pollIntervalMs = 2 * 60 * 1000; const issuesPerPoll = 25; const deadlineHour = 9; -export type IssueDraft = { - project: string; - subject: string; - description?: string; - assignToMe?: boolean; -}; - type Deps = { baseUrl: string; - connect: (apiKey: string) => IssueTracker; - service?: IssueTracker | undefined; + client: IssueTracker; tracker: TrackerRepository; - secrets: SecretBox; - reminders: ReminderService; scheduler: Scheduler; messenger: Messenger; authz: Authorizer; @@ -56,60 +39,10 @@ type Deps = { }; export function createRedmineService(deps: Deps) { - const { - connect, - service, - tracker, - secrets, - reminders, - messenger, - authz, - log, - } = deps; + const { client, tracker, messenger, authz, log } = deps; const root = deps.baseUrl.endsWith('/') ? deps.baseUrl : `${deps.baseUrl}/`; const issueUrl = (id: number) => `${root}issues/${id}`; - const asUser = async ( - actor: Actor, - run: (client: IssueTracker, redmineUserId: number) => Promise, - ) => { - const link = await tracker.link(actor.userId); - - if (!link) { - throw new UserError( - 'Link your Redmine account first with "/redmine link".', - ); - } - - try { - return await run( - connect(secrets.decrypt(link.encryptedApiKey)), - link.redmineUserId, - ); - } catch (error) { - if (error instanceof IntegrationError) { - log.warn( - { kind: error.kind, userId: actor.userId }, - 'Redmine request failed', - ); - - throw new UserError(error.message); - } - - throw error; - } - }; - - const requireService = () => { - if (!service) { - throw new UserError( - 'Redmine notifications are not configured (REDMINE_API_KEY).', - ); - } - - return service; - }; - const sendOnce = async ( subscription: Subscription, notification: Notification, @@ -149,7 +82,6 @@ export function createRedmineService(deps: Deps) { }; const pollSubscription = async ( - client: IssueTracker, subscription: Subscription, statuses: ReadonlyMap, ) => { @@ -191,12 +123,11 @@ export function createRedmineService(deps: Deps) { type: 'redmine:poll', payload: z.object({}), handle: async () => { - const client = requireService(); const known = await client.listStatuses().catch(() => []); const statuses = new Map(known.map((status) => [status.id, status])); await forEachSubscription((subscription) => - pollSubscription(client, subscription, statuses), + pollSubscription(subscription, statuses), ); return { rescheduleAt: new Date(Date.now() + pollIntervalMs) }; @@ -207,7 +138,6 @@ export function createRedmineService(deps: Deps) { type: 'redmine:deadlines', payload: z.object({}), handle: async () => { - const client = requireService(); const tomorrow = formatCalendarDay( addCalendarDays(calendarDay(new Date(), deps.timezone), 1), ); @@ -237,30 +167,32 @@ export function createRedmineService(deps: Deps) { }, }); - const subscription = async (actor: Actor, identifier: string) => - asUser(actor, async (client) => { + const project = async (identifier: string) => { + try { const { projects } = await client.listProjects(0, 100); - const project = projects.find( + const found = projects.find( (p) => p.identifier === identifier || String(p.id) === identifier, ); - if (!project) { - throw new UserError( - `Project "${identifier}" not found among your projects.`, - ); + if (!found) { + throw new UserError(`Project "${identifier}" not found.`); } - return project; - }); + return found; + } catch (error) { + if (error instanceof IntegrationError) { + log.warn({ kind: error.kind }, 'Redmine request failed'); - return { - issueUrl, - jobs: service ? [pollJob, deadlineJob] : [], - start: async () => { - if (!service) { - return; + throw new UserError(error.message); } + throw error; + } + }; + + return { + jobs: [pollJob, deadlineJob], + start: async () => { await deps.scheduler.schedule( pollJob, {}, @@ -275,151 +207,16 @@ export function createRedmineService(deps: Deps) { }, ); }, - link: async (actor: Actor, apiKey: string) => { - let user: TrackerUser; - - try { - user = await connect(apiKey.trim()).currentUser(); - } catch (error) { - if (error instanceof IntegrationError) { - throw new UserError( - error.kind === 'auth' - ? 'Redmine did not accept that API key.' - : error.message, - ); - } - - throw error; - } - - await tracker.saveLink({ - userId: actor.userId, - redmineUserId: user.id, - redmineLogin: user.login, - encryptedApiKey: secrets.encrypt(apiKey.trim()), - }); - log.info( - { userId: actor.userId, redmineUserId: user.id }, - 'Redmine account linked', - ); - - return user; - }, - unlink: async (actor: Actor) => { - const removed = await tracker.unlink(actor.userId); - - log.info({ userId: actor.userId, removed }, 'Redmine account unlinked'); - - return removed; - }, - projects: (actor: Actor) => - asUser(actor, (client) => client.listProjects()), - issues: (actor: Actor, query: IssueQuery) => - asUser(actor, (client) => client.listIssues({ ...query, limit: 15 })), - issue: (actor: Actor, id: number) => - asUser(actor, (client) => client.getIssue(id)), - statuses: (actor: Actor) => - asUser(actor, (client) => client.listStatuses()), - createIssue: guard( - authz, - 'redmine:issue:create', - (actor, draft: IssueDraft) => - asUser(actor, (client, redmineUserId) => - client.createIssue({ - project_id: draft.project, - subject: draft.subject, - ...(draft.description !== undefined && { - description: draft.description, - }), - ...(draft.assignToMe === true && { assigned_to_id: redmineUserId }), - }), - ), - ), - updateIssue: guard( - authz, - 'redmine:issue:update', - (actor, id: number, changes: { statusId?: number; notes?: string }) => { - if (changes.statusId === undefined && changes.notes === undefined) { - throw new UserError('Give a new status or notes.'); - } - - return asUser(actor, (client) => - client.updateIssue(id, { - ...(changes.statusId !== undefined && { - status_id: changes.statusId, - }), - ...(changes.notes !== undefined && { notes: changes.notes }), - }), - ); - }, - ), - comment: guard( - authz, - 'redmine:issue:update', - (actor, id: number, notes: string) => - asUser(actor, (client) => client.updateIssue(id, { notes })), - ), - assign: guard( - authz, - 'redmine:issue:assign', - async (actor, id: number, memberId?: string) => { - const target = - memberId === undefined || memberId === actor.userId - ? undefined - : await tracker.link(memberId); - - if (memberId !== undefined && memberId !== actor.userId && !target) { - throw new UserError('That member has not linked a Redmine account.'); - } - - return asUser(actor, (client, redmineUserId) => - client.updateIssue(id, { - assigned_to_id: target?.redmineUserId ?? redmineUserId, - }), - ); - }, - ), - remind: async (actor: Actor, id: number, daysBefore = 1) => { - const issue = await asUser(actor, (client) => client.getIssue(id)); - const due = parseCalendarDay(issue.due_date ?? ''); - - if (!due) { - throw new UserError(`#${issue.id} has no due date.`); - } - - const runAt = zonedTime( - addCalendarDays(due, -daysBefore), - 9, - deps.timezone, - ); - - if (runAt.getTime() <= Date.now()) { - throw new UserError('That reminder time has already passed.'); - } - - return reminders.schedule({ - guildId: actor.guildId, - userId: actor.userId, - channelId: null, - message: `Redmine #${issue.id} "${issue.subject}" is due ${issue.due_date ?? ''}: ${issueUrl(issue.id)}`, - runAt, - recurrence: null, - timezone: deps.timezone, - }); - }, subscribe: guard( authz, 'redmine:subscription:manage', async (actor, channelId: string, identifier: string) => { - const project = await subscription(actor, identifier); - - await requireService().listIssues({ projectId: project.id, limit: 1 }); - + const found = await project(identifier); const added = await tracker.subscribe({ guildId: actor.guildId, channelId, - projectId: project.id, - projectName: project.name, + projectId: found.id, + projectName: found.name, createdBy: actor.userId, }); @@ -427,27 +224,27 @@ export function createRedmineService(deps: Deps) { { guildId: actor.guildId, channelId, - projectId: project.id, + projectId: found.id, actorId: actor.userId, }, 'Redmine subscription added', ); - return { project, added }; + return { project: found, added }; }, ), unsubscribe: guard( authz, 'redmine:subscription:manage', async (actor, channelId: string, identifier: string) => { - const project = await subscription(actor, identifier); + const found = await project(identifier); return { - project, + project: found, removed: await tracker.unsubscribe( actor.guildId, channelId, - project.id, + found.id, ), }; }, diff --git a/src/domain/issue.ts b/src/domain/issue.ts index a873643..13b53c4 100644 --- a/src/domain/issue.ts +++ b/src/domain/issue.ts @@ -1,12 +1,5 @@ export type Named = { id: number; name: string }; -export type TrackerUser = { - id: number; - login: string; - firstname?: string; - lastname?: string; -}; - export type TrackerProject = { id: number; name: string; @@ -52,7 +45,6 @@ export type Issue = { export type IssueQuery = { projectId?: number | string; - assignedToMe?: boolean; status?: 'open' | 'closed' | '*'; updatedSince?: Date; dueDate?: string; @@ -61,21 +53,8 @@ export type IssueQuery = { limit?: number; }; -export type IssueChanges = { - subject?: string; - description?: string; - status_id?: number; - assigned_to_id?: number; - notes?: string; -}; - export type IntegrationErrorKind = - | 'auth' - | 'forbidden' - | 'not_found' - | 'validation' - | 'unavailable' - | 'invalid_response'; + 'auth' | 'forbidden' | 'not_found' | 'unavailable' | 'invalid_response'; export class IntegrationError extends Error { override readonly name = 'IntegrationError'; diff --git a/src/infra/crypto/index.ts b/src/infra/crypto/index.ts deleted file mode 100644 index 1157635..0000000 --- a/src/infra/crypto/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './secret-box'; diff --git a/src/infra/crypto/secret-box.ts b/src/infra/crypto/secret-box.ts deleted file mode 100644 index 28e8c44..0000000 --- a/src/infra/crypto/secret-box.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; - -const version = 'v1'; - -export function createSecretBox(base64Key: string) { - const key = Buffer.from(base64Key, 'base64'); - - if (key.length !== 32) { - throw new Error('Encryption key must be 32 bytes'); - } - - return { - encrypt: (plaintext: string): string => { - const iv = randomBytes(12); - const cipher = createCipheriv('aes-256-gcm', key, iv); - const data = Buffer.concat([ - cipher.update(plaintext, 'utf8'), - cipher.final(), - ]); - - return [version, iv, cipher.getAuthTag(), data] - .map((part) => - typeof part === 'string' ? part : part.toString('base64'), - ) - .join(':'); - }, - decrypt: (sealed: string): string => { - const [prefix, iv, tag, data] = sealed.split(':'); - - if ( - prefix !== version || - iv === undefined || - tag === undefined || - data === undefined - ) { - throw new Error('Unrecognised secret format'); - } - - const decipher = createDecipheriv( - 'aes-256-gcm', - key, - Buffer.from(iv, 'base64'), - ); - - decipher.setAuthTag(Buffer.from(tag, 'base64')); - - return Buffer.concat([ - decipher.update(Buffer.from(data, 'base64')), - decipher.final(), - ]).toString('utf8'); - }, - }; -} - -export type SecretBox = ReturnType; diff --git a/src/infra/db/redmine/model.ts b/src/infra/db/redmine/model.ts index cb1d621..c19468a 100644 --- a/src/infra/db/redmine/model.ts +++ b/src/infra/db/redmine/model.ts @@ -8,16 +8,6 @@ import { unique, } from 'drizzle-orm/pg-core'; -export const redmineLinks = pgTable('redmine_links', { - userId: text('user_id').primaryKey(), - redmineUserId: integer('redmine_user_id').notNull(), - redmineLogin: text('redmine_login').notNull(), - encryptedApiKey: text('encrypted_api_key').notNull(), - linkedAt: timestamp('linked_at', { withTimezone: true }) - .notNull() - .defaultNow(), -}); - export const redmineSubscriptions = pgTable( 'redmine_subscriptions', { @@ -48,5 +38,4 @@ export const redmineNotifications = pgTable( (table) => [primaryKey({ columns: [table.subscriptionId, table.key] })], ); -export type RedmineLink = typeof redmineLinks.$inferSelect; export type RedmineSubscription = typeof redmineSubscriptions.$inferSelect; diff --git a/src/infra/db/redmine/repo.ts b/src/infra/db/redmine/repo.ts index 2e2ab21..4c9c83c 100644 --- a/src/infra/db/redmine/repo.ts +++ b/src/infra/db/redmine/repo.ts @@ -1,46 +1,7 @@ import { and, asc, eq, gt } from 'drizzle-orm'; import type { TrackerRepository } from '~/core/ports'; import type { Db } from '../client'; -import { - redmineLinks, - redmineNotifications, - redmineSubscriptions, - type RedmineLink, -} from './model'; - -export async function saveLink( - db: Db, - link: Omit, -): Promise { - await db - .insert(redmineLinks) - .values(link) - .onConflictDoUpdate({ - target: redmineLinks.userId, - set: { ...link, linkedAt: new Date() }, - }); -} - -export async function getLink( - db: Db, - userId: string, -): Promise { - const [row] = await db - .select() - .from(redmineLinks) - .where(eq(redmineLinks.userId, userId)); - - return row; -} - -export async function deleteLink(db: Db, userId: string): Promise { - const rows = await db - .delete(redmineLinks) - .where(eq(redmineLinks.userId, userId)) - .returning({ userId: redmineLinks.userId }); - - return rows.length > 0; -} +import { redmineNotifications, redmineSubscriptions } from './model'; export async function addSubscription( db: Db, @@ -111,9 +72,6 @@ export async function claimNotification( export function createTrackerRepository(db: Db): TrackerRepository { return { - saveLink: (link) => saveLink(db, link), - link: (userId) => getLink(db, userId), - unlink: (userId) => deleteLink(db, userId), subscribe: (subscription) => addSubscription(db, subscription), unsubscribe: (guildId, channelId, projectId) => removeSubscription(db, guildId, channelId, projectId), diff --git a/src/infra/discord/commands/redmine.ts b/src/infra/discord/commands/redmine.ts index fdac713..b3bf7f8 100644 --- a/src/infra/discord/commands/redmine.ts +++ b/src/infra/discord/commands/redmine.ts @@ -1,158 +1,19 @@ import { ChannelType, - EmbedBuilder, InteractionContextType, - LabelBuilder, - MessageFlags, - ModalBuilder, SlashCommandBuilder, - TextInputBuilder, - TextInputStyle, - type SlashCommandIntegerOption, } from 'discord.js'; import type { RedmineService } from '~/core/services'; -import { channelMention, discordTime, type Issue } from '~/domain'; +import { channelMention } from '~/domain'; import { toActor } from '../actor'; import { bySubcommand, deferred } from '../define'; -import type { - ComponentHandler, - CommandInteraction, - Feature, - SlashCommand, -} from '../module'; +import type { CommandInteraction, Feature } from '../module'; import { respond } from '../router'; -const issueOption = (o: SlashCommandIntegerOption) => - o - .setName('issue') - .setDescription('Issue number') - .setRequired(true) - .setMinValue(1); - const data = new SlashCommandBuilder() .setName('redmine') - .setDescription('Redmine projects and issues') + .setDescription('Redmine project updates') .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub.setName('projects').setDescription('Projects you can see'), - ) - .addSubcommand((sub) => - sub - .setName('issues') - .setDescription('List issues') - .addStringOption((o) => - o.setName('project').setDescription('Project identifier'), - ) - .addBooleanOption((o) => - o.setName('mine').setDescription('Only issues assigned to me'), - ) - .addStringOption((o) => - o - .setName('status') - .setDescription('Status filter') - .addChoices( - { name: 'open', value: 'open' }, - { name: 'closed', value: 'closed' }, - { name: 'all', value: '*' }, - ), - ), - ) - .addSubcommandGroup((group) => - group - .setName('issue') - .setDescription('A single issue') - .addSubcommand((sub) => - sub - .setName('view') - .setDescription('Show an issue') - .addIntegerOption(issueOption), - ) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Create an issue') - .addStringOption((o) => - o - .setName('project') - .setDescription('Project identifier') - .setRequired(true), - ) - .addStringOption((o) => - o - .setName('subject') - .setDescription('Subject') - .setRequired(true) - .setMaxLength(255), - ) - .addStringOption((o) => - o - .setName('description') - .setDescription('Description') - .setMaxLength(4000), - ) - .addBooleanOption((o) => - o.setName('assign_to_me').setDescription('Assign it to me'), - ), - ) - .addSubcommand((sub) => - sub - .setName('update') - .setDescription('Change status or add notes') - .addIntegerOption(issueOption) - .addIntegerOption((o) => - o - .setName('status') - .setDescription('New status') - .setAutocomplete(true), - ) - .addStringOption((o) => - o.setName('notes').setDescription('Notes').setMaxLength(4000), - ), - ) - .addSubcommand((sub) => - sub - .setName('assign') - .setDescription('Assign an issue') - .addIntegerOption(issueOption) - .addUserOption((o) => - o.setName('member').setDescription('Linked member (default: you)'), - ), - ) - .addSubcommand((sub) => - sub - .setName('comment') - .setDescription('Comment on an issue') - .addIntegerOption(issueOption) - .addStringOption((o) => - o - .setName('text') - .setDescription('Comment') - .setRequired(true) - .setMaxLength(4000), - ), - ) - .addSubcommand((sub) => - sub - .setName('remind') - .setDescription('DM me before the due date') - .addIntegerOption(issueOption) - .addIntegerOption((o) => - o - .setName('days_before') - .setDescription('Days before (default 1)') - .setMinValue(0) - .setMaxValue(30), - ), - ), - ) - .addSubcommand((sub) => - sub - .setName('link') - .setDescription('Link your Redmine account with your API key'), - ) - .addSubcommand((sub) => - sub.setName('unlink').setDescription('Remove your stored Redmine key'), - ) .addSubcommand((sub) => sub .setName('subscribe') @@ -188,138 +49,15 @@ const data = new SlashCommandBuilder() ), ); -function issueLine(baseUrl: string, issue: Issue): string { - const assignee = issue.assigned_to ? ` · ${issue.assigned_to.name}` : ''; - - return `[#${issue.id}](<${baseUrl}issues/${issue.id}>) **${issue.subject}** — ${issue.status.name}${assignee}`; -} - -function issueEmbed(baseUrl: string, issue: Issue): EmbedBuilder { - return new EmbedBuilder() - .setTitle(`#${issue.id} ${issue.subject}`.slice(0, 256)) - .setURL(`${baseUrl}issues/${issue.id}`) - .setDescription((issue.description ?? '').slice(0, 1500) || null) - .addFields( - { name: 'Project', value: issue.project.name, inline: true }, - { name: 'Status', value: issue.status.name, inline: true }, - { name: 'Priority', value: issue.priority.name, inline: true }, - { name: 'Assignee', value: issue.assigned_to?.name ?? '—', inline: true }, - { name: 'Due', value: issue.due_date ?? '—', inline: true }, - ); -} - type Handler = (interaction: CommandInteraction) => Promise; -export function redmineCommands( - redmine: RedmineService, - baseUrl: string, -): Feature { - const root = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; +export function redmineCommands(redmine: RedmineService): Feature { const actorOf = (interaction: CommandInteraction) => toActor(interaction.member); const channelOf = (interaction: CommandInteraction) => interaction.options.getChannel('channel')?.id ?? interaction.channelId; const handlers: Record = { - projects: async (interaction) => { - const { projects, total } = await redmine.projects(actorOf(interaction)); - const lines = projects.map((p) => `"${p.identifier}" ${p.name}`); - const more = - total > projects.length ? [`…and ${total - projects.length} more`] : []; - - await respond( - interaction, - [...lines, ...more].join('\n') || 'No projects.', - ); - }, - issues: async (interaction) => { - const status = interaction.options.getString('status'); - const project = interaction.options.getString('project'); - const { issues, total } = await redmine.issues(actorOf(interaction), { - ...(project !== null && { projectId: project }), - assignedToMe: interaction.options.getBoolean('mine') ?? false, - status: status === 'closed' || status === '*' ? status : 'open', - }); - const lines = issues.map((issue) => issueLine(root, issue)); - - await respond( - interaction, - lines.length === 0 - ? 'No issues.' - : `${lines.join('\n')}\n${issues.length} of ${total}`.slice(0, 2000), - ); - }, - 'issue view': async (interaction) => { - const issue = await redmine.issue( - actorOf(interaction), - interaction.options.getInteger('issue', true), - ); - - await respond(interaction, { embeds: [issueEmbed(root, issue)] }); - }, - 'issue create': async (interaction) => { - const description = interaction.options.getString('description'); - const issue = await redmine.createIssue(actorOf(interaction), { - project: interaction.options.getString('project', true), - subject: interaction.options.getString('subject', true), - ...(description !== null && { description }), - assignToMe: interaction.options.getBoolean('assign_to_me') ?? false, - }); - - await respond(interaction, `Created ${issueLine(root, issue)}`); - }, - 'issue update': async (interaction) => { - const statusId = interaction.options.getInteger('status'); - const notes = interaction.options.getString('notes'); - const id = interaction.options.getInteger('issue', true); - - await redmine.updateIssue(actorOf(interaction), id, { - ...(statusId !== null && { statusId }), - ...(notes !== null && { notes }), - }); - await respond(interaction, `Updated #${id}.`); - }, - 'issue assign': async (interaction) => { - const id = interaction.options.getInteger('issue', true); - const member = interaction.options.getUser('member'); - - await redmine.assign( - actorOf(interaction), - id, - ...(member ? [member.id] : []), - ); - await respond(interaction, `Assigned #${id}.`); - }, - 'issue comment': async (interaction) => { - const id = interaction.options.getInteger('issue', true); - - await redmine.comment( - actorOf(interaction), - id, - interaction.options.getString('text', true), - ); - await respond(interaction, `Commented on #${id}.`); - }, - 'issue remind': async (interaction) => { - const reminder = await redmine.remind( - actorOf(interaction), - interaction.options.getInteger('issue', true), - interaction.options.getInteger('days_before') ?? 1, - ); - - await respond( - interaction, - `I will DM you ${discordTime(reminder.runAt, 'R')} (reminder #${reminder.id}).`, - ); - }, - unlink: async (interaction) => { - const removed = await redmine.unlink(actorOf(interaction)); - - await respond( - interaction, - removed ? 'Your Redmine key is deleted.' : 'You had no linked account.', - ); - }, subscribe: async (interaction) => { const channelId = channelOf(interaction); const { project, added } = await redmine.subscribe( @@ -352,85 +90,27 @@ export function redmineCommands( }, }; - const link: Handler = async (interaction) => { - const key = new TextInputBuilder() - .setCustomId('key') - .setStyle(TextInputStyle.Short) - .setMinLength(20) - .setMaxLength(100); - - await interaction.showModal( - new ModalBuilder() - .setCustomId('redmine:link') - .setTitle('Link Redmine') - .addLabelComponents( - new LabelBuilder() - .setLabel('API key') - .setDescription( - 'Redmine → My account → API access key. Stored encrypted.', - ) - .setTextInputComponent(key), - ), - ); - }; - - const linkModal: ComponentHandler = { - prefix: 'redmine:link', - execute: async (interaction) => { - if (!interaction.isModalSubmit()) { - return; - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - - const user = await redmine.link( - toActor(interaction.member), - interaction.fields.getTextInputValue('key'), - ); - - await respond(interaction, `Linked to Redmine user **${user.login}**.`); - }, - }; - - const command: SlashCommand = { - data: data.toJSON(), - execute: bySubcommand({ - link, - ...Object.fromEntries( - Object.entries(handlers).map(([path, handler]) => [ - path, - deferred(handler), - ]), - ), - }), - autocomplete: async (interaction) => { - const statuses = await redmine.statuses(toActor(interaction.member)); - - await interaction.respond( - statuses.slice(0, 25).map((s) => ({ name: s.name, value: s.id })), - ); - }, - }; - return { name: 'redmine', permissions: [ - { - id: 'redmine:issue:create', - description: 'Create Redmine issues (Redmine permissions still apply)', - }, - { - id: 'redmine:issue:update', - description: 'Update and comment on Redmine issues', - }, - { id: 'redmine:issue:assign', description: 'Assign Redmine issues' }, { id: 'redmine:subscription:manage', description: 'Subscribe channels to Redmine projects', }, ], - commands: [command], - components: [linkModal], + commands: [ + { + data: data.toJSON(), + execute: bySubcommand( + Object.fromEntries( + Object.entries(handlers).map(([path, handler]) => [ + path, + deferred(handler), + ]), + ), + ), + }, + ], start: () => redmine.start(), }; } diff --git a/src/infra/redmine/client.ts b/src/infra/redmine/client.ts index 27ff41f..3d1eb76 100644 --- a/src/infra/redmine/client.ts +++ b/src/infra/redmine/client.ts @@ -4,22 +4,13 @@ import { IntegrationError, type IntegrationErrorKind, type Issue, - type IssueChanges, type IssueQuery, type IssueStatus, type TrackerProject, - type TrackerUser, } from '~/domain'; const named = z.object({ id: z.number(), name: z.string() }); -const userSchema = z.object({ - id: z.number(), - login: z.string(), - firstname: z.string().exactOptional(), - lastname: z.string().exactOptional(), -}); - const projectSchema = z.object({ id: z.number(), name: z.string(), @@ -78,18 +69,9 @@ const issuesPage = z.object({ total_count: z.number().exactOptional(), }); -type Request = { - method?: 'GET' | 'POST' | 'PUT'; - body?: unknown; - query?: Record; -}; - const messages: Record = { - 401: [ - 'auth', - 'Redmine rejected the API key. Link your account again with `/redmine link`.', - ], - 403: ['forbidden', 'Your Redmine account is not allowed to do that.'], + 401: ['auth', 'Redmine rejected REDMINE_API_KEY.'], + 403: ['forbidden', 'The Redmine service account is not allowed to do that.'], 404: ['not_found', 'Redmine could not find that (or you cannot see it).'], }; @@ -102,50 +84,42 @@ export class RedmineClient implements IssueTracker { private readonly options: { timeoutMs?: number; fetch?: typeof fetch } = {}, ) {} - private async request(path: string, request: Request = {}): Promise { + private async request( + path: string, + query: Record = {}, + ): Promise { const url = new URL( path, this.baseUrl.endsWith('/') ? this.baseUrl : `${this.baseUrl}/`, ); - for (const [key, value] of Object.entries(request.query ?? {})) { + for (const [key, value] of Object.entries(query)) { url.searchParams.set(key, value); } - const method = request.method ?? 'GET'; - try { - return await this.send(url, method, request.body); + return await this.send(url); } catch (error) { - const retryable = - method === 'GET' && - error instanceof IntegrationError && - error.kind === 'unavailable'; - - if (!retryable) { + if ( + !(error instanceof IntegrationError) || + error.kind !== 'unavailable' + ) { throw error; } - return this.send(url, method, request.body); + return this.send(url); } } - private async send( - url: URL, - method: string, - body: unknown, - ): Promise { + private async send(url: URL): Promise { let response: Response; try { response = await (this.options.fetch ?? fetch)(url, { - method, headers: { 'X-Redmine-API-Key': this.apiKey, Accept: 'application/json', - ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(this.options.timeoutMs ?? 10_000), }); } catch { @@ -155,19 +129,6 @@ export class RedmineClient implements IssueTracker { ); } - if (response.status === 422) { - const parsed = z - .object({ errors: z.array(z.string()) }) - .safeParse(await response.json().catch(() => null)); - - throw new IntegrationError( - 'validation', - parsed.success - ? parsed.data.errors.join('; ') - : 'Redmine rejected the request.', - ); - } - const known = messages[response.status]; if (known) { @@ -181,9 +142,7 @@ export class RedmineClient implements IssueTracker { ); } - const text = await response.text(); - - return text === '' ? null : JSON.parse(text); + return response.json().catch(() => null); } private async get( @@ -191,9 +150,7 @@ export class RedmineClient implements IssueTracker { schema: T, query?: Record, ): Promise> { - const parsed = schema.safeParse( - await this.request(path, query === undefined ? {} : { query }), - ); + const parsed = schema.safeParse(await this.request(path, query)); if (!parsed.success) { throw new IntegrationError( @@ -205,15 +162,6 @@ export class RedmineClient implements IssueTracker { return parsed.data; } - async currentUser(): Promise { - const data = await this.get( - 'users/current.json', - z.object({ user: userSchema }), - ); - - return data.user; - } - async listProjects( offset = 0, limit = 25, @@ -243,10 +191,6 @@ export class RedmineClient implements IssueTracker { params.project_id = String(query.projectId); } - if (query.assignedToMe === true) { - params.assigned_to_id = 'me'; - } - if (query.updatedSince) { params.updated_on = `>=${redmineTime(query.updatedSince)}`; } @@ -282,30 +226,4 @@ export class RedmineClient implements IssueTracker { return data.issue_statuses; } - - async createIssue( - fields: IssueChanges & { project_id: number | string; subject: string }, - ): Promise { - const data = await this.request('issues.json', { - method: 'POST', - body: { issue: fields }, - }); - const parsed = z.object({ issue: issueSchema }).safeParse(data); - - if (!parsed.success) { - throw new IntegrationError( - 'invalid_response', - 'Redmine created the issue but sent an unexpected response.', - ); - } - - return parsed.data.issue; - } - - async updateIssue(id: number, changes: IssueChanges): Promise { - await this.request(`issues/${id}.json`, { - method: 'PUT', - body: { issue: changes }, - }); - } } diff --git a/tests/app.test.ts b/tests/app.test.ts index e238285..2efcaec 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -10,7 +10,7 @@ import type { Config } from '~/config'; const config = { DEFAULT_TIMEZONE: 'Europe/Tallinn', REDMINE_BASE_URL: 'https://redmine.example', - CREDENTIAL_ENCRYPTION_KEY: Buffer.alloc(32).toString('base64'), + REDMINE_API_KEY: 'key', } as Config; function problems( diff --git a/tests/core/services/redmine.test.ts b/tests/core/services/redmine.test.ts index 71d00f8..61a79a5 100644 --- a/tests/core/services/redmine.test.ts +++ b/tests/core/services/redmine.test.ts @@ -1,9 +1,7 @@ -import { randomBytes } from 'node:crypto'; import { describe, expect, it, vi } from 'vitest'; import type { IssueTracker, Scheduler } from '~/core/ports'; -import { createRedmineService, type ReminderService } from '~/core/services'; +import { createRedmineService } from '~/core/services'; import { IntegrationError, UserError, type Issue } from '~/domain'; -import { createSecretBox } from '~/infra/crypto'; import { createTrackerRepository } from '~/infra/db'; import { noDatabase, snowflake, testDb } from '../../db'; import { actor, allowAll, fakeMessenger, silentLog } from '../../fakes'; @@ -26,7 +24,6 @@ const issue: Issue = { function tracker(overrides: Partial = {}): IssueTracker { return { - currentUser: vi.fn(async () => ({ id: 5, login: 'mari' })), listProjects: vi.fn(async () => ({ projects: [{ id: 1, name: 'Web', identifier: 'web' }], total: 1, @@ -34,8 +31,6 @@ function tracker(overrides: Partial = {}): IssueTracker { listIssues: vi.fn(async () => ({ issues: [issue], total: 1 })), getIssue: vi.fn(async () => issue), listStatuses: vi.fn(async () => []), - createIssue: vi.fn(async () => issue), - updateIssue: vi.fn(async () => undefined), ...overrides, }; } @@ -43,14 +38,10 @@ function tracker(overrides: Partial = {}): IssueTracker { describe.skipIf(noDatabase)('redmine service', () => { const setup = (client = tracker()) => { const { messenger } = fakeMessenger(); - const connect = vi.fn(() => client); const service = createRedmineService({ baseUrl: 'https://r', - connect, - service: client, + client, tracker: createTrackerRepository(testDb()), - secrets: createSecretBox(randomBytes(32).toString('base64')), - reminders: {} as ReminderService, scheduler: { schedule: vi.fn(async () => undefined), cancel: vi.fn(async () => undefined), @@ -61,19 +52,26 @@ describe.skipIf(noDatabase)('redmine service', () => { timezone: 'Europe/Tallinn', }); - return { service, messenger, connect, client }; + return { service, messenger }; }; - it('requires a linked account and uses that key for user actions', async () => { - const { service, connect } = setup(); + it('subscribes a channel to a project found by identifier', async () => { + const { service } = setup(); const member = actor({ guildId: snowflake(), userId: snowflake() }); + const channelId = snowflake(); - await expect(service.projects(member)).rejects.toThrow( - 'Link your Redmine account', + await expect(service.subscribe(member, channelId, 'nope')).rejects.toThrow( + UserError, + ); + + const first = await service.subscribe(member, channelId, 'web'); + const again = await service.subscribe(member, channelId, '1'); + + expect(first).toMatchObject({ project: { id: 1 }, added: true }); + expect(again.added).toBe(false); + expect((await service.unsubscribe(member, channelId, 'web')).removed).toBe( + true, ); - await service.link(member, 'k'.repeat(40)); - await service.projects(member); - expect(connect).toHaveBeenLastCalledWith('k'.repeat(40)); }); it('turns tracker failures into user-facing errors', async () => { @@ -85,8 +83,9 @@ describe.skipIf(noDatabase)('redmine service', () => { const { service } = setup(failing); const member = actor({ guildId: snowflake(), userId: snowflake() }); - await service.link(member, 'k'.repeat(40)); - await expect(service.projects(member)).rejects.toThrow(UserError); + await expect(service.subscribe(member, snowflake(), 'web')).rejects.toThrow( + UserError, + ); }); it('notifies once per change and advances the checkpoint', async () => { diff --git a/tests/infra/crypto/secret-box.test.ts b/tests/infra/crypto/secret-box.test.ts deleted file mode 100644 index 4523cd2..0000000 --- a/tests/infra/crypto/secret-box.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { randomBytes } from 'node:crypto'; -import { describe, expect, it } from 'vitest'; -import { createSecretBox } from '~/infra/crypto'; - -describe('createSecretBox', () => { - const box = createSecretBox(randomBytes(32).toString('base64')); - - it('round-trips without leaking the plaintext', () => { - const sealed = box.encrypt('api-key-123'); - - expect(sealed).not.toContain('api-key-123'); - expect(box.encrypt('api-key-123')).not.toBe(sealed); - expect(box.decrypt(sealed)).toBe('api-key-123'); - }); - - it('refuses tampered values and other keys', () => { - const sealed = box.encrypt('api-key-123'); - const parts = sealed.split(':'); - const tampered = [ - ...parts.slice(0, 3), - Buffer.from('x').toString('base64'), - ].join(':'); - - expect(() => box.decrypt(tampered)).toThrow(); - expect(() => - createSecretBox(randomBytes(32).toString('base64')).decrypt(sealed), - ).toThrow(); - expect(() => createSecretBox('short')).toThrow('32 bytes'); - }); -}); diff --git a/tests/infra/redmine/client.test.ts b/tests/infra/redmine/client.test.ts index 6a73014..08a5e1f 100644 --- a/tests/infra/redmine/client.test.ts +++ b/tests/infra/redmine/client.test.ts @@ -15,7 +15,7 @@ const issue = { }; const json = (status: number, body: unknown) => - new Response(body === undefined ? null : JSON.stringify(body), { status }); + new Response(JSON.stringify(body), { status }); function client(...responses: Array) { const fetch = vi.fn(); @@ -51,7 +51,6 @@ describe('RedmineClient', () => { ); const result = await redmine.listIssues({ projectId: 'web', - assignedToMe: true, updatedSince: new Date('2026-11-01T10:00:00.123Z'), }); @@ -60,7 +59,6 @@ describe('RedmineClient', () => { const url = input instanceof URL ? input.href : ''; expect(url).toContain('project_id=web'); - expect(url).toContain('assigned_to_id=me'); expect(decodeURIComponent(url)).toContain( 'updated_on=>=2026-11-01T10:00:00Z', ); @@ -80,32 +78,18 @@ describe('RedmineClient', () => { ])('maps HTTP %i to %s', async (status, expected) => { const { redmine } = client(json(status, {})); - expect(await kind(redmine.currentUser())).toBe(expected); + expect(await kind(redmine.listStatuses())).toBe(expected); }); - it('reports validation errors from Redmine', async () => { - const { redmine } = client( - json(422, { errors: ['Subject cannot be blank'] }), - ); - - await expect( - redmine.createIssue({ project_id: 1, subject: '' }), - ).rejects.toThrow('Subject cannot be blank'); - }); - - it('retries reads once on timeouts but never retries writes', async () => { + it('retries once on timeouts', async () => { const timeout = new DOMException('timed out', 'TimeoutError'); - const read = client(timeout, json(200, { user: { id: 1, login: 'mari' } })); - - expect((await read.redmine.currentUser()).login).toBe('mari'); - expect(read.fetch).toHaveBeenCalledTimes(2); - - const write = client(timeout, json(204, undefined)); - - expect(await kind(write.redmine.updateIssue(7, { notes: 'hi' }))).toBe( - 'unavailable', + const { fetch, redmine } = client( + timeout, + json(200, { issue_statuses: [{ id: 1, name: 'New' }] }), ); - expect(write.fetch).toHaveBeenCalledOnce(); + + expect(await redmine.listStatuses()).toHaveLength(1); + expect(fetch).toHaveBeenCalledTimes(2); }); it('treats server errors as unavailable', async () => { From 947e72489041d9ab9a3df5a31e8888b1d2edb7e8 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:44:17 +0200 Subject: [PATCH 044/199] docs: drop crypto from the architecture overview --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3a42879..05655e2 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,7 @@ src/ lib/ generic helpers core/ ports/ contracts: Messenger, Directory, Calendar, Scheduler, - IssueTracker, SecretBox and one repository per area + IssueTracker and one repository per area services/ use cases (roles, reminders, events, polls, ...), each created from its ports, with permission guards infra/ @@ -200,9 +200,8 @@ src/ thin slash-command adapters in commands/ scheduler/ job queue (Scheduler port) and the job runner redmine/ Redmine adapter for the IssueTracker port - crypto/ AES-256-GCM SecretBox logging/ pino - web/ server-rendered web UI and the Authenticator adapters + web/ server-rendered web UI and its Authenticator adapter tests/ mirrors src/ drizzle/ SQL migrations ``` From deb4263d60ca01590257a9daa4efa366ee946942 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 11:45:18 +0200 Subject: [PATCH 045/199] feat(announcements): post as a plain message by default --- src/infra/discord/commands/announcements.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts index 70a1635..376f120 100644 --- a/src/infra/discord/commands/announcements.ts +++ b/src/infra/discord/commands/announcements.ts @@ -81,7 +81,7 @@ const data = new SlashCommandBuilder() ), ) .addBooleanOption((o) => - o.setName('embed').setDescription('Post as an embed (default yes)'), + o.setName('embed').setDescription('Post as an embed (default no)'), ), ) .addSubcommand((sub) => @@ -204,7 +204,7 @@ export function announcementCommands( execute: bySubcommand({ create: async (interaction) => { const channel = interaction.options.getChannel('channel', true); - const embed = interaction.options.getBoolean('embed') ?? true; + const embed = interaction.options.getBoolean('embed') ?? false; await interaction.showModal( contentModal( From 2eb8fa4f6f0ff7d8a6a655c92a31996c23b34b29 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:00:22 +0200 Subject: [PATCH 046/199] refactor(roles): leave role selection to Discord onboarding, keep only the legacy reaction message --- README.md | 45 ++-- src/app.ts | 1 - src/core/ports/chat.ts | 12 - src/core/ports/roles.ts | 22 -- src/core/services/roles.ts | 298 +------------------------ src/domain/role.ts | 14 -- src/infra/db/roles/repo.ts | 151 +------------ src/infra/discord/adapters.ts | 19 -- src/infra/discord/commands/roles.ts | 325 +--------------------------- tests/core/services/roles.test.ts | 70 +----- tests/domain/role.test.ts | 19 +- tests/fakes.ts | 4 - 12 files changed, 28 insertions(+), 952 deletions(-) diff --git a/README.md b/README.md index 05655e2..d931fb6 100644 --- a/README.md +++ b/README.md @@ -50,18 +50,16 @@ environment-only. ## Commands -| Command | Who | -| -------------------------------------------------------------------------- | -------------------------------------------------------------- | -| `/role list`, role panels (button + select menu) | everyone | -| `/role create`, `delete`, `assign`, `remove`, `panel create/update/remove` | `role:create`, `role:manage`, `role:assign` | -| `/remindme`, `/reminders list/edit/cancel` | everyone; `channel:` needs `reminder:channel` | -| `/announce create/preview/publish/schedule/edit/cancel` | `announcement:create`, `:publish`, `:schedule` | -| `/event create/edit/cancel/list/view/attendees`, RSVP buttons | create needs `event:create`; organizer or `event:manage` edits | -| `/birthday set/remove/view/upcoming`, `/birthday settings` | everyone; settings need `birthday:manage` | -| `/poll create/list/results/close/cancel` | create needs `poll:create`; creator or `poll:manage` manages | -| `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | -| `/redmine subscribe/unsubscribe` | `redmine:subscription:manage` | -| `/permissions grant/revoke/list/check` | `permissions:manage` | +| Command | Who | +| -------------------------------------------------------------- | -------------------------------------------------------------- | +| `/remindme`, `/reminders list/edit/cancel` | everyone; `channel:` needs `reminder:channel` | +| `/announce create/preview/publish/schedule/edit/cancel` | `announcement:create`, `:publish`, `:schedule` | +| `/event create/edit/cancel/list/view/attendees`, RSVP buttons | create needs `event:create`; organizer or `event:manage` edits | +| `/birthday set/remove/view/upcoming`, `/birthday settings` | everyone; settings need `birthday:manage` | +| `/poll create/list/results/close/cancel` | create needs `poll:create`; creator or `poll:manage` manages | +| `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | +| `/redmine subscribe/unsubscribe` | `redmine:subscription:manage` | +| `/permissions grant/revoke/list/check` | `permissions:manage` | ## Web UI @@ -100,26 +98,19 @@ The bot has its own action-based permissions (`event:create`, `poll:manage`, the message was created. Discord role hierarchy always applies on top. - Every grant and revoke is logged. -## Role panels and migrating from reactions +## Role selection + +Members pick their own roles through Discord's **Server Settings → Onboarding** +(customization questions) and the **Channels & Roles** page. The bot has no +role commands. The original reaction message (`Valige endale rolli: …` with 1️⃣ 2️⃣ 3️⃣) still works when `ROLE_SELECTION_CHANNEL_ID` and the role IDs are set. On first start the bot finds the message it posted before, or posts it once, and stores its ID. It no longer reposts or searches on later starts, and reactions on any -other message are ignored. - -Select-menu panels are the replacement. Members press **Choose roles** and get -a private menu showing the roles they already have. To migrate: - -1. `/role panel create channel:#rollid title:Vali endale roll` -2. `/role panel update panel: add:@Tarkvara`, then do the same for each role. -3. Announce the new panel. Members who reacted keep their roles. -4. When ready, an administrator runs `/role panel remove` on the legacy - panel and clears `ROLE_SELECTION_CHANNEL_ID`. The bot never deletes the - legacy message on its own. - -Roles that grant moderator permissions, are managed by integrations, or sit -above the bot cannot be put on a panel. +other message are ignored. Roles that grant moderator permissions, are managed +by integrations, or sit above the bot are never handed out. To retire it, +clear `ROLE_SELECTION_CHANNEL_ID` and delete the message yourself. ## Redmine diff --git a/src/app.ts b/src/app.ts index a12d94a..a2d99ce 100644 --- a/src/app.ts +++ b/src/app.ts @@ -85,7 +85,6 @@ export function compose(config: Config, log: Logger) { panels: createRolePanelRepository(database.db), directory, messenger, - authz, log: log.child({ service: 'roles' }), legacy: legacyPanel(config), }); diff --git a/src/core/ports/chat.ts b/src/core/ports/chat.ts index 930b837..8444bcc 100644 --- a/src/core/ports/chat.ts +++ b/src/core/ports/chat.ts @@ -23,8 +23,6 @@ export type Messenger = { react: (channelId: string, messageId: string, emoji: string) => Promise; }; -export type NewRole = { name: string; color?: number; mentionable: boolean }; - export type Directory = { guildOf: (channelId: string) => Promise; channels: (guildId: string) => Promise; @@ -42,16 +40,6 @@ export type Directory = { roleIds: readonly string[], reason: string, ) => Promise; - createRole: ( - guildId: string, - role: NewRole, - reason: string, - ) => Promise; - deleteRole: ( - guildId: string, - roleId: string, - reason: string, - ) => Promise; }; export type CalendarEvent = { diff --git a/src/core/ports/roles.ts b/src/core/ports/roles.ts index 4a23d97..a499bf6 100644 --- a/src/core/ports/roles.ts +++ b/src/core/ports/roles.ts @@ -6,21 +6,6 @@ export type PanelRole = { emoji: string | null; }; -export type RolePanel = { - id: number; - guildId: string; - channelId: string; - messageId: string | null; - kind: PanelKind; - title: string; - roles: PanelRole[]; -}; - -export type PanelSummary = Pick< - RolePanel, - 'id' | 'title' | 'kind' | 'channelId' ->; - export type NewPanel = { guildId: string; channelId: string; @@ -38,18 +23,11 @@ export type ReactionKey = { export type RolePanelRepository = { reactionRole: (key: ReactionKey) => Promise; - find: (guildId: string, id: number) => Promise; - list: (guildId: string) => Promise; - selfAssignable: (guildId: string) => Promise; create: (panel: NewPanel) => Promise; reactionPanel: ( guildId: string, channelId: string, ) => Promise<{ id: number; messageId: string | null } | undefined>; setMessage: (id: number, messageId: string | null) => Promise; - setTitle: (id: number, title: string) => Promise; replaceRoles: (id: number, roles: readonly PanelRole[]) => Promise; - addRole: (id: number, role: PanelRole) => Promise; - removeRole: (id: number, roleId: string) => Promise; - remove: (id: number) => Promise; }; diff --git a/src/core/services/roles.ts b/src/core/services/roles.ts index 93d7c9c..eef43ce 100644 --- a/src/core/services/roles.ts +++ b/src/core/services/roles.ts @@ -1,28 +1,11 @@ -import { - channelMention, - controlId, - requireAbove, - requireManageable, - requireSelfAssignable, - roleMention, - selfAssignProblem, - UserError, - type Actor, - type Message, - type RoleInfo, -} from '~/domain'; +import { selfAssignProblem } from '~/domain'; import type { - Authorizer, Directory, Logger, Messenger, - NewRole, - PanelRole, - RolePanel, RolePanelRepository, } from '~/core/ports'; import { sequential } from '~/lib'; -import { guard } from './guard'; export const legacyMessage = 'Valige endale rolli:\n1 - Tarkvara\n2 - Helpdesk\n3 - Kultuur'; @@ -44,109 +27,12 @@ type Deps = { panels: RolePanelRepository; directory: Directory; messenger: Messenger; - authz: Authorizer; log: Logger; legacy?: LegacyPanel | undefined; }; -export function panelView(panel: RolePanel): Message { - return { - embeds: [ - { - title: panel.title, - description: - panel.roles.length === 0 - ? 'No roles yet.' - : panel.roles - .map((role) => `• ${roleMention(role.roleId)}`) - .join('\n'), - }, - ], - controls: - panel.roles.length === 0 - ? [] - : [ - [ - { - kind: 'button', - id: controlId('roles:open', panel.id), - label: 'Choose roles', - style: 'primary', - }, - ], - ], - }; -} - -export function choiceView(actor: Actor, panel: RolePanel): Message { - return { - content: - 'Pick the roles you want. Unselected roles from this panel are removed.', - controls: [ - [ - { - kind: 'select', - id: controlId('roles:choose', panel.id), - placeholder: 'Select your roles', - min: 0, - max: panel.roles.length, - options: panel.roles.map((role) => ({ - label: role.label, - value: role.roleId, - default: actor.roleIds.includes(role.roleId), - })), - }, - ], - ], - }; -} - export function createRoleService(deps: Deps) { - const { panels, directory, messenger, authz, log, legacy } = deps; - - const requirePanel = async (guildId: string, id: number) => { - const panel = await panels.find(guildId, id); - - if (!panel) { - throw new UserError(`Role panel #${id} does not exist.`); - } - - return panel; - }; - - const requireRole = async (guildId: string, roleId: string) => { - const role = await directory.role(guildId, roleId); - - if (!role) { - throw new UserError('That role no longer exists.'); - } - - return role; - }; - - const publish = async (panel: RolePanel) => { - const view = panelView(panel); - const edited = - panel.messageId !== null && - (await messenger.edit(panel.channelId, panel.messageId, view)); - - if (!edited) { - const sent = await messenger.send(panel.channelId, view); - - await panels.setMessage(panel.id, sent.messageId); - } - }; - - const assignable = (actor: Actor, role: RoleInfo) => { - requireAbove(actor, role); - requireManageable(role); - - if (role.administrator && !actor.administrator) { - throw new UserError( - 'Only administrators can hand out administrator roles.', - ); - } - }; + const { panels, directory, messenger, log, legacy } = deps; const postLegacy = async (channelId: string) => { log.info({ channelId }, 'Posting role selection message'); @@ -255,185 +141,7 @@ export function createRoleService(deps: Deps) { ); }; - return { - syncLegacyPanel, - reacted, - panels: (guildId: string) => panels.list(guildId), - overview: async (guildId: string) => ({ - roles: await panels.selfAssignable(guildId), - panels: await panels.list(guildId), - }), - open: async (actor: Actor, panelId: number) => { - const panel = await requirePanel(actor.guildId, panelId); - - if (panel.roles.length === 0) { - throw new UserError('This panel has no roles yet.'); - } - - return choiceView(actor, panel); - }, - choose: async ( - actor: Actor, - panelId: number, - wanted: readonly string[], - ) => { - const panel = await requirePanel(actor.guildId, panelId); - const selected = new Set(wanted); - const roles = await directory.roles(actor.guildId); - const byId = new Map(roles.map((role) => [role.id, role])); - const usable = panel.roles.filter((entry) => { - const role = byId.get(entry.roleId); - - return role !== undefined && selfAssignProblem(role) === undefined; - }); - const skipped = panel.roles.filter((entry) => !usable.includes(entry)); - const has = (roleId: string) => actor.roleIds.includes(roleId); - const toAdd = usable - .filter((entry) => selected.has(entry.roleId) && !has(entry.roleId)) - .map((entry) => entry.roleId); - const toRemove = usable - .filter((entry) => !selected.has(entry.roleId) && has(entry.roleId)) - .map((entry) => entry.roleId); - const member = { guildId: actor.guildId, userId: actor.userId }; - - if (toAdd.length > 0) { - await directory.addRoles(member, toAdd, 'Role panel selection'); - } - - if (toRemove.length > 0) { - await directory.removeRoles(member, toRemove, 'Role panel selection'); - } - - log.info({ ...member, toAdd, toRemove }, 'Updated roles from panel'); - - return { - changed: toAdd.length + toRemove.length, - skipped: skipped.map((s) => s.label), - }; - }, - createPanel: guard( - authz, - 'role:manage', - async (actor, channelId: string, title: string) => { - if (!(await directory.canPost(actor, channelId))) { - throw new UserError( - `You cannot post in ${channelMention(channelId)} yourself.`, - ); - } - - const id = await panels.create({ - guildId: actor.guildId, - channelId, - kind: 'select', - title, - createdBy: actor.userId, - }); - - await publish(await requirePanel(actor.guildId, id)); - - return id; - }, - ), - updatePanel: guard( - authz, - 'role:manage', - async ( - actor, - panelId: number, - changes: { add?: PanelRole; remove?: string; title?: string }, - ) => { - const panel = await requirePanel(actor.guildId, panelId); - - if (panel.kind === 'reaction') { - throw new UserError( - 'The legacy reaction panel is configured through environment variables.', - ); - } - - if (changes.add) { - const role = await requireRole(actor.guildId, changes.add.roleId); - - requireSelfAssignable(role); - requireAbove(actor, role); - await panels.addRole(panel.id, changes.add); - } - - if ( - changes.remove !== undefined && - !(await panels.removeRole(panel.id, changes.remove)) - ) { - throw new UserError('That role is not on this panel.'); - } - - if (changes.title !== undefined) { - await panels.setTitle(panel.id, changes.title); - } - - await publish(await requirePanel(actor.guildId, panel.id)); - }, - ), - removePanel: guard(authz, 'role:manage', async (actor, panelId: number) => { - const panel = await requirePanel(actor.guildId, panelId); - - if (panel.kind === 'reaction' && !actor.administrator) { - throw new UserError( - 'Only an administrator can remove the original role message.', - ); - } - - if (panel.messageId !== null) { - await messenger.remove(panel.channelId, panel.messageId); - } - - await panels.remove(panel.id); - log.info( - { panelId, actorId: actor.userId, kind: panel.kind }, - 'Role panel removed', - ); - - return panel; - }), - createRole: guard(authz, 'role:create', (actor, role: NewRole) => - directory.createRole(actor.guildId, role, `Requested by ${actor.userId}`), - ), - deleteRole: guard(authz, 'role:manage', async (actor, roleId: string) => { - const role = await requireRole(actor.guildId, roleId); - - requireAbove(actor, role); - requireManageable(role); - await directory.deleteRole( - actor.guildId, - roleId, - `Requested by ${actor.userId}`, - ); - - return role; - }), - assign: guard( - authz, - 'role:assign', - async (actor, userId: string, roleId: string) => { - assignable(actor, await requireRole(actor.guildId, roleId)); - await directory.addRoles( - { guildId: actor.guildId, userId }, - [roleId], - `Assigned by ${actor.userId}`, - ); - }, - ), - unassign: guard( - authz, - 'role:assign', - async (actor, userId: string, roleId: string) => { - assignable(actor, await requireRole(actor.guildId, roleId)); - await directory.removeRoles( - { guildId: actor.guildId, userId }, - [roleId], - `Removed by ${actor.userId}`, - ); - }, - ), - }; + return { syncLegacyPanel, reacted }; } export type RoleService = ReturnType; diff --git a/src/domain/role.ts b/src/domain/role.ts index 577621e..0291e01 100644 --- a/src/domain/role.ts +++ b/src/domain/role.ts @@ -33,20 +33,6 @@ export function selfAssignProblem(role: RoleInfo): string | undefined { return undefined; } -export function requireSelfAssignable(role: RoleInfo): void { - const problem = selfAssignProblem(role); - - if (problem !== undefined) { - throw new UserError(`${role.name} cannot be self-assigned: it ${problem}.`); - } -} - -export function requireAbove(actor: Actor, role: RoleInfo): void { - if (!actor.owner && actor.highestRolePosition <= role.position) { - throw new UserError(`${role.name} is not below your highest role.`); - } -} - export function requireManageable(role: RoleInfo): void { if (role.managed || !role.botCanAssign) { throw new UserError( diff --git a/src/infra/db/roles/repo.ts b/src/infra/db/roles/repo.ts index c47e14d..7ac8002 100644 --- a/src/infra/db/roles/repo.ts +++ b/src/infra/db/roles/repo.ts @@ -1,13 +1,8 @@ -import { and, asc, count, eq, max } from 'drizzle-orm'; +import { and, eq } from 'drizzle-orm'; import type { PanelRole, RolePanelRepository } from '~/core/ports'; import type { Db } from '../client'; -import { UserError } from '~/domain'; import { rolePanelRoles, rolePanels } from './model'; -export const maxPanelRoles = 25; - -export type Panel = typeof rolePanels.$inferSelect & { roles: PanelRole[] }; - export async function findReactionRole( db: Db, reaction: { @@ -35,77 +30,6 @@ export async function findReactionRole( return row?.roleId; } -export async function getPanel( - db: Db, - guildId: string, - panelId: number, -): Promise { - const [panel] = await db - .select() - .from(rolePanels) - .where(and(eq(rolePanels.id, panelId), eq(rolePanels.guildId, guildId))); - - if (!panel) { - return undefined; - } - - const roles = await db - .select({ - roleId: rolePanelRoles.roleId, - label: rolePanelRoles.label, - emoji: rolePanelRoles.emoji, - }) - .from(rolePanelRoles) - .where(eq(rolePanelRoles.panelId, panelId)) - .orderBy(asc(rolePanelRoles.position)); - - return { ...panel, roles }; -} - -export async function requirePanel( - db: Db, - guildId: string, - panelId: number, -): Promise { - const panel = await getPanel(db, guildId, panelId); - - if (!panel) { - throw new UserError(`Role panel #${panelId} does not exist.`); - } - - return panel; -} - -export async function listPanels(db: Db, guildId: string) { - return db - .select({ - id: rolePanels.id, - title: rolePanels.title, - kind: rolePanels.kind, - channelId: rolePanels.channelId, - }) - .from(rolePanels) - .where(eq(rolePanels.guildId, guildId)) - .orderBy(asc(rolePanels.id)) - .limit(100); -} - -export async function listSelfAssignableRoles( - db: Db, - guildId: string, -): Promise> { - return db - .selectDistinctOn([rolePanelRoles.roleId], { - roleId: rolePanelRoles.roleId, - panelId: rolePanelRoles.panelId, - }) - .from(rolePanelRoles) - .innerJoin(rolePanels, eq(rolePanels.id, rolePanelRoles.panelId)) - .where(eq(rolePanels.guildId, guildId)) - .orderBy(rolePanelRoles.roleId) - .limit(500); -} - export async function createPanel( db: Db, input: { @@ -158,14 +82,6 @@ export async function setPanelMessage( .where(eq(rolePanels.id, panelId)); } -export async function setPanelTitle( - db: Db, - panelId: number, - title: string, -): Promise { - await db.update(rolePanels).set({ title }).where(eq(rolePanels.id, panelId)); -} - export async function replacePanelRoles( db: Db, panelId: number, @@ -183,78 +99,13 @@ export async function replacePanelRoles( }); } -export async function addPanelRole( - db: Db, - panelId: number, - role: PanelRole, -): Promise { - await db.transaction(async (tx) => { - await tx - .select({ id: rolePanels.id }) - .from(rolePanels) - .where(eq(rolePanels.id, panelId)) - .for('update'); - const [stats] = await tx - .select({ total: count(), last: max(rolePanelRoles.position) }) - .from(rolePanelRoles) - .where(eq(rolePanelRoles.panelId, panelId)); - - if ((stats?.total ?? 0) >= maxPanelRoles) { - throw new UserError(`A panel can hold at most ${maxPanelRoles} roles.`); - } - - const inserted = await tx - .insert(rolePanelRoles) - .values({ ...role, panelId, position: (stats?.last ?? -1) + 1 }) - .onConflictDoNothing() - .returning({ roleId: rolePanelRoles.roleId }); - - if (inserted.length === 0) { - throw new UserError('That role is already on this panel.'); - } - }); -} - -export async function removePanelRole( - db: Db, - panelId: number, - roleId: string, -): Promise { - const rows = await db - .delete(rolePanelRoles) - .where( - and( - eq(rolePanelRoles.panelId, panelId), - eq(rolePanelRoles.roleId, roleId), - ), - ) - .returning({ roleId: rolePanelRoles.roleId }); - - return rows.length > 0; -} - -export async function deletePanel(db: Db, panelId: number): Promise { - await db.delete(rolePanels).where(eq(rolePanels.id, panelId)); -} - export function createRolePanelRepository(db: Db): RolePanelRepository { return { reactionRole: (key) => findReactionRole(db, key), - find: (guildId, id) => getPanel(db, guildId, id), - list: (guildId) => listPanels(db, guildId), - selfAssignable: async (guildId) => { - const rows = await listSelfAssignableRoles(db, guildId); - - return rows.map((row) => row.roleId); - }, create: (panel) => createPanel(db, panel), reactionPanel: (guildId, channelId) => findReactionPanel(db, guildId, channelId), setMessage: (id, messageId) => setPanelMessage(db, id, messageId), - setTitle: (id, title) => setPanelTitle(db, id, title), replaceRoles: (id, roles) => replacePanelRoles(db, id, roles), - addRole: (id, role) => addPanelRole(db, id, role), - removeRole: (id, roleId) => removePanelRole(db, id, roleId), - remove: (id) => deletePanel(db, id), }; } diff --git a/src/infra/discord/adapters.ts b/src/infra/discord/adapters.ts index 4889db3..0595736 100644 --- a/src/infra/discord/adapters.ts +++ b/src/infra/discord/adapters.ts @@ -185,25 +185,6 @@ export function createDiscordDirectory(client: Client): Directory { await permanent(() => member.roles.remove([...roleIds], reason)); }, - createRole: async (guildId, role, reason) => { - const found = await guild(guildId); - const created = await found.roles.create({ - name: role.name, - permissions: [], - mentionable: role.mentionable, - reason, - ...(role.color !== undefined && { - colors: { primaryColor: role.color }, - }), - }); - - return toRoleInfo(created); - }, - deleteRole: async (guildId, roleId, reason) => { - const found = await guild(guildId); - - await found.roles.delete(roleId, reason); - }, }; } diff --git a/src/infra/discord/commands/roles.ts b/src/infra/discord/commands/roles.ts index 6a5011b..4d87d91 100644 --- a/src/infra/discord/commands/roles.ts +++ b/src/infra/discord/commands/roles.ts @@ -1,162 +1,13 @@ import { - ChannelType, Events, - InteractionContextType, - SlashCommandBuilder, type MessageReaction, type PartialMessageReaction, type PartialUser, type User, } from 'discord.js'; import type { RoleService } from '~/core/services'; -import { channelMention, roleMention, userMention, UserError } from '~/domain'; -import { toActor } from '../actor'; -import { bySubcommand, deferred, defineListener } from '../define'; -import type { ComponentHandler, Feature, SlashCommand } from '../module'; -import { respond, respondView } from '../router'; - -const data = new SlashCommandBuilder() - .setName('role') - .setDescription('Manage roles and role panels') - .setContexts(InteractionContextType.Guild) - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Create a role without permissions') - .addStringOption((o) => - o - .setName('name') - .setDescription('Role name') - .setRequired(true) - .setMaxLength(100), - ) - .addStringOption((o) => - o.setName('color').setDescription('Hex color, e.g. #FFAC1C'), - ) - .addBooleanOption((o) => - o.setName('mentionable').setDescription('Allow anyone to mention it'), - ), - ) - .addSubcommand((sub) => - sub - .setName('delete') - .setDescription('Delete a role') - .addRoleOption((o) => - o.setName('role').setDescription('Role').setRequired(true), - ), - ) - .addSubcommand((sub) => - sub - .setName('assign') - .setDescription('Give a member a role') - .addUserOption((o) => - o.setName('member').setDescription('Member').setRequired(true), - ) - .addRoleOption((o) => - o.setName('role').setDescription('Role').setRequired(true), - ), - ) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription('Take a role from a member') - .addUserOption((o) => - o.setName('member').setDescription('Member').setRequired(true), - ) - .addRoleOption((o) => - o.setName('role').setDescription('Role').setRequired(true), - ), - ) - .addSubcommand((sub) => - sub.setName('list').setDescription('List self-assignable roles and panels'), - ) - .addSubcommandGroup((group) => - group - .setName('panel') - .setDescription('Role selection panels') - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Post a new role panel') - .addChannelOption((o) => - o - .setName('channel') - .setDescription('Channel') - .setRequired(true) - .addChannelTypes(ChannelType.GuildText), - ) - .addStringOption((o) => - o - .setName('title') - .setDescription('Panel title') - .setRequired(true) - .setMaxLength(200), - ), - ) - .addSubcommand((sub) => - sub - .setName('update') - .setDescription('Add or remove roles, or rename a panel') - .addIntegerOption((o) => - o - .setName('panel') - .setDescription('Panel') - .setRequired(true) - .setAutocomplete(true), - ) - .addRoleOption((o) => o.setName('add').setDescription('Role to add')) - .addStringOption((o) => - o - .setName('label') - .setDescription('Label for the added role') - .setMaxLength(100), - ) - .addRoleOption((o) => - o.setName('remove').setDescription('Role to remove'), - ) - .addStringOption((o) => - o.setName('title').setDescription('New title').setMaxLength(200), - ), - ) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription( - 'Delete a panel and its message (including the legacy reaction panel)', - ) - .addIntegerOption((o) => - o - .setName('panel') - .setDescription('Panel') - .setRequired(true) - .setAutocomplete(true), - ), - ), - ); - -function parseColor(value: string | null): number | undefined { - if (value === null) { - return undefined; - } - - const match = /^#?([\da-f]{6})$/i.exec(value); - - if (match?.[1] === undefined) { - throw new UserError('Color must be a hex value like #FFAC1C.'); - } - - return Number.parseInt(match[1], 16); -} - -function panelId(args: readonly string[]): number { - const id = Number(args[0]); - - if (!Number.isSafeInteger(id)) { - throw new UserError('This role panel is invalid.'); - } - - return id; -} +import { defineListener } from '../define'; +import type { Feature } from '../module'; function reactionOf( reaction: MessageReaction | PartialMessageReaction, @@ -179,171 +30,6 @@ function reactionOf( } export function roleCommands(roles: RoleService): Feature { - const command: SlashCommand = { - data: data.toJSON(), - execute: bySubcommand({ - create: deferred(async (interaction) => { - const color = parseColor(interaction.options.getString('color')); - const role = await roles.createRole(toActor(interaction.member), { - name: interaction.options.getString('name', true), - mentionable: interaction.options.getBoolean('mentionable') ?? false, - ...(color !== undefined && { color }), - }); - - await respond(interaction, `Created ${roleMention(role.id)}.`); - }), - delete: deferred(async (interaction) => { - const role = interaction.options.getRole('role', true); - const deleted = await roles.deleteRole( - toActor(interaction.member), - role.id, - ); - - await respond(interaction, `Deleted ${deleted.name}.`); - }), - assign: deferred(async (interaction) => { - const role = interaction.options.getRole('role', true); - const user = interaction.options.getUser('member', true); - - await roles.assign(toActor(interaction.member), user.id, role.id); - await respond( - interaction, - `Gave ${roleMention(role.id)} to ${userMention(user.id)}.`, - ); - }), - remove: deferred(async (interaction) => { - const role = interaction.options.getRole('role', true); - const user = interaction.options.getUser('member', true); - - await roles.unassign(toActor(interaction.member), user.id, role.id); - await respond( - interaction, - `Removed ${roleMention(role.id)} from ${userMention(user.id)}.`, - ); - }), - list: async (interaction) => { - const overview = await roles.overview(interaction.guildId); - const lines = [ - '**Self-assignable roles**', - ...(overview.roles.length === 0 - ? ['None yet.'] - : overview.roles.map((id) => `• ${roleMention(id)}`)), - '', - '**Panels**', - ...(overview.panels.length === 0 - ? ['None yet.'] - : overview.panels.map( - (p) => - `• #${p.id} ${p.title} (${p.kind}) in ${channelMention(p.channelId)}`, - )), - ]; - - await respond(interaction, lines.join('\n')); - }, - 'panel create': deferred(async (interaction) => { - const channel = interaction.options.getChannel('channel', true, [ - ChannelType.GuildText, - ]); - const id = await roles.createPanel( - toActor(interaction.member), - channel.id, - interaction.options.getString('title', true), - ); - - await respond( - interaction, - `Created panel #${id}. Add roles with "/role panel update panel:${id} add:".`, - ); - }), - 'panel update': deferred(async (interaction) => { - const add = interaction.options.getRole('add'); - const remove = interaction.options.getRole('remove'); - const title = interaction.options.getString('title'); - const id = interaction.options.getInteger('panel', true); - - await roles.updatePanel(toActor(interaction.member), id, { - ...(add && { - add: { - roleId: add.id, - label: interaction.options.getString('label') ?? add.name, - emoji: null, - }, - }), - ...(remove && { remove: remove.id }), - ...(title !== null && { title }), - }); - await respond(interaction, `Panel #${id} updated.`); - }), - 'panel remove': deferred(async (interaction) => { - const panel = await roles.removePanel( - toActor(interaction.member), - interaction.options.getInteger('panel', true), - ); - const note = - panel.kind === 'reaction' - ? ' Unset ROLE_SELECTION_CHANNEL_ID, or it will be posted again on the next start.' - : ''; - - await respond(interaction, `Removed panel #${panel.id}.${note}`); - }), - }), - autocomplete: async (interaction) => { - const query = interaction.options.getFocused().toLowerCase(); - const panels = await roles.panels(interaction.guildId); - - await interaction.respond( - panels - .filter( - (p) => - p.title.toLowerCase().includes(query) || String(p.id) === query, - ) - .slice(0, 25) - .map((p) => ({ - name: `#${p.id} ${p.title}`.slice(0, 100), - value: p.id, - })), - ); - }, - }; - - const open: ComponentHandler = { - prefix: 'roles:open', - execute: async (interaction, args) => { - await respondView( - interaction, - await roles.open(toActor(interaction.member), panelId(args)), - ); - }, - }; - - const choose: ComponentHandler = { - prefix: 'roles:choose', - execute: async (interaction, args) => { - if (!interaction.isStringSelectMenu()) { - return; - } - - await interaction.deferUpdate(); - - const result = await roles.choose( - toActor(interaction.member), - panelId(args), - interaction.values, - ); - const lines = [ - result.changed === 0 ? 'No changes.' : 'Your roles are updated.', - ...(result.skipped.length > 0 - ? [`Unavailable right now: ${result.skipped.join(', ')}`] - : []), - ]; - - await interaction.editReply({ - content: lines.join('\n'), - components: [], - }); - }, - }; - const added = defineListener( Events.MessageReactionAdd, async (_ctx, reaction, user) => { @@ -367,13 +53,6 @@ export function roleCommands(roles: RoleService): Feature { return { name: 'roles', - permissions: [ - { id: 'role:create', description: 'Create roles' }, - { id: 'role:manage', description: 'Delete roles and manage role panels' }, - { id: 'role:assign', description: 'Assign roles to other members' }, - ], - commands: [command], - components: [open, choose], events: [added, removed], start: () => roles.syncLegacyPanel(), }; diff --git a/tests/core/services/roles.test.ts b/tests/core/services/roles.test.ts index 8621695..3d3c982 100644 --- a/tests/core/services/roles.test.ts +++ b/tests/core/services/roles.test.ts @@ -2,29 +2,20 @@ import { describe, expect, it } from 'vitest'; import { createRoleService, legacyMessage } from '~/core/services'; import { createRolePanelRepository } from '~/infra/db'; import { noDatabase, snowflake, testDb } from '../../db'; -import { - actor, - allowAll, - fakeDirectory, - fakeMessenger, - role, - silentLog, -} from '../../fakes'; +import { fakeDirectory, fakeMessenger, role, silentLog } from '../../fakes'; describe.skipIf(noDatabase)('role service', () => { const setup = ( roles = [role({ id: 'tarkvara' }), role({ id: 'helpdesk' })], - canPost = true, ) => { const guildId = snowflake(); const channelId = snowflake(); const { messenger, sent } = fakeMessenger(); - const directory = fakeDirectory(roles, { canPost, guildId }); + const directory = fakeDirectory(roles, { guildId }); const service = createRoleService({ panels: createRolePanelRepository(testDb()), directory, messenger, - authz: allowAll, log: silentLog, legacy: { channelId, @@ -97,61 +88,4 @@ describe.skipIf(noDatabase)('role service', () => { ); expect(directory.addRoles).not.toHaveBeenCalled(); }); - - it('only lets administrators remove the legacy panel', async () => { - const { service, guildId } = setup(); - - await service.syncLegacyPanel(); - - const [legacy] = await service.panels(guildId); - - await expect( - service.removePanel(actor({ guildId }), legacy?.id ?? 0), - ).rejects.toThrow('administrator'); - await expect( - service.removePanel( - actor({ guildId, administrator: true }), - legacy?.id ?? 0, - ), - ).resolves.toBeDefined(); - }); - - it('applies select-menu choices and ignores forged role IDs', async () => { - const { service, directory, guildId, channelId } = setup(); - const id = await service.createPanel( - actor({ guildId }), - channelId, - 'Teams', - ); - - await service.updatePanel(actor({ guildId }), id, { - add: { roleId: 'tarkvara', label: 'Tarkvara', emoji: null }, - }); - await service.updatePanel(actor({ guildId }), id, { - add: { roleId: 'helpdesk', label: 'Helpdesk', emoji: null }, - }); - - const member = actor({ guildId, roleIds: ['helpdesk'] }); - const result = await service.choose(member, id, ['tarkvara', 'admin']); - - expect(result.changed).toBe(2); - expect(directory.addRoles).toHaveBeenCalledWith( - expect.anything(), - ['tarkvara'], - expect.any(String), - ); - expect(directory.removeRoles).toHaveBeenCalledWith( - expect.anything(), - ['helpdesk'], - expect.any(String), - ); - }); - - it('refuses panels in channels the member cannot post in', async () => { - const { service, guildId, channelId } = setup(undefined, false); - - await expect( - service.createPanel(actor({ guildId }), channelId, 'x'), - ).rejects.toThrow('cannot post'); - }); }); diff --git a/tests/domain/role.test.ts b/tests/domain/role.test.ts index 07cbf66..a0689c2 100644 --- a/tests/domain/role.test.ts +++ b/tests/domain/role.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { requireAbove, selfAssignProblem } from '~/domain'; -import { actor, role } from '../fakes'; +import { selfAssignProblem } from '~/domain'; +import { role } from '../fakes'; describe('role rules', () => { it('accepts ordinary assignable roles', () => { @@ -15,19 +15,4 @@ describe('role rules', () => { ])('rejects %s roles', (_name, candidate) => { expect(selfAssignProblem(candidate)).toBeDefined(); }); - - it('only lets members manage roles below their highest role', () => { - expect(() => - requireAbove(actor({ highestRolePosition: 2 }), role({ position: 1 })), - ).not.toThrow(); - expect(() => - requireAbove(actor({ highestRolePosition: 1 }), role({ position: 1 })), - ).toThrow('not below'); - expect(() => - requireAbove( - actor({ highestRolePosition: 1, owner: true }), - role({ position: 5 }), - ), - ).not.toThrow(); - }); }); diff --git a/tests/fakes.ts b/tests/fakes.ts index d351314..a4718a3 100644 --- a/tests/fakes.ts +++ b/tests/fakes.ts @@ -97,10 +97,6 @@ export function fakeDirectory( canPost: vi.fn(async () => options.canPost ?? true), addRoles: vi.fn(async () => undefined), removeRoles: vi.fn(async () => undefined), - createRole: vi.fn(async (_g, r) => - role({ name: r.name }), - ), - deleteRole: vi.fn(async () => undefined), } satisfies Directory; return directory; From b7a4ff68b93183090a18f5901ec1db2855f19626 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:09:28 +0200 Subject: [PATCH 047/199] refactor(scheduler): run jobs on pg-boss instead of the hand-rolled runner --- package.json | 1 + pnpm-lock.yaml | 193 +++++++++++++++++++- src/app.ts | 31 ++-- src/core/ports/scheduler.ts | 15 +- src/core/services/announcements.ts | 4 +- src/core/services/birthdays.ts | 2 +- src/core/services/events.ts | 2 +- src/core/services/jobs.ts | 13 +- src/core/services/polls.ts | 4 +- src/core/services/reminders.ts | 2 +- src/infra/scheduler/boss.ts | 91 ++++++++++ src/infra/scheduler/index.ts | 3 +- src/infra/scheduler/queue.ts | 17 -- src/infra/scheduler/runner.ts | 128 -------------- tests/core/services/announcements.test.ts | 10 +- tests/core/services/birthdays.test.ts | 5 +- tests/core/services/events.test.ts | 5 +- tests/core/services/polls.test.ts | 5 +- tests/core/services/redmine.test.ts | 9 +- tests/core/services/reminders.test.ts | 10 +- tests/global-setup.ts | 1 + tests/infra/scheduler/boss.test.ts | 79 +++++++++ tests/infra/scheduler/runner.test.ts | 205 ---------------------- 23 files changed, 409 insertions(+), 426 deletions(-) create mode 100644 src/infra/scheduler/boss.ts delete mode 100644 src/infra/scheduler/queue.ts delete mode 100644 src/infra/scheduler/runner.ts create mode 100644 tests/infra/scheduler/boss.test.ts delete mode 100644 tests/infra/scheduler/runner.test.ts diff --git a/package.json b/package.json index 62cfaa1..d514fd2 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "date-fns": "^4.4.0", "discord.js": "^14.28.1", "drizzle-orm": "^0.45.4", + "pg-boss": "^12.38.2", "pino": "^10.4.0", "postgres": "^3.4.9", "zod": "^4.6.7" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 97c54d9..1b00b4f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,7 +19,10 @@ importers: version: 14.28.1 drizzle-orm: specifier: ^0.45.4 - version: 0.45.4(postgres@3.4.9) + version: 0.45.4(@opentelemetry/api@1.10.0)(pg@8.23.1)(postgres@3.4.9) + pg-boss: + specifier: ^12.38.2 + version: 12.38.2(@opentelemetry/api@1.10.0) pino: specifier: ^10.4.0 version: 10.4.0 @@ -89,7 +92,7 @@ importers: version: 8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) vitest: specifier: ^5.1.0 - version: 5.1.0(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) + version: 5.1.0(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) packages: @@ -686,6 +689,10 @@ packages: '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 + '@opentelemetry/api@1.10.0': + resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} + engines: {node: '>=8.0.0'} + '@oxc-project/types@0.156.0': resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} @@ -1280,6 +1287,10 @@ packages: resolution: {integrity: sha512-52r6fkXgxv4GLMjmFcMWRx7X9bw071xTTdrDcdyPGRqU2oE+9pCG0bAOMifSBdLw0JRBZKEF0q3B55qPlLuE8g==} engines: {node: '>=6.4.0'} + cron-parser@5.10.6: + resolution: {integrity: sha512-kpoxgQyveO1l29nw+FWdvmotyV7eOSzGHQpxiXOEZIDOjqO1iR6kfgJ0PVHTuV26uBemKq3ppzma7dHFAG7viw==} + engines: {node: '>=18'} + cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -1829,6 +1840,10 @@ packages: lodash@4.18.1: resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + luxon@3.7.2: + resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} + engines: {node: '>=12'} + magic-bytes.js@1.13.1: resolution: {integrity: sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==} @@ -1932,6 +1947,10 @@ packages: resolution: {integrity: sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==} engines: {node: '>=18'} + non-error@0.1.0: + resolution: {integrity: sha512-TMB1uHiGsHRGv1uYclfhivcnf0/PdFp2pNqRxXjncaAsjYMoisaQJI+SSZCqRq+VliwRTC8tsMQfmrWjDMhkPQ==} + engines: {node: '>=20'} + obug@3.0.0: resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} @@ -1966,6 +1985,47 @@ packages: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} + pg-boss@12.38.2: + resolution: {integrity: sha512-nvB9hB2cDJGSPUwYjN/Mth+EE3zvxffkp7uKXIiYloMAaxSoEiutmZi9mpSW85hNCcPChf3yicNXdwhIWkv2nA==} + engines: {node: '>=22.12.0'} + hasBin: true + peerDependencies: + '@opentelemetry/api': ^1.9.0 + + pg-cloudflare@1.4.1: + resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==} + + pg-connection-string@2.14.1: + resolution: {integrity: sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-pool@3.14.0: + resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.16.1: + resolution: {integrity: sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg@8.23.1: + resolution: {integrity: sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -1995,6 +2055,22 @@ packages: resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} engines: {node: ^10 || ^12 || >=14} + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + postgres@3.4.9: resolution: {integrity: sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw==} engines: {node: '>=12'} @@ -2086,6 +2162,9 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + rrule-temporal@2.2.9: + resolution: {integrity: sha512-5Bc+IxlGKZtOF/JtkM+39VtK9uYvg1NRWGzZCy2QQj9KFZ4mMMa949GMtGv0Ud/bzyk2KuGhwxmVDuq8cnbzuA==} + safe-stable-stringify@2.5.0: resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} engines: {node: '>=10'} @@ -2102,6 +2181,10 @@ packages: engines: {node: '>=10'} hasBin: true + serialize-error@13.1.0: + resolution: {integrity: sha512-FT1EL2Pz7lAWA48I6Qb1qHEvGT9ZGz2pb1sYZ9Dhu2t+RmHN6O12WMu7HzFcqFRQaUWEl3Q+++EYBTrZpCoykQ==} + engines: {node: '>=20'} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -2146,6 +2229,13 @@ packages: resolution: {integrity: sha512-ErcwpJBYr8EfX/Br7JauOIGXoRE92w0hVtuS9j92UFgbATxA+WRSIZksSUDzEeItfWB/0QCEprTZT55RSINUHQ==} engines: {node: '>=22'} + tagged-tag@1.0.0: + resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} + engines: {node: '>=20'} + + temporal-spec@1.0.1: + resolution: {integrity: sha512-wxVoanmDeavXie1vu2JaQ3WIc3JZnWAOYFBsJyATaVsXsycKYUflGsyBmrRSnoCpZJpwPyr38VpgSUlQ8CbFxg==} + thread-stream@4.2.1: resolution: {integrity: sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ==} engines: {node: '>=20'} @@ -2220,6 +2310,10 @@ packages: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} + type-fest@5.10.0: + resolution: {integrity: sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==} + engines: {node: '>=20'} + typescript-eslint@8.72.2: resolution: {integrity: sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2374,6 +2468,10 @@ packages: utf-8-validate: optional: true + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} @@ -2791,6 +2889,8 @@ snapshots: '@tybys/wasm-util': 0.10.4 optional: true + '@opentelemetry/api@1.10.0': {} + '@oxc-project/types@0.156.0': {} '@oxc-project/types@0.158.0': {} @@ -3222,6 +3322,10 @@ snapshots: dependencies: browserslist: 4.29.5 + cron-parser@5.10.6: + dependencies: + luxon: 3.7.2 + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -3282,8 +3386,10 @@ snapshots: esbuild: 0.25.12 tsx: 4.23.15 - drizzle-orm@0.45.4(postgres@3.4.9): + drizzle-orm@0.45.4(@opentelemetry/api@1.10.0)(pg@8.23.1)(postgres@3.4.9): optionalDependencies: + '@opentelemetry/api': 1.10.0 + pg: 8.23.1 postgres: 3.4.9 dts-resolver@3.0.0: {} @@ -3730,6 +3836,8 @@ snapshots: lodash@4.18.1: {} + luxon@3.7.2: {} + magic-bytes.js@1.13.1: {} magic-string@1.4.5: @@ -3891,6 +3999,8 @@ snapshots: node-releases@2.0.64: {} + non-error@0.1.0: {} + obug@3.0.0: {} on-exit-leak-free@2.1.2: {} @@ -3924,6 +4034,51 @@ snapshots: path-key@3.1.1: {} + pg-boss@12.38.2(@opentelemetry/api@1.10.0): + dependencies: + '@opentelemetry/api': 1.10.0 + cron-parser: 5.10.6 + pg: 8.23.1 + rrule-temporal: 2.2.9 + serialize-error: 13.1.0 + transitivePeerDependencies: + - pg-native + + pg-cloudflare@1.4.1: + optional: true + + pg-connection-string@2.14.1: {} + + pg-int8@1.0.1: {} + + pg-pool@3.14.0(pg@8.23.1): + dependencies: + pg: 8.23.1 + + pg-protocol@1.16.1: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg@8.23.1: + dependencies: + pg-connection-string: 2.14.1 + pg-pool: 3.14.0(pg@8.23.1) + pg-protocol: 1.16.1 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.4.1 + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + picocolors@1.1.1: {} picomatch@4.0.7: {} @@ -3972,6 +4127,16 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 + postgres-array@2.0.0: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + postgres@3.4.9: {} prelude-ls@1.2.1: {} @@ -4073,6 +4238,10 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.3.2 '@rolldown/binding-win32-x64-msvc': 1.3.2 + rrule-temporal@2.2.9: + dependencies: + temporal-spec: 1.0.1 + safe-stable-stringify@2.5.0: {} scslre@0.3.0: @@ -4085,6 +4254,11 @@ snapshots: semver@7.8.6: {} + serialize-error@13.1.0: + dependencies: + non-error: 0.1.0 + type-fest: 5.10.0 + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 @@ -4118,6 +4292,10 @@ snapshots: strip-json-comments@5.1.0: {} + tagged-tag@1.0.0: {} + + temporal-spec@1.0.1: {} + thread-stream@4.2.1: dependencies: real-require: 1.0.0 @@ -4178,6 +4356,10 @@ snapshots: dependencies: prelude-ls: 1.2.1 + type-fest@5.10.0: + dependencies: + tagged-tag: 1.0.0 + typescript-eslint@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3): dependencies: '@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) @@ -4255,7 +4437,7 @@ snapshots: tsx: 4.23.15 yaml: 2.9.1 - vitest@5.1.0(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)): + vitest@5.1.0(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.1.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) @@ -4272,6 +4454,7 @@ snapshots: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) why-is-node-running: 3.2.1 optionalDependencies: + '@opentelemetry/api': 1.10.0 '@types/node': 24.19.2 transitivePeerDependencies: - msw @@ -4288,6 +4471,8 @@ snapshots: ws@8.23.0: {} + xtend@4.0.2: {} + yaml@2.9.1: {} yocto-queue@0.1.0: {} diff --git a/src/app.ts b/src/app.ts index a2d99ce..0affa9d 100644 --- a/src/app.ts +++ b/src/app.ts @@ -32,7 +32,8 @@ import { } from '~/core/services'; import type { AppContext, Feature, Registry } from '~/infra/discord'; import type { Logger } from '~/infra/logging'; -import { createJobQueue, createJobRunner } from '~/infra/scheduler'; +import { PgBoss } from 'pg-boss'; +import { createJobQueue, startJobs } from '~/infra/scheduler'; import { systemClock, type Directory, type Job } from '~/core/ports'; import type { Actor } from '~/domain'; import { @@ -89,7 +90,8 @@ export function compose(config: Config, log: Logger) { legacy: legacyPanel(config), }); const timezone = config.DEFAULT_TIMEZONE; - const scheduler = createJobQueue(database.db); + const boss = new PgBoss({ connectionString: config.DATABASE_URL }); + const scheduler = createJobQueue(boss); const reminders = createReminderService({ reminders: createReminderRepository(database.db), scheduler, @@ -204,6 +206,7 @@ export function compose(config: Config, log: Logger) { return { database, + boss, client, authz, registry, @@ -268,19 +271,21 @@ export async function startApp( config: Config, log: Logger, ): Promise<() => Promise> { - const { database, client, authz, registry, directory, jobs, web } = compose( - config, - log, - ); + const { database, boss, client, authz, registry, directory, jobs, web } = + compose(config, log); + const jobLog = log.child({ component: 'scheduler' }); + + boss.on('error', (error) => { + jobLog.error({ err: error }, 'Job queue error'); + }); try { await runMigrations(database.db); - const runner = createJobRunner( - database.db, - jobs, - log.child({ component: 'scheduler' }), - ); + await boss.start(); const ready = await waitForReady(client, config.DISCORD_TOKEN); + + await startJobs(boss, jobs.values(), jobLog); + const ctx: AppContext = { log, authz }; for (const feature of registry.features) { @@ -315,7 +320,6 @@ export async function startApp( } }), ); - runner.start(); const stopWeb = await startWeb(config, { directory, @@ -332,11 +336,12 @@ export async function startApp( return async () => { client.removeAllListeners(Events.InteractionCreate); await stopWeb(); - await runner.stop(); + await boss.stop(); await client.destroy(); await database.close(); }; } catch (error) { + await boss.stop().catch(() => null); await client.destroy(); await database.close(); throw error; diff --git a/src/core/ports/scheduler.ts b/src/core/ports/scheduler.ts index b6a389f..fbf354a 100644 --- a/src/core/ports/scheduler.ts +++ b/src/core/ports/scheduler.ts @@ -1,25 +1,18 @@ -export type JobInfo = { id: number; runAt: Date; attempt: number }; - export type JobOutcome = null | { rescheduleAt: Date }; export type Job

= { type: string; - maxAttempts: number; - run: (raw: unknown, info: JobInfo) => Promise; + run: (raw: unknown) => Promise; payloadType?: P; }; -export type ScheduleOptions = { - runAt: Date; - key?: string; - maxAttempts?: number; -}; +export type ScheduleOptions = { runAt: Date; key: string }; export type Scheduler = { - schedule:

( + schedule:

( job: Job

, payload: P, options: ScheduleOptions, ) => Promise; - cancel: (key: string) => Promise; + cancel:

(job: Job

, key: string) => Promise; }; diff --git a/src/core/services/announcements.ts b/src/core/services/announcements.ts index f7b1387..137a279 100644 --- a/src/core/services/announcements.ts +++ b/src/core/services/announcements.ts @@ -290,7 +290,7 @@ export function createAnnouncementService(deps: Deps) { }, publish: guard(authz, 'announcement:publish', async (actor, id: number) => { await requireOwnGuild(actor, id); - await scheduler.cancel(jobKey(id)); + await scheduler.cancel(publishJob, jobKey(id)); return publish(id, reopenable); }), @@ -336,7 +336,7 @@ export function createAnnouncementService(deps: Deps) { ); } - await scheduler.cancel(jobKey(id)); + await scheduler.cancel(publishJob, jobKey(id)); return cancelled; }, diff --git a/src/core/services/birthdays.ts b/src/core/services/birthdays.ts index 11e76c2..3a4196a 100644 --- a/src/core/services/birthdays.ts +++ b/src/core/services/birthdays.ts @@ -219,7 +219,7 @@ export function createBirthdayService(deps: Deps) { async (actor, change: BirthdayConfiguration) => { if (change.disable === true) { await birthdays.deleteSettings(actor.guildId); - await scheduler.cancel(dailyKey(actor.guildId)); + await scheduler.cancel(dailyJob, dailyKey(actor.guildId)); return 'Birthday announcements are off.'; } diff --git a/src/core/services/events.ts b/src/core/services/events.ts index eb38f18..0292004 100644 --- a/src/core/services/events.ts +++ b/src/core/services/events.ts @@ -229,7 +229,7 @@ export function createEventService(deps: Deps) { ) => { await Promise.all( previous.map((minutes) => - scheduler.cancel(reminderKey(event.id, minutes)), + scheduler.cancel(remindJob, reminderKey(event.id, minutes)), ), ); diff --git a/src/core/services/jobs.ts b/src/core/services/jobs.ts index a70f42a..f833629 100644 --- a/src/core/services/jobs.ts +++ b/src/core/services/jobs.ts @@ -1,27 +1,22 @@ import type { z } from 'zod'; import { PermanentError } from '~/domain'; -import type { Job, JobInfo, JobOutcome } from '~/core/ports'; +import type { Job, JobOutcome } from '~/core/ports'; export function defineJob(definition: { type: string; payload: S; - maxAttempts?: number; - handle: ( - payload: z.infer, - info: JobInfo, - ) => Promise; + handle: (payload: z.infer) => Promise; }): Job> { return { type: definition.type, - maxAttempts: definition.maxAttempts ?? 5, - run: async (raw, info) => { + run: async (raw) => { const parsed = definition.payload.safeParse(raw); if (!parsed.success) { throw new PermanentError(`Invalid payload: ${parsed.error.message}`); } - return (await definition.handle(parsed.data, info)) ?? null; + return (await definition.handle(parsed.data)) ?? null; }, }; } diff --git a/src/core/services/polls.ts b/src/core/services/polls.ts index a2e660d..8163933 100644 --- a/src/core/services/polls.ts +++ b/src/core/services/polls.ts @@ -275,7 +275,7 @@ export function createPollService(deps: Deps) { throw new UserError('That poll is not open.'); } - await scheduler.cancel(closeKey(id)); + await scheduler.cancel(closeJob, closeKey(id)); await refresh(id); }, cancel: async (actor: Actor, id: number) => { @@ -285,7 +285,7 @@ export function createPollService(deps: Deps) { throw new UserError('That poll is not open.'); } - await scheduler.cancel(closeKey(id)); + await scheduler.cancel(closeJob, closeKey(id)); await refresh(id); }, }; diff --git a/src/core/services/reminders.ts b/src/core/services/reminders.ts index 7869e20..121d2de 100644 --- a/src/core/services/reminders.ts +++ b/src/core/services/reminders.ts @@ -192,7 +192,7 @@ export function createReminderService(deps: Deps) { cancel: async (actor: Actor, id: number) => { await own(actor, id); await reminders.update(id, { status: 'cancelled' }); - await scheduler.cancel(jobKey(id)); + await scheduler.cancel(deliverJob, jobKey(id)); }, }; } diff --git a/src/infra/scheduler/boss.ts b/src/infra/scheduler/boss.ts new file mode 100644 index 0000000..f78c155 --- /dev/null +++ b/src/infra/scheduler/boss.ts @@ -0,0 +1,91 @@ +import type { JobWithMetadata, PgBoss } from 'pg-boss'; +import type { Job, Logger, Scheduler } from '~/core/ports'; +import { PermanentError } from '~/domain'; +import { sequential } from '~/lib'; + +const queueOptions = { + policy: 'short', + retryLimit: 4, + retryDelay: 30, + retryBackoff: true, + retryDelayMax: 3600, +} as const; + +export function createJobQueue(boss: PgBoss): Scheduler { + return { + schedule: async (job, payload, { runAt, key }) => { + await boss.upsert(job.type, payload, { + singletonKey: key, + startAfter: runAt, + }); + }, + cancel: async (job, key) => { + const queued = await boss.findJobs(job.type, { key, queued: true }); + + if (queued.length > 0) { + await boss.cancel( + job.type, + queued.map((found) => found.id), + ); + } + }, + }; +} + +export async function startJobs( + boss: PgBoss, + jobs: Iterable>, + log: Logger, +): Promise { + await sequential(jobs, async (job) => { + if (!(await boss.getQueue(job.type))) { + await boss.createQueue(job.type, queueOptions); + } + + await boss.work( + job.type, + { includeMetadata: true, perJobResults: true }, + (batch: JobWithMetadata[]) => + Promise.all( + batch.map(async (found) => { + try { + const outcome = await job.run(found.data); + + if (outcome && found.singletonKey !== null) { + await boss.upsert(job.type, found.data, { + singletonKey: found.singletonKey, + startAfter: outcome.rescheduleAt, + }); + } + + return { id: found.id, status: 'completed' as const }; + } catch (error) { + const permanent = error instanceof PermanentError; + + log.error( + { + err: error, + jobId: found.id, + jobType: job.type, + attempt: found.retryCount + 1, + permanent, + }, + 'Job failed', + ); + + return { + id: found.id, + status: permanent + ? ('deadletter' as const) + : ('failed' as const), + output: { + message: + error instanceof Error ? error.message : String(error), + }, + }; + } + }), + ), + ); + }); +} diff --git a/src/infra/scheduler/index.ts b/src/infra/scheduler/index.ts index a4c109e..9185310 100644 --- a/src/infra/scheduler/index.ts +++ b/src/infra/scheduler/index.ts @@ -1,2 +1 @@ -export * from './queue'; -export * from './runner'; +export * from './boss'; diff --git a/src/infra/scheduler/queue.ts b/src/infra/scheduler/queue.ts deleted file mode 100644 index 0226b40..0000000 --- a/src/infra/scheduler/queue.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Scheduler } from '~/core/ports'; -import { cancelJob, upsertJob, type Db } from '~/infra/db'; - -export function createJobQueue(db: Db): Scheduler { - return { - schedule: async (job, payload, options) => { - await upsertJob(db, { - type: job.type, - payload, - runAt: options.runAt, - key: options.key, - maxAttempts: options.maxAttempts ?? job.maxAttempts, - }); - }, - cancel: (key) => cancelJob(db, key), - }; -} diff --git a/src/infra/scheduler/runner.ts b/src/infra/scheduler/runner.ts deleted file mode 100644 index 7ecc605..0000000 --- a/src/infra/scheduler/runner.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { setTimeout as sleep } from 'node:timers/promises'; -import type { Db, JobRow } from '~/infra/db'; -import { PermanentError } from '~/domain'; -import type { Job, Logger } from '~/core/ports'; -import { claimDueJobs, finishJob } from '~/infra/db'; - -export type RunnerOptions = { - pollIntervalMs?: number; - batchSize?: number; - leaseMs?: number; -}; - -export type JobRunner = { - tick: () => Promise; - start: () => void; - stop: () => Promise; -}; - -const maxBackoffMs = 60 * 60 * 1000; - -export function retryDelayMs(attempt: number): number { - return Math.min(30_000 * 2 ** (attempt - 1), maxBackoffMs); -} - -export function createJobRunner( - db: Db, - jobs: ReadonlyMap>, - log: Logger, - options: RunnerOptions = {}, -): JobRunner { - const pollIntervalMs = options.pollIntervalMs ?? 5000; - const batchSize = options.batchSize ?? 10; - const leaseMs = options.leaseMs ?? 5 * 60 * 1000; - const types = [...jobs.keys()]; - const abort = new AbortController(); - let loop: Promise | undefined; - - async function execute(row: JobRow): Promise { - const job = jobs.get(row.type); - const jobLog = log.child({ jobId: row.id, jobType: row.type }); - - if (!job) { - return; - } - - if (row.attempts > row.maxAttempts) { - await finishJob(db, row.id, { - kind: 'failed', - error: 'Exceeded max attempts', - }); - - return; - } - - try { - const outcome = await job.run(row.payload, { - id: row.id, - runAt: row.runAt, - attempt: row.attempts, - }); - - await finishJob( - db, - row.id, - outcome - ? { kind: 'reschedule', runAt: outcome.rescheduleAt } - : { kind: 'done' }, - ); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - const permanent = - error instanceof PermanentError || row.attempts >= row.maxAttempts; - - jobLog.error( - { err: error, attempt: row.attempts, permanent }, - 'Job failed', - ); - await finishJob( - db, - row.id, - permanent - ? { kind: 'failed', error: message } - : { - kind: 'retry', - error: message, - runAt: new Date(Date.now() + retryDelayMs(row.attempts)), - }, - ); - } - } - - async function tick(): Promise { - const rows = await claimDueJobs(db, { types, limit: batchSize, leaseMs }); - - await Promise.all(rows.map((row) => execute(row))); - - return rows.length; - } - - async function run(): Promise { - while (!abort.signal.aborted) { - let claimed = 0; - - try { - claimed = await tick(); - } catch (error) { - log.error({ err: error }, 'Scheduler tick failed'); - } - - if (claimed < batchSize) { - await sleep(pollIntervalMs, undefined, { signal: abort.signal }).catch( - () => false, - ); - } - } - } - - return { - tick, - start: () => { - loop ??= run(); - }, - stop: async () => { - abort.abort(); - await loop; - }, - }; -} diff --git a/tests/core/services/announcements.test.ts b/tests/core/services/announcements.test.ts index 3e2079b..1f2911e 100644 --- a/tests/core/services/announcements.test.ts +++ b/tests/core/services/announcements.test.ts @@ -138,10 +138,7 @@ describe.skipIf(noDatabase)('announcement service', () => { status: 'scheduled', scheduledAt: new Date(Date.now() - 2 * 3_600_000), }); - await service.jobs[0]?.run( - { announcementId: draft.id }, - { id: 1, runAt: new Date(), attempt: 1 }, - ); + await service.jobs[0]?.run({ announcementId: draft.id }); expect(messenger.send).not.toHaveBeenCalled(); expect((await repository.find(draft.id))?.status).toBe('failed'); }); @@ -153,14 +150,13 @@ describe.skipIf(noDatabase)('announcement service', () => { content: 'Hi', }); const job = service.jobs[0]; - const info = { id: 1, runAt: new Date(), attempt: 1 }; await repository.transition(draft.id, ['draft'], { status: 'scheduled', scheduledAt: new Date(), }); - await job?.run({ announcementId: draft.id }, info); - await job?.run({ announcementId: draft.id }, info); + await job?.run({ announcementId: draft.id }); + await job?.run({ announcementId: draft.id }); expect(messenger.send).toHaveBeenCalledOnce(); expect((await repository.find(draft.id))?.status).toBe('published'); }); diff --git a/tests/core/services/birthdays.test.ts b/tests/core/services/birthdays.test.ts index 49d4270..1d23f83 100644 --- a/tests/core/services/birthdays.test.ts +++ b/tests/core/services/birthdays.test.ts @@ -160,10 +160,9 @@ describe.skipIf(noDatabase)('birthdays', () => { await service.configure(admin, { channelId: 'c' }); const [daily] = service.jobs; - const info = { id: 1, runAt: new Date(), attempt: 1 }; - const outcome = await daily?.run({ guildId: admin.guildId }, info); + const outcome = await daily?.run({ guildId: admin.guildId }); - await daily?.run({ guildId: admin.guildId }, info); + await daily?.run({ guildId: admin.guildId }); expect(messenger.send).toHaveBeenCalledOnce(); expect(messenger.send).toHaveBeenCalledWith( 'c', diff --git a/tests/core/services/events.test.ts b/tests/core/services/events.test.ts index c959fe7..16f12a2 100644 --- a/tests/core/services/events.test.ts +++ b/tests/core/services/events.test.ts @@ -180,10 +180,7 @@ describe.skipIf(noDatabase)('event service', () => { await service.cancel(organizer, event.id); messenger.send.mockClear(); - await service.jobs[0]?.run( - { eventId: event.id, minutes: 60 }, - { id: 1, runAt: new Date(), attempt: 1 }, - ); + await service.jobs[0]?.run({ eventId: event.id, minutes: 60 }); expect(messenger.send).not.toHaveBeenCalled(); }); diff --git a/tests/core/services/polls.test.ts b/tests/core/services/polls.test.ts index 922df15..1464ffa 100644 --- a/tests/core/services/polls.test.ts +++ b/tests/core/services/polls.test.ts @@ -146,10 +146,7 @@ describe.skipIf(noDatabase)('poll service', () => { poll.id, [poll.options[1]?.id ?? 0], ); - await service.jobs[0]?.run( - { pollId: poll.id }, - { id: 1, runAt: new Date(), attempt: 1 }, - ); + await service.jobs[0]?.run({ pollId: poll.id }); const closed = await repository.find(poll.id); diff --git a/tests/core/services/redmine.test.ts b/tests/core/services/redmine.test.ts index 61a79a5..5189a54 100644 --- a/tests/core/services/redmine.test.ts +++ b/tests/core/services/redmine.test.ts @@ -108,10 +108,9 @@ describe.skipIf(noDatabase)('redmine service', () => { await repository.setCheckpoint(subscription?.id ?? 0, since); const [poll] = service.jobs; - const info = { id: 1, runAt: new Date(), attempt: 1 }; - const outcome = await poll?.run({}, info); + const outcome = await poll?.run({}); - await poll?.run({}, info); + await poll?.run({}); const ours = messenger.send.mock.calls.filter(([id]) => id === channelId); @@ -134,8 +133,6 @@ describe.skipIf(noDatabase)('redmine service', () => { }), ); - await expect( - service.jobs[0]?.run({}, { id: 1, runAt: new Date(), attempt: 1 }), - ).resolves.toBeDefined(); + await expect(service.jobs[0]?.run({})).resolves.toBeDefined(); }); }); diff --git a/tests/core/services/reminders.test.ts b/tests/core/services/reminders.test.ts index 4ee0ee5..7718dd3 100644 --- a/tests/core/services/reminders.test.ts +++ b/tests/core/services/reminders.test.ts @@ -12,8 +12,6 @@ import { fakeMessenger, } from '../../fakes'; -const info = { id: 1, runAt: new Date(), attempt: 1 }; - describe.skipIf(noDatabase)('reminder service', () => { const setup = (authz = allowAll) => { const { messenger } = fakeMessenger(); @@ -66,7 +64,7 @@ describe.skipIf(noDatabase)('reminder service', () => { message: 'stand-up', }); - expect(await deliver?.run({ reminderId: reminder.id }, info)).toBeNull(); + expect(await deliver?.run({ reminderId: reminder.id })).toBeNull(); expect(messenger.direct).toHaveBeenCalledWith(member.userId, { content: '⏰ **Reminder:** stand-up', }); @@ -84,7 +82,7 @@ describe.skipIf(noDatabase)('reminder service', () => { recurrence: 'daily', timezone: 'Europe/Tallinn', }); - const outcome = await deliver?.run({ reminderId: reminder.id }, info); + const outcome = await deliver?.run({ reminderId: reminder.id }); expect(outcome?.rescheduleAt.getTime()).toBeGreaterThan(Date.now()); expect(outcome?.rescheduleAt.getTime()).toBeLessThanOrEqual( @@ -106,7 +104,7 @@ describe.skipIf(noDatabase)('reminder service', () => { }); await expect( - deliver?.run({ reminderId: reminder.id }, info), + deliver?.run({ reminderId: reminder.id }), ).rejects.toBeInstanceOf(PermanentError); expect((await repository.find(reminder.id))?.status).toBe('failed'); }); @@ -122,7 +120,7 @@ describe.skipIf(noDatabase)('reminder service', () => { service.cancel(actor({ guildId: member.guildId }), reminder.id), ).rejects.toBeInstanceOf(UserError); await service.cancel(member, reminder.id); - await deliver?.run({ reminderId: reminder.id }, info); + await deliver?.run({ reminderId: reminder.id }); expect(messenger.direct).not.toHaveBeenCalled(); }); diff --git a/tests/global-setup.ts b/tests/global-setup.ts index 7b9f283..55b12b6 100644 --- a/tests/global-setup.ts +++ b/tests/global-setup.ts @@ -14,6 +14,7 @@ export default async function setup(): Promise { await sql`DROP SCHEMA IF EXISTS public CASCADE`; await sql`DROP SCHEMA IF EXISTS drizzle CASCADE`; + await sql`DROP SCHEMA IF EXISTS pgboss CASCADE`; await sql`CREATE SCHEMA public`; await sql.end(); const database = connectDatabase(url); diff --git a/tests/infra/scheduler/boss.test.ts b/tests/infra/scheduler/boss.test.ts new file mode 100644 index 0000000..cba0b7c --- /dev/null +++ b/tests/infra/scheduler/boss.test.ts @@ -0,0 +1,79 @@ +import { PgBoss } from 'pg-boss'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import type { Job } from '~/core/ports'; +import { PermanentError } from '~/domain'; +import { createJobQueue, startJobs } from '~/infra/scheduler'; +import { silentLog } from '../../fakes'; +import { noDatabase } from '../../db'; + +describe.skipIf(noDatabase)('pg-boss scheduler', () => { + const boss = new PgBoss(process.env.TEST_DATABASE_URL ?? ''); + const scheduler = createJobQueue(boss); + const later = new Date(Date.now() + 60 * 60 * 1000); + const idle: Job<{ n: number }> = { type: 'test-idle', run: async () => null }; + const recurring: Job<{ n: number }> = { + type: 'test-recurring', + run: vi.fn(async () => ({ rescheduleAt: later })), + }; + const broken: Job<{ n: number }> = { + type: 'test-broken', + run: vi.fn(async () => { + throw new PermanentError('bad'); + }), + }; + const queued = async (job: Job<{ n: number }>, key: string) => + boss.findJobs<{ n: number }>(job.type, { key, queued: true }); + + beforeAll(async () => { + await boss.start(); + await startJobs(boss, [idle, recurring, broken], silentLog); + }); + + afterAll(async () => { + await boss.stop(); + }); + + it('keeps one queued job per key and cancels it', async () => { + await scheduler.schedule(idle, { n: 1 }, { runAt: later, key: 'a' }); + await scheduler.schedule(idle, { n: 2 }, { runAt: later, key: 'a' }); + + const jobs = await queued(idle, 'a'); + + expect(jobs.map((job) => job.data.n)).toEqual([2]); + + await scheduler.cancel(idle, 'a'); + expect(await queued(idle, 'a')).toHaveLength(0); + }); + + it('queues the next run of a job that reschedules itself', async () => { + await scheduler.schedule( + recurring, + { n: 1 }, + { runAt: new Date(), key: 'r' }, + ); + + await vi.waitFor( + async () => { + const [next] = await queued(recurring, 'r'); + + expect(next?.startAfter.getTime()).toBe(later.getTime()); + }, + { timeout: 10_000, interval: 250 }, + ); + expect(recurring.run).toHaveBeenCalledOnce(); + }); + + it('does not retry permanent failures', async () => { + await scheduler.schedule(broken, { n: 1 }, { runAt: new Date(), key: 'b' }); + + await vi.waitFor( + async () => { + const [job] = await boss.findJobs(broken.type, { key: 'b' }); + + expect(job?.state).toBe('failed'); + }, + { timeout: 10_000, interval: 250 }, + ); + expect(broken.run).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/infra/scheduler/runner.test.ts b/tests/infra/scheduler/runner.test.ts deleted file mode 100644 index 9da1866..0000000 --- a/tests/infra/scheduler/runner.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { eq, sql } from 'drizzle-orm'; -import { pino } from 'pino'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { z } from 'zod'; -import { noDatabase, testDb } from '../../db'; -import { PermanentError } from '~/domain'; -import { defineJob } from '~/core/services'; -import { - createJobQueue, - createJobRunner, - retryDelayMs, -} from '~/infra/scheduler'; -import { scheduledJobs, claimDueJobs } from '~/infra/db'; - -const log = pino({ level: 'silent' }); - -describe.skipIf(noDatabase)('scheduler', () => { - const db = noDatabase ? undefined : testDb(); - const handle = - vi.fn<(payload: { n: number }) => Promise>(); - const job = defineJob({ - type: 'test:job', - payload: z.object({ n: z.number() }), - maxAttempts: 3, - handle: (payload) => handle(payload), - }); - - const setup = () => { - if (!db) { - throw new Error('unreachable'); - } - - const scheduler = { - ...createJobQueue(db), - ...createJobRunner(db, new Map([[job.type, job]]), log), - }; - - return { db, scheduler }; - }; - - const past = () => new Date(Date.now() - 1000); - const row = async (key: string) => { - const { db: database } = setup(); - const [found] = await database - .select() - .from(scheduledJobs) - .where(eq(scheduledJobs.key, key)); - - return found; - }; - - beforeEach(async () => { - handle.mockReset(); - await setup().db.delete(scheduledJobs); - }); - - it('runs due jobs once and marks them done', async () => { - const { scheduler } = setup(); - - handle.mockResolvedValue(null); - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'a' }); - await scheduler.schedule( - job, - { n: 2 }, - { runAt: new Date(Date.now() + 60_000), key: 'b' }, - ); - - expect(await scheduler.tick()).toBe(1); - expect(await scheduler.tick()).toBe(0); - expect(handle).toHaveBeenCalledExactlyOnceWith({ n: 1 }); - expect((await row('a'))?.status).toBe('done'); - expect((await row('b'))?.status).toBe('pending'); - }); - - it('replaces a pending job scheduled with the same key', async () => { - const { scheduler } = setup(); - - handle.mockResolvedValue(null); - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'same' }); - await scheduler.schedule(job, { n: 2 }, { runAt: past(), key: 'same' }); - await scheduler.tick(); - expect(handle).toHaveBeenCalledExactlyOnceWith({ n: 2 }); - }); - - it('does not run cancelled jobs', async () => { - const { scheduler } = setup(); - - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'c' }); - await scheduler.cancel('c'); - expect(await scheduler.tick()).toBe(0); - expect((await row('c'))?.status).toBe('cancelled'); - }); - - it('retries transient failures with backoff, then fails', async () => { - const { db: database, scheduler } = setup(); - - handle.mockRejectedValue(new Error('discord down')); - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'r' }); - - for (let attempt = 1; attempt <= 3; attempt++) { - await scheduler.tick(); - const current = await row('r'); - - expect(current?.attempts).toBe(attempt); - if (attempt < 3) { - expect(current?.status).toBe('pending'); - expect(current?.runAt.getTime()).toBeGreaterThan(Date.now()); - await database - .update(scheduledJobs) - .set({ runAt: past() }) - .where(eq(scheduledJobs.key, 'r')); - } - } - - expect((await row('r'))?.status).toBe('failed'); - expect((await row('r'))?.lastError).toBe('discord down'); - expect(retryDelayMs(1)).toBe(30_000); - expect(retryDelayMs(20)).toBe(3_600_000); - }); - - it('does not retry permanent failures or invalid payloads', async () => { - const { db: database, scheduler } = setup(); - - handle.mockRejectedValue(new PermanentError('user blocked DMs')); - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'p' }); - await database.insert(scheduledJobs).values({ - type: job.type, - payload: { n: 'x' }, - runAt: past(), - key: 'bad', - }); - await scheduler.tick(); - expect((await row('p'))?.status).toBe('failed'); - expect((await row('bad'))?.status).toBe('failed'); - expect(handle).toHaveBeenCalledOnce(); - }); - - it('reschedules recurring jobs', async () => { - const { scheduler } = setup(); - const next = new Date(Date.now() + 86_400_000); - - handle.mockResolvedValue({ rescheduleAt: next }); - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'rec' }); - await scheduler.tick(); - const current = await row('rec'); - - expect(current?.status).toBe('pending'); - expect(current?.runAt.getTime()).toBe(next.getTime()); - expect(current?.attempts).toBe(0); - }); - - it('recovers jobs whose lease expired after a crash', async () => { - const { db: database, scheduler } = setup(); - - handle.mockResolvedValue(null); - await scheduler.schedule(job, { n: 1 }, { runAt: past(), key: 'crash' }); - await claimDueJobs(database, { - types: [job.type], - limit: 10, - leaseMs: 60_000, - }); - expect(await scheduler.tick()).toBe(0); - await database - .update(scheduledJobs) - .set({ lockedUntil: sql`now() - interval '1 second'` }) - .where(eq(scheduledJobs.key, 'crash')); - expect(await scheduler.tick()).toBe(1); - expect((await row('crash'))?.status).toBe('done'); - }); - - it('never hands the same job to concurrent claimers', async () => { - const { db: database, scheduler } = setup(); - - for (let n = 0; n < 20; n++) { - await scheduler.schedule(job, { n }, { runAt: past(), key: `k${n}` }); - } - - const claims = await Promise.all( - Array.from({ length: 5 }, () => - claimDueJobs(database, { - types: [job.type], - limit: 8, - leaseMs: 60_000, - }), - ), - ); - const ids = claims.flat().map((claimed) => claimed.id); - - expect(new Set(ids).size).toBe(ids.length); - expect(ids).toHaveLength(20); - }); - - it('leaves jobs of unregistered types untouched', async () => { - const { db: database, scheduler } = setup(); - - await database.insert(scheduledJobs).values({ - type: 'disabled:feature', - payload: {}, - runAt: past(), - key: 'off', - }); - expect(await scheduler.tick()).toBe(0); - expect((await row('off'))?.status).toBe('pending'); - }); -}); From 3448754f408cae10d8323e3e470c60b0d83bf7dd Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:11:14 +0200 Subject: [PATCH 048/199] refactor(db): drop the scheduled_jobs table now that pg-boss owns jobs --- README.md | 9 +- drizzle/0004_drop_scheduled_jobs.sql | 2 + drizzle/meta/0004_snapshot.json | 1531 ++++++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/infra/db/index.ts | 2 - src/infra/db/jobs/model.ts | 49 - src/infra/db/jobs/repo.ts | 119 -- 7 files changed, 1545 insertions(+), 174 deletions(-) create mode 100644 drizzle/0004_drop_scheduled_jobs.sql create mode 100644 drizzle/meta/0004_snapshot.json delete mode 100644 src/infra/db/jobs/model.ts delete mode 100644 src/infra/db/jobs/repo.ts diff --git a/README.md b/README.md index d931fb6..3da43db 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ src/ db// drizzle model and repository adapters discord/ discord.js client, router, outbound adapters and the thin slash-command adapters in commands/ - scheduler/ job queue (Scheduler port) and the job runner + scheduler/ pg-boss adapter for the Scheduler port redmine/ Redmine adapter for the IssueTracker port logging/ pino web/ server-rendered web UI and its Authenticator adapter @@ -208,9 +208,10 @@ drizzle/ SQL migrations mentions and controls. `infra/discord/render.ts` turns them into discord.js payloads. - **Cross-service use is explicit**: movies get the poll and event services. -- **Scheduler:** jobs live in `scheduled_jobs`. The runner claims due jobs - with `FOR UPDATE SKIP LOCKED` and a lease, so a crash mid-job leads to a - retry after the lease expires. Delivery is at-least-once, and handlers +- **Scheduler:** jobs run on [pg-boss](https://github.com/timgit/pg-boss) in + the `pgboss` schema, one queue per job type with one queued job per key. + A failed job is retried up to 4 times with backoff, and a crash mid-job + leads to a retry once the job expires. Delivery is at-least-once, and handlers re-check current state. Where a duplicate message would be worse than a missed one (announcements, birthdays, Redmine notifications), the handler records the send before posting. Each handler decides what lateness means: diff --git a/drizzle/0004_drop_scheduled_jobs.sql b/drizzle/0004_drop_scheduled_jobs.sql new file mode 100644 index 0000000..884c370 --- /dev/null +++ b/drizzle/0004_drop_scheduled_jobs.sql @@ -0,0 +1,2 @@ +DROP TABLE "scheduled_jobs" CASCADE;--> statement-breakpoint +DROP TYPE "public"."job_status"; \ No newline at end of file diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..b426793 --- /dev/null +++ b/drizzle/meta/0004_snapshot.json @@ -0,0 +1,1531 @@ +{ + "id": "2a764cb7-5481-41c5-99ba-158a5685eebf", + "prevId": "bfc4bd90-b9f9-45da-b76c-d469c18c353b", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embed": { + "name": "embed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "publishing", + "published", + "cancelled", + "failed" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 3d6dea7..4ce8ac0 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1794822022773, "tag": "0003_drop_redmine_links", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1794823786228, + "tag": "0004_drop_scheduled_jobs", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/infra/db/index.ts b/src/infra/db/index.ts index 26727b6..5666b4e 100644 --- a/src/infra/db/index.ts +++ b/src/infra/db/index.ts @@ -1,6 +1,4 @@ export * from './client'; -export * from './jobs/model'; -export * from './jobs/repo'; export * from './permissions/model'; export * from './permissions/repo'; export * from './roles/model'; diff --git a/src/infra/db/jobs/model.ts b/src/infra/db/jobs/model.ts deleted file mode 100644 index 5a446e3..0000000 --- a/src/infra/db/jobs/model.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { sql } from 'drizzle-orm'; -import { - bigserial, - index, - integer, - jsonb, - pgEnum, - pgTable, - text, - timestamp, -} from 'drizzle-orm/pg-core'; - -export const jobStatus = pgEnum('job_status', [ - 'pending', - 'running', - 'done', - 'failed', - 'cancelled', -]); - -export const scheduledJobs = pgTable( - 'scheduled_jobs', - { - id: bigserial('id', { mode: 'number' }).primaryKey(), - type: text('type').notNull(), - payload: jsonb('payload').$type().notNull(), - runAt: timestamp('run_at', { withTimezone: true }).notNull(), - status: jobStatus('status').notNull().default('pending'), - attempts: integer('attempts').notNull().default(0), - maxAttempts: integer('max_attempts').notNull().default(5), - lockedUntil: timestamp('locked_until', { withTimezone: true }), - lastError: text('last_error'), - key: text('key').unique(), - createdAt: timestamp('created_at', { withTimezone: true }) - .notNull() - .defaultNow(), - finishedAt: timestamp('finished_at', { withTimezone: true }), - }, - (table) => [ - index('scheduled_jobs_due_idx') - .on(table.runAt) - .where(sql`${table.status} = 'pending'`), - index('scheduled_jobs_lease_idx') - .on(table.lockedUntil) - .where(sql`${table.status} = 'running'`), - ], -); - -export type JobRow = typeof scheduledJobs.$inferSelect; diff --git a/src/infra/db/jobs/repo.ts b/src/infra/db/jobs/repo.ts deleted file mode 100644 index 91364c2..0000000 --- a/src/infra/db/jobs/repo.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { and, asc, eq, inArray, lte, lt, or, sql } from 'drizzle-orm'; -import type { Db } from '../client'; -import { scheduledJobs, type JobRow } from './model'; - -export type NewJob = { - type: string; - payload: unknown; - runAt: Date; - key?: string | undefined; - maxAttempts?: number | undefined; -}; - -export async function upsertJob(db: Db, job: NewJob): Promise { - const values = { - type: job.type, - payload: job.payload, - runAt: job.runAt, - key: job.key ?? null, - maxAttempts: job.maxAttempts ?? 5, - }; - - await db - .insert(scheduledJobs) - .values(values) - .onConflictDoUpdate({ - target: scheduledJobs.key, - set: { - ...values, - status: 'pending', - attempts: 0, - lockedUntil: null, - lastError: null, - finishedAt: null, - }, - }); -} - -export async function cancelJob(db: Db, key: string): Promise { - await db - .update(scheduledJobs) - .set({ status: 'cancelled', finishedAt: new Date(), lockedUntil: null }) - .where( - and( - eq(scheduledJobs.key, key), - inArray(scheduledJobs.status, ['pending', 'running']), - ), - ); -} - -export async function claimDueJobs( - db: Db, - options: { types: readonly string[]; limit: number; leaseMs: number }, -): Promise { - if (options.types.length === 0) { - return []; - } - - const due = db - .select({ id: scheduledJobs.id }) - .from(scheduledJobs) - .where( - and( - inArray(scheduledJobs.type, [...options.types]), - or( - and( - eq(scheduledJobs.status, 'pending'), - lte(scheduledJobs.runAt, sql`now()`), - ), - and( - eq(scheduledJobs.status, 'running'), - lt(scheduledJobs.lockedUntil, sql`now()`), - ), - ), - ), - ) - .orderBy(asc(scheduledJobs.runAt)) - .limit(options.limit) - .for('update', { skipLocked: true }); - - return db - .update(scheduledJobs) - .set({ - status: 'running', - attempts: sql`${scheduledJobs.attempts} + 1`, - lockedUntil: sql`now() + ${options.leaseMs} * interval '1 millisecond'`, - }) - .where(inArray(scheduledJobs.id, due)) - .returning(); -} - -type Finish = - | { kind: 'done' } - | { kind: 'reschedule'; runAt: Date } - | { kind: 'retry'; runAt: Date; error: string } - | { kind: 'failed'; error: string }; - -export async function finishJob( - db: Db, - id: number, - finish: Finish, -): Promise { - const now = new Date(); - const changes = { - done: { status: 'done', finishedAt: now }, - reschedule: { status: 'pending', attempts: 0, lastError: null }, - retry: { status: 'pending' }, - failed: { status: 'failed', finishedAt: now }, - } as const; - - await db - .update(scheduledJobs) - .set({ - ...changes[finish.kind], - lockedUntil: null, - ...('runAt' in finish && { runAt: finish.runAt }), - ...('error' in finish && { lastError: finish.error.slice(0, 2000) }), - }) - .where(and(eq(scheduledJobs.id, id), eq(scheduledJobs.status, 'running'))); -} From 7449cd6fa53332085f912a9c83be12985582795a Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:26:14 +0200 Subject: [PATCH 049/199] feat(announcements): post as plain text with the title as a heading --- drizzle/0005_drop_announcement_embed.sql | 1 + drizzle/meta/0005_snapshot.json | 1524 +++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/core/ports/announcements.ts | 9 +- src/core/services/announcements.ts | 23 +- src/infra/db/announcements/model.ts | 1 - src/infra/discord/commands/announcements.ts | 9 +- src/infra/web/app.ts | 7 +- src/infra/web/layout.ts | 2 +- src/infra/web/preview.ts | 18 +- tests/core/services/announcements.test.ts | 8 +- tests/infra/web/app.test.ts | 4 +- 12 files changed, 1548 insertions(+), 65 deletions(-) create mode 100644 drizzle/0005_drop_announcement_embed.sql create mode 100644 drizzle/meta/0005_snapshot.json diff --git a/drizzle/0005_drop_announcement_embed.sql b/drizzle/0005_drop_announcement_embed.sql new file mode 100644 index 0000000..d1504ec --- /dev/null +++ b/drizzle/0005_drop_announcement_embed.sql @@ -0,0 +1 @@ +ALTER TABLE "announcements" DROP COLUMN "embed"; \ No newline at end of file diff --git a/drizzle/meta/0005_snapshot.json b/drizzle/meta/0005_snapshot.json new file mode 100644 index 0000000..f62c2fa --- /dev/null +++ b/drizzle/meta/0005_snapshot.json @@ -0,0 +1,1524 @@ +{ + "id": "e5243c7c-36fa-42d0-bbbe-a2ee9ba2f42c", + "prevId": "2a764cb7-5481-41c5-99ba-158a5685eebf", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "publishing", + "published", + "cancelled", + "failed" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 4ce8ac0..16cdbcd 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1794823786228, "tag": "0004_drop_scheduled_jobs", "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1794824606678, + "tag": "0005_drop_announcement_embed", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/core/ports/announcements.ts b/src/core/ports/announcements.ts index f96506f..ff15616 100644 --- a/src/core/ports/announcements.ts +++ b/src/core/ports/announcements.ts @@ -8,7 +8,6 @@ export type Announcement = { channelId: string; title: string | null; content: string; - embed: boolean; mentionRoleIds: string[]; mentionEveryone: boolean; status: AnnouncementStatus; @@ -26,7 +25,6 @@ export type NewAnnouncement = Pick< | 'channelId' | 'title' | 'content' - | 'embed' | 'mentionRoleIds' | 'mentionEveryone' >; @@ -49,12 +47,7 @@ export type AnnouncementRepository = { changes: Partial< Pick< Announcement, - | 'title' - | 'content' - | 'channelId' - | 'embed' - | 'mentionRoleIds' - | 'mentionEveryone' + 'title' | 'content' | 'channelId' | 'mentionRoleIds' | 'mentionEveryone' > >, ) => Promise; diff --git a/src/core/services/announcements.ts b/src/core/services/announcements.ts index 137a279..a9eb42b 100644 --- a/src/core/services/announcements.ts +++ b/src/core/services/announcements.ts @@ -26,16 +26,14 @@ import { defineJob } from './jobs'; const jobKey = (id: number) => `announcement:${id}`; const maxLatenessMs = 60 * 60 * 1000; -const accent = 0xff_ac_1c; const reopenable: AnnouncementStatus[] = ['draft', 'scheduled', 'failed']; -export const maxAnnouncementLength = 4000; +export const maxAnnouncementLength = 1900; export type AnnouncementDraft = { channelId: string; title?: string; content: string; - embed?: boolean; mentionRoleIds?: readonly string[]; mentionEveryone?: boolean; }; @@ -50,29 +48,15 @@ export function announcementView(announcement: Announcement): Message { roles: announcement.mentionRoleIds, }; - if (announcement.embed) { - return { - ...(pings !== '' && { content: pings }), - embeds: [ - { - ...(announcement.title !== null && { title: announcement.title }), - description: announcement.content, - color: accent, - }, - ], - mentions, - }; - } - const heading = - announcement.title === null ? '' : `**${announcement.title}**\n`; + announcement.title === null ? '' : `# ${announcement.title}\n`; const content = [pings, `${heading}${announcement.content}`] .filter(Boolean) .join('\n'); if (content.length > maxContentLength) { throw new UserError( - 'Plain announcements are limited to 2000 characters; use an embed.', + 'Announcements are limited to 2000 characters, including the title and mentions.', ); } @@ -244,7 +228,6 @@ export function createAnnouncementService(deps: Deps) { channelId: draft.channelId, title: title === '' ? null : title, content: draft.content, - embed: draft.embed ?? true, mentionRoleIds: [...(draft.mentionRoleIds ?? [])], mentionEveryone: draft.mentionEveryone ?? false, }); diff --git a/src/infra/db/announcements/model.ts b/src/infra/db/announcements/model.ts index 2137fac..d2a1231 100644 --- a/src/infra/db/announcements/model.ts +++ b/src/infra/db/announcements/model.ts @@ -26,7 +26,6 @@ export const announcements = pgTable( channelId: text('channel_id').notNull(), title: text('title'), content: text('content').notNull(), - embed: boolean('embed').notNull().default(true), mentionRoleIds: text('mention_role_ids').array().notNull().default([]), mentionEveryone: boolean('mention_everyone').notNull().default(false), status: announcementStatus('status').notNull().default('draft'), diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts index 376f120..3010dec 100644 --- a/src/infra/discord/commands/announcements.ts +++ b/src/infra/discord/commands/announcements.ts @@ -79,9 +79,6 @@ const data = new SlashCommandBuilder() ChannelType.GuildText, ChannelType.GuildAnnouncement, ), - ) - .addBooleanOption((o) => - o.setName('embed').setDescription('Post as an embed (default no)'), ), ) .addSubcommand((sub) => @@ -140,7 +137,7 @@ export function announcementCommands( return; } - const [channelId = '', embed] = args; + const [channelId = ''] = args; const roles = interaction.fields.getSelectedRoles('mentions'); const announcement = await announcements.draft( toActor(interaction.member), @@ -148,7 +145,6 @@ export function announcementCommands( channelId, title: interaction.fields.getTextInputValue('title'), content: interaction.fields.getTextInputValue('content'), - embed: embed === '1', mentionRoleIds: roles ? [...roles.keys()] : [], mentionEveryone: interaction.fields .getStringSelectValues('everyone') @@ -204,11 +200,10 @@ export function announcementCommands( execute: bySubcommand({ create: async (interaction) => { const channel = interaction.options.getChannel('channel', true); - const embed = interaction.options.getBoolean('embed') ?? false; await interaction.showModal( contentModal( - controlId('announcements:create', channel.id, embed ? 1 : 0), + controlId('announcements:create', channel.id), 'New announcement', ).addLabelComponents( new LabelBuilder() diff --git a/src/infra/web/app.ts b/src/infra/web/app.ts index 2024163..5cf4f40 100644 --- a/src/infra/web/app.ts +++ b/src/infra/web/app.ts @@ -136,7 +136,6 @@ function psaDraft(context: Context) { channelId: field(context.form, 'channelId') ?? '', title: field(context.form, 'title') ?? '', content: context.form.get('content') ?? '', - embed: context.form.get('embed') === '1', mentionRoleIds: context.form.getAll('role'), mentionEveryone: context.form.get('everyone') === '1', }; @@ -152,13 +151,9 @@ function psaForm(context: Context, preview?: Html) { /> - ${mentionPicker(context, draft.mentionRoleIds)}

${message.content === undefined || message.content === '' ? '' : html`

${lines(message.content, names)}

`} - ${(message.embeds ?? []).map( - (embed) => - html`
- ${embed.title === undefined ? '' : html`${embed.title}`} - ${embed.description === undefined ? '' : html`

${lines(embed.description, names)}

`} - ${(embed.fields ?? []).map((field) => html`

${field.name}
${lines(field.value, names)}

`)} - ${embed.footer === undefined ? '' : html`${embed.footer}`} -
`, - )}
`; } diff --git a/tests/core/services/announcements.test.ts b/tests/core/services/announcements.test.ts index 1f2911e..03e9309 100644 --- a/tests/core/services/announcements.test.ts +++ b/tests/core/services/announcements.test.ts @@ -19,7 +19,6 @@ const sample = (overrides: Partial = {}): Announcement => ({ channelId: 'c', title: 'Hello', content: 'World', - embed: false, mentionRoleIds: [], mentionEveryone: false, status: 'draft', @@ -39,7 +38,7 @@ describe('announcement view', () => { expect( announcementView(sample({ mentionRoleIds: ['r1', 'r2'] })), ).toMatchObject({ - content: '<@&r1> <@&r2>\n**Hello**\nWorld', + content: '<@&r1> <@&r2>\n# Hello\nWorld', mentions: { roles: ['r1', 'r2'] }, }); expect( @@ -47,13 +46,10 @@ describe('announcement view', () => { ).toBe(true); }); - it('rejects plain messages over the Discord limit', () => { + it('rejects messages over the Discord limit', () => { expect(() => announcementView(sample({ content: 'x'.repeat(2001) })), ).toThrow('2000'); - expect(() => - announcementView(sample({ content: 'x'.repeat(2001), embed: true })), - ).not.toThrow(); }); }); diff --git a/tests/infra/web/app.test.ts b/tests/infra/web/app.test.ts index e577bb1..3cc57fe 100644 --- a/tests/infra/web/app.test.ts +++ b/tests/infra/web/app.test.ts @@ -160,7 +160,6 @@ describe.skipIf(noDatabase)('web UI', () => { title: 'Hi', content: `Meeting <@&${teamId}> **now**`, role: teamId, - embed: '1', action: 'preview', }); const page = await response.text(); @@ -177,7 +176,6 @@ describe.skipIf(noDatabase)('web UI', () => { title: 'Hackathon', content: 'Sign up today', role: teamId, - embed: '1', action: 'publish', }); @@ -186,7 +184,7 @@ describe.skipIf(noDatabase)('web UI', () => { expect(messenger.send).toHaveBeenCalledWith( 'general', expect.objectContaining({ - content: `<@&${teamId}>`, + content: `<@&${teamId}>\n# Hackathon\nSign up today`, mentions: { everyone: false, roles: [teamId] }, }), ); From 8d88c6b65dfeed3d296d214c2bd6af8be109c9a0 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:32:14 +0200 Subject: [PATCH 050/199] refactor(announcements): four statuses and one update with an optional status guard --- drizzle/0006_simplify_announcement_status.sql | 7 + drizzle/meta/0006_snapshot.json | 1522 +++++++++++++++++ drizzle/meta/_journal.json | 7 + src/core/ports/announcements.ts | 19 +- src/core/services/announcements.ts | 93 +- src/infra/db/announcements/model.ts | 2 - src/infra/db/announcements/repo.ts | 21 +- src/infra/discord/commands/announcements.ts | 4 +- src/infra/web/app.ts | 11 +- tests/core/services/announcements.test.ts | 35 +- 10 files changed, 1641 insertions(+), 80 deletions(-) create mode 100644 drizzle/0006_simplify_announcement_status.sql create mode 100644 drizzle/meta/0006_snapshot.json diff --git a/drizzle/0006_simplify_announcement_status.sql b/drizzle/0006_simplify_announcement_status.sql new file mode 100644 index 0000000..4049fc0 --- /dev/null +++ b/drizzle/0006_simplify_announcement_status.sql @@ -0,0 +1,7 @@ +ALTER TABLE "announcements" ALTER COLUMN "status" SET DATA TYPE text;--> statement-breakpoint +UPDATE "announcements" SET "status" = 'draft' WHERE "status" IN ('publishing', 'failed');--> statement-breakpoint +ALTER TABLE "announcements" ALTER COLUMN "status" SET DEFAULT 'draft'::text;--> statement-breakpoint +DROP TYPE "public"."announcement_status";--> statement-breakpoint +CREATE TYPE "public"."announcement_status" AS ENUM('draft', 'scheduled', 'published', 'cancelled');--> statement-breakpoint +ALTER TABLE "announcements" ALTER COLUMN "status" SET DEFAULT 'draft'::"public"."announcement_status";--> statement-breakpoint +ALTER TABLE "announcements" ALTER COLUMN "status" SET DATA TYPE "public"."announcement_status" USING "status"::"public"."announcement_status"; \ No newline at end of file diff --git a/drizzle/meta/0006_snapshot.json b/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..308f811 --- /dev/null +++ b/drizzle/meta/0006_snapshot.json @@ -0,0 +1,1522 @@ +{ + "id": "e35670ef-b1eb-4e4b-aa0d-686e6a9ca60d", + "prevId": "e5243c7c-36fa-42d0-bbbe-a2ee9ba2f42c", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "published", + "cancelled" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 16cdbcd..2259366 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1794824606678, "tag": "0005_drop_announcement_embed", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1794824856256, + "tag": "0006_simplify_announcement_status", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/core/ports/announcements.ts b/src/core/ports/announcements.ts index ff15616..bf0cc6a 100644 --- a/src/core/ports/announcements.ts +++ b/src/core/ports/announcements.ts @@ -1,5 +1,5 @@ export type AnnouncementStatus = - 'draft' | 'scheduled' | 'publishing' | 'published' | 'cancelled' | 'failed'; + 'draft' | 'scheduled' | 'published' | 'cancelled'; export type Announcement = { id: number; @@ -30,25 +30,16 @@ export type NewAnnouncement = Pick< >; export type AnnouncementChanges = Partial< - Omit -> & { status: AnnouncementStatus }; + Omit +>; export type AnnouncementRepository = { insert: (announcement: NewAnnouncement) => Promise; find: (id: number) => Promise; list: (guildId: string, limit?: number) => Promise; - transition: ( + update: ( id: number, - from: readonly AnnouncementStatus[], changes: AnnouncementChanges, + onlyIf?: readonly AnnouncementStatus[], ) => Promise; - update: ( - id: number, - changes: Partial< - Pick< - Announcement, - 'title' | 'content' | 'channelId' | 'mentionRoleIds' | 'mentionEveryone' - > - >, - ) => Promise; }; diff --git a/src/core/services/announcements.ts b/src/core/services/announcements.ts index a9eb42b..279ff7b 100644 --- a/src/core/services/announcements.ts +++ b/src/core/services/announcements.ts @@ -20,13 +20,14 @@ import type { Logger, Messenger, Scheduler, + Sent, } from '~/core/ports'; import { guard } from './guard'; import { defineJob } from './jobs'; const jobKey = (id: number) => `announcement:${id}`; const maxLatenessMs = 60 * 60 * 1000; -const reopenable: AnnouncementStatus[] = ['draft', 'scheduled', 'failed']; +const open: AnnouncementStatus[] = ['draft', 'scheduled']; export const maxAnnouncementLength = 1900; @@ -131,46 +132,45 @@ export function createAnnouncementService(deps: Deps) { }; const publish = async (id: number, from: readonly AnnouncementStatus[]) => { - const claimed = await announcements.transition(id, from, { - status: 'publishing', - }); + const claimed = await announcements.update( + id, + { + status: 'published', + publishedAt: clock.now(), + failure: null, + }, + from, + ); if (!claimed) { throw new UserError( - `Announcement #${id} cannot be published in its current state.`, + `Announcement #${id} is already published or cancelled.`, ); } - try { - const sent = await messenger.send( - claimed.channelId, - announcementView(claimed), - ); - const published = await announcements.transition(id, ['publishing'], { - status: 'published', - publishedAt: clock.now(), - messageId: sent.messageId, - failure: null, - }); - - log.info( - { announcementId: id, messageId: sent.messageId }, - 'Announcement published', - ); + let sent: Sent; - return published ?? claimed; + try { + sent = await messenger.send(claimed.channelId, announcementView(claimed)); } catch (error) { const permanent = error instanceof PermanentError || error instanceof UserError; - const message = error instanceof Error ? error.message : String(error); - await announcements.transition(id, ['publishing'], { - status: permanent ? 'failed' : (from[0] ?? 'draft'), - failure: message, + await announcements.update(id, { + status: permanent ? 'draft' : (from[0] ?? 'draft'), + publishedAt: null, + failure: error instanceof Error ? error.message : String(error), }); throw error; } + + const { messageId } = sent; + + await announcements.update(id, { messageId }); + log.info({ announcementId: id, messageId }, 'Announcement published'); + + return { ...claimed, messageId }; }; const publishJob = defineJob({ @@ -186,11 +186,14 @@ export function createAnnouncementService(deps: Deps) { const due = announcement.scheduledAt ?? announcement.createdAt; if (clock.now().getTime() - due.getTime() > maxLatenessMs) { - await announcements.transition(announcementId, ['scheduled'], { - status: 'failed', - failure: - 'Skipped: the scheduled time passed while the bot was offline', - }); + await announcements.update( + announcementId, + { + status: 'draft', + failure: 'Not posted: the bot was offline at the scheduled time.', + }, + ['scheduled'], + ); log.warn({ announcementId }, 'Skipped stale scheduled announcement'); return; @@ -275,7 +278,7 @@ export function createAnnouncementService(deps: Deps) { await requireOwnGuild(actor, id); await scheduler.cancel(publishJob, jobKey(id)); - return publish(id, reopenable); + return publish(id, open); }), schedule: guard( authz, @@ -286,15 +289,19 @@ export function createAnnouncementService(deps: Deps) { await checkTargets(actor, announcement); - const scheduled = await announcements.transition(id, reopenable, { - status: 'scheduled', - scheduledAt: runAt, - failure: null, - }); + const scheduled = await announcements.update( + id, + { + status: 'scheduled', + scheduledAt: runAt, + failure: null, + }, + open, + ); if (!scheduled) { throw new UserError( - `Announcement #${id} cannot be scheduled in its current state.`, + `Announcement #${id} is already published or cancelled.`, ); } @@ -309,9 +316,13 @@ export function createAnnouncementService(deps: Deps) { ), cancel: async (actor: Actor, id: number) => { const announcement = await requireEditable(actor, id); - const cancelled = await announcements.transition(id, reopenable, { - status: 'cancelled', - }); + const cancelled = await announcements.update( + id, + { + status: 'cancelled', + }, + open, + ); if (!cancelled) { throw new UserError( diff --git a/src/infra/db/announcements/model.ts b/src/infra/db/announcements/model.ts index d2a1231..2f6423b 100644 --- a/src/infra/db/announcements/model.ts +++ b/src/infra/db/announcements/model.ts @@ -11,10 +11,8 @@ import { export const announcementStatus = pgEnum('announcement_status', [ 'draft', 'scheduled', - 'publishing', 'published', 'cancelled', - 'failed', ]); export const announcements = pgTable( diff --git a/src/infra/db/announcements/repo.ts b/src/infra/db/announcements/repo.ts index ced242f..581db18 100644 --- a/src/infra/db/announcements/repo.ts +++ b/src/infra/db/announcements/repo.ts @@ -47,37 +47,32 @@ export async function listAnnouncements( .limit(limit); } -export async function transition( +export async function updateAnnouncement( db: Db, id: number, - from: readonly Status[], changes: AnnouncementChanges, + onlyIf?: readonly Status[], ): Promise { const [row] = await db .update(announcements) .set(changes) .where( - and(eq(announcements.id, id), inArray(announcements.status, [...from])), + and( + eq(announcements.id, id), + onlyIf && inArray(announcements.status, [...onlyIf]), + ), ) .returning(); return row; } -export async function updateContent( - db: Db, - id: number, - changes: Parameters[1], -): Promise { - await db.update(announcements).set(changes).where(eq(announcements.id, id)); -} - export function createAnnouncementRepository(db: Db): AnnouncementRepository { return { insert: (announcement) => insertAnnouncement(db, announcement), find: (id) => getAnnouncement(db, id), list: (guildId, limit) => listAnnouncements(db, guildId, limit), - transition: (id, from, changes) => transition(db, id, from, changes), - update: (id, changes) => updateContent(db, id, changes), + update: (id, changes, onlyIf) => + updateAnnouncement(db, id, changes, onlyIf), }; } diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts index 3010dec..d2b5d5c 100644 --- a/src/infra/discord/commands/announcements.ts +++ b/src/infra/discord/commands/announcements.ts @@ -293,9 +293,7 @@ export function announcementCommands( await interaction.respond( rows - .filter((row) => - ['draft', 'scheduled', 'failed'].includes(row.status), - ) + .filter((row) => ['draft', 'scheduled'].includes(row.status)) .slice(0, 25) .map((row) => ({ name: `#${row.id} [${row.status}] ${row.title ?? row.content}`.slice( diff --git a/src/infra/web/app.ts b/src/infra/web/app.ts index 5cf4f40..c42709c 100644 --- a/src/infra/web/app.ts +++ b/src/infra/web/app.ts @@ -108,7 +108,7 @@ function mentionPicker(context: Context, selected: readonly string[] = []) { } const psaActions = (context: Context, psa: { id: number; status: string }) => { - if (!['draft', 'failed', 'scheduled'].includes(psa.status)) { + if (!['draft', 'scheduled'].includes(psa.status)) { return html``; } @@ -257,7 +257,14 @@ export function createWebApp(deps: Deps) { (a) => html` ${a.id} - ${a.status} + + ${a.status} + ${ + a.failure === null + ? '' + : html`
${a.failure}` + } + ${channelName(context, a.channelId)} ${a.title ?? a.content.slice(0, 60)} ${date(a.publishedAt ?? a.scheduledAt)} diff --git a/tests/core/services/announcements.test.ts b/tests/core/services/announcements.test.ts index 03e9309..7d5d824 100644 --- a/tests/core/services/announcements.test.ts +++ b/tests/core/services/announcements.test.ts @@ -93,11 +93,27 @@ describe.skipIf(noDatabase)('announcement service', () => { await service.publish(author, draft.id); await expect(service.publish(author, draft.id)).rejects.toThrow( - 'cannot be published', + 'already published', ); expect(messenger.send).toHaveBeenCalledOnce(); }); + it('goes back to draft with the reason when posting fails', async () => { + const { service, messenger, repository, author } = setup(); + const draft = await service.draft(author, { + channelId: 'c', + content: 'Hi', + }); + + messenger.send.mockRejectedValueOnce(new Error('Discord is down')); + await expect(service.publish(author, draft.id)).rejects.toThrow('down'); + expect(await repository.find(draft.id)).toMatchObject({ + status: 'draft', + publishedAt: null, + failure: 'Discord is down', + }); + }); + it('refuses unmentionable roles, everyone and channels the author cannot use', async () => { const { service, author } = setup(); @@ -130,13 +146,16 @@ describe.skipIf(noDatabase)('announcement service', () => { content: 'Hi', }); - await repository.transition(draft.id, ['draft'], { + await repository.update(draft.id, { status: 'scheduled', scheduledAt: new Date(Date.now() - 2 * 3_600_000), }); await service.jobs[0]?.run({ announcementId: draft.id }); expect(messenger.send).not.toHaveBeenCalled(); - expect((await repository.find(draft.id))?.status).toBe('failed'); + const skipped = await repository.find(draft.id); + + expect(skipped?.status).toBe('draft'); + expect(skipped?.failure).toContain('offline'); }); it('publishes due scheduled announcements once', async () => { @@ -147,7 +166,7 @@ describe.skipIf(noDatabase)('announcement service', () => { }); const job = service.jobs[0]; - await repository.transition(draft.id, ['draft'], { + await repository.update(draft.id, { status: 'scheduled', scheduledAt: new Date(), }); @@ -165,7 +184,13 @@ describe.skipIf(noDatabase)('announcement service', () => { }); const claims = await Promise.all( Array.from({ length: 5 }, () => - repository.transition(draft.id, ['draft'], { status: 'publishing' }), + repository.update( + draft.id, + { + status: 'published', + }, + ['draft'], + ), ), ); From 21c19157ecc79ae8f0da8d2e2298355433abb65f Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:35:10 +0200 Subject: [PATCH 051/199] feat(announcements): preview with publish, schedule, edit and discard buttons --- README.md | 20 +- src/infra/discord/commands/announcements.ts | 293 +++++++++++--------- 2 files changed, 179 insertions(+), 134 deletions(-) diff --git a/README.md b/README.md index 3da43db..2e94f2a 100644 --- a/README.md +++ b/README.md @@ -50,16 +50,16 @@ environment-only. ## Commands -| Command | Who | -| -------------------------------------------------------------- | -------------------------------------------------------------- | -| `/remindme`, `/reminders list/edit/cancel` | everyone; `channel:` needs `reminder:channel` | -| `/announce create/preview/publish/schedule/edit/cancel` | `announcement:create`, `:publish`, `:schedule` | -| `/event create/edit/cancel/list/view/attendees`, RSVP buttons | create needs `event:create`; organizer or `event:manage` edits | -| `/birthday set/remove/view/upcoming`, `/birthday settings` | everyone; settings need `birthday:manage` | -| `/poll create/list/results/close/cancel` | create needs `poll:create`; creator or `poll:manage` manages | -| `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | -| `/redmine subscribe/unsubscribe` | `redmine:subscription:manage` | -| `/permissions grant/revoke/list/check` | `permissions:manage` | +| Command | Who | +| ------------------------------------------------------------------------------- | -------------------------------------------------------------- | +| `/remindme`, `/reminders list/edit/cancel` | everyone; `channel:` needs `reminder:channel` | +| `/announce create` (then Publish / Schedule / Edit / Discard), `/announce edit` | `announcement:create`, `:publish`, `:schedule` | +| `/event create/edit/cancel/list/view/attendees`, RSVP buttons | create needs `event:create`; organizer or `event:manage` edits | +| `/birthday set/remove/view/upcoming`, `/birthday settings` | everyone; settings need `birthday:manage` | +| `/poll create/list/results/close/cancel` | create needs `poll:create`; creator or `poll:manage` manages | +| `/movie suggest/suggestions/remove/vote/night/watched/history` | vote, night, watched need `movie:manage` | +| `/redmine subscribe/unsubscribe` | `redmine:subscription:manage` | +| `/permissions grant/revoke/list/check` | `permissions:manage` | ## Web UI diff --git a/src/infra/discord/commands/announcements.ts b/src/infra/discord/commands/announcements.ts index d2b5d5c..64ef989 100644 --- a/src/infra/discord/commands/announcements.ts +++ b/src/infra/discord/commands/announcements.ts @@ -8,17 +8,24 @@ import { SlashCommandBuilder, TextInputBuilder, TextInputStyle, - type SlashCommandIntegerOption, } from 'discord.js'; import type { Announcement } from '~/core/ports'; import { maxAnnouncementLength, type AnnouncementService, } from '~/core/services'; -import { channelMention, controlId, discordTime } from '~/domain'; +import { + channelMention, + controlId, + discordTime, + UserError, + type Actor, + type Message, +} from '~/domain'; import { toActor } from '../actor'; -import { bySubcommand, deferred } from '../define'; -import type { ComponentHandler, Feature } from '../module'; +import { bySubcommand } from '../define'; +import type { AppContext, ComponentHandler, Feature } from '../module'; +import { render } from '../render'; import { respond, respondView } from '../router'; function contentModal( @@ -55,21 +62,14 @@ function contentModal( ); } -const idOption = (o: SlashCommandIntegerOption) => - o - .setName('id') - .setDescription('Announcement') - .setRequired(true) - .setAutocomplete(true); - const data = new SlashCommandBuilder() .setName('announce') - .setDescription('Create and publish announcements') + .setDescription('Write an announcement') .setContexts(InteractionContextType.Guild) .addSubcommand((sub) => sub .setName('create') - .setDescription('Draft an announcement') + .setDescription('Write, preview and publish an announcement') .addChannelOption((o) => o .setName('channel') @@ -83,80 +83,166 @@ const data = new SlashCommandBuilder() ) .addSubcommand((sub) => sub - .setName('preview') - .setDescription('Preview privately') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('publish') - .setDescription('Publish now') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('schedule') - .setDescription('Publish later') - .addIntegerOption(idOption) - .addStringOption((o) => + .setName('edit') + .setDescription('Fix the text of an announcement') + .addIntegerOption((o) => o - .setName('when') - .setDescription('e.g. 2h, 2026-11-20 18:00') - .setRequired(true), + .setName('id') + .setDescription('Announcement') + .setRequired(true) + .setAutocomplete(true), ), - ) - .addSubcommand((sub) => - sub - .setName('edit') - .setDescription('Edit the text') - .addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('cancel') - .setDescription('Cancel a draft or schedule') - .addIntegerOption(idOption), ); export function announcementCommands( announcements: AnnouncementService, ): Feature { - const preview = (announcement: Announcement, note: string) => { + const draftView = async ( + announcement: Announcement, + actor: Actor, + ctx: AppContext, + ): Promise => { const view = announcements.view(announcement); + const action = (name: string) => + controlId('announcements:act', announcement.id, name); + const [canPublish, canSchedule] = await Promise.all([ + ctx.authz.can(actor, 'announcement:publish'), + ctx.authz.can(actor, 'announcement:schedule'), + ]); return { ...view, - content: [note, view.content].filter(Boolean).join('\n\n'), + content: `-# Preview for ${channelMention(announcement.channelId)}\n${view.content ?? ''}`, + controls: [ + [ + ...(canPublish + ? [ + { + kind: 'button' as const, + id: action('publish'), + label: 'Publish now', + style: 'primary' as const, + }, + ] + : []), + ...(canSchedule + ? [ + { + kind: 'button' as const, + id: action('schedule'), + label: 'Schedule…', + style: 'secondary' as const, + }, + ] + : []), + { + kind: 'button', + id: action('edit'), + label: 'Edit', + style: 'secondary', + }, + { + kind: 'button', + id: action('discard'), + label: 'Discard', + style: 'danger', + }, + ], + ], }; }; + const done = (content: string) => ({ content, embeds: [], components: [] }); + const create: ComponentHandler = { prefix: 'announcements:create', - execute: async (interaction, args) => { + execute: async (interaction, [channelId = ''], ctx) => { if (!interaction.isModalSubmit()) { return; } - const [channelId = ''] = args; + const actor = toActor(interaction.member); const roles = interaction.fields.getSelectedRoles('mentions'); - const announcement = await announcements.draft( + const announcement = await announcements.draft(actor, { + channelId, + title: interaction.fields.getTextInputValue('title'), + content: interaction.fields.getTextInputValue('content'), + mentionRoleIds: roles ? [...roles.keys()] : [], + mentionEveryone: interaction.fields + .getStringSelectValues('everyone') + .includes('everyone'), + }); + + await respondView(interaction, await draftView(announcement, actor, ctx)); + }, + }; + + const act: ComponentHandler = { + prefix: 'announcements:act', + execute: async (interaction, [rawId, name]) => { + const id = Number(rawId); + + if (!interaction.isButton() || !Number.isSafeInteger(id)) { + throw new UserError('This button is invalid.'); + } + + const actor = toActor(interaction.member); + + if (name === 'publish') { + const published = await announcements.publish(actor, id); + + await interaction.update( + done(`Published in ${channelMention(published.channelId)}.`), + ); + } else if (name === 'schedule') { + await interaction.showModal( + new ModalBuilder() + .setCustomId(controlId('announcements:when', id)) + .setTitle('Schedule announcement') + .addLabelComponents( + new LabelBuilder() + .setLabel('When') + .setDescription('e.g. tomorrow 18:00, fri 9:00, 20.11 18:00') + .setTextInputComponent( + new TextInputBuilder() + .setCustomId('when') + .setStyle(TextInputStyle.Short), + ), + ), + ); + } else if (name === 'edit') { + await interaction.showModal( + contentModal( + controlId('announcements:edit', id), + 'Edit announcement', + await announcements.get(actor, id), + ), + ); + } else if (name === 'discard') { + await announcements.cancel(actor, id); + await interaction.update(done('Discarded.')); + } else { + throw new UserError('This button is invalid.'); + } + }, + }; + + const when: ComponentHandler = { + prefix: 'announcements:when', + execute: async (interaction, [id]) => { + if (!interaction.isModalSubmit() || !interaction.isFromMessage()) { + return; + } + + const scheduled = await announcements.schedule( toActor(interaction.member), - { - channelId, - title: interaction.fields.getTextInputValue('title'), - content: interaction.fields.getTextInputValue('content'), - mentionRoleIds: roles ? [...roles.keys()] : [], - mentionEveryone: interaction.fields - .getStringSelectValues('everyone') - .includes('everyone'), - }, + Number(id), + interaction.fields.getTextInputValue('when'), ); - await respondView( - interaction, - preview( - announcement, - `Draft #${announcement.id} for ${channelMention(channelId)}. Publish with "/announce publish" or "/announce schedule".`, + await interaction.update( + done( + `Will be posted in ${channelMention(scheduled.channelId)} ${discordTime(scheduled.scheduledAt ?? new Date())}.`, ), ); }, @@ -164,35 +250,42 @@ export function announcementCommands( const edit: ComponentHandler = { prefix: 'announcements:edit', - execute: async (interaction, [id]) => { + execute: async (interaction, [id], ctx) => { if (!interaction.isModalSubmit()) { return; } - const updated = await announcements.edit( - toActor(interaction.member), - Number(id), - { - title: interaction.fields.getTextInputValue('title'), - content: interaction.fields.getTextInputValue('content'), - }, - ); + const actor = toActor(interaction.member); + const updated = await announcements.edit(actor, Number(id), { + title: interaction.fields.getTextInputValue('title'), + content: interaction.fields.getTextInputValue('content'), + }); + + if (interaction.isFromMessage() && updated.status === 'draft') { + const { content, components } = render( + await draftView(updated, actor, ctx), + ); - await respond(interaction, `Announcement #${updated.id} updated.`); + await interaction.update({ content, components }); + + return; + } + + await respond(interaction, 'Announcement updated.'); }, }; return { name: 'announcements', permissions: [ - { id: 'announcement:create', description: 'Draft announcements' }, + { id: 'announcement:create', description: 'Write announcements' }, { id: 'announcement:publish', description: 'Publish and edit any announcement', }, { id: 'announcement:schedule', description: 'Schedule announcements' }, ], - components: [create, edit], + components: [create, act, when, edit], commands: [ { data: data.toJSON(), @@ -225,43 +318,6 @@ export function announcementCommands( ), ); }, - preview: async (interaction) => { - const announcement = await announcements.get( - toActor(interaction.member), - interaction.options.getInteger('id', true), - ); - - await respondView( - interaction, - preview( - announcement, - `Preview of #${announcement.id} (${announcement.status}):`, - ), - ); - }, - publish: deferred(async (interaction) => { - const published = await announcements.publish( - toActor(interaction.member), - interaction.options.getInteger('id', true), - ); - - await respond( - interaction, - `Published #${published.id} in ${channelMention(published.channelId)}.`, - ); - }), - schedule: async (interaction) => { - const scheduled = await announcements.schedule( - toActor(interaction.member), - interaction.options.getInteger('id', true), - interaction.options.getString('when', true), - ); - - await respond( - interaction, - `Announcement #${scheduled.id} will be published ${discordTime(scheduled.scheduledAt ?? new Date())}.`, - ); - }, edit: async (interaction) => { const announcement = await announcements.get( toActor(interaction.member), @@ -276,24 +332,13 @@ export function announcementCommands( ), ); }, - cancel: async (interaction) => { - const cancelled = await announcements.cancel( - toActor(interaction.member), - interaction.options.getInteger('id', true), - ); - - await respond( - interaction, - `Cancelled announcement #${cancelled.id}.`, - ); - }, }), autocomplete: async (interaction) => { const rows = await announcements.list(interaction.guildId); await interaction.respond( rows - .filter((row) => ['draft', 'scheduled'].includes(row.status)) + .filter((row) => row.status !== 'cancelled') .slice(0, 25) .map((row) => ({ name: `#${row.id} [${row.status}] ${row.title ?? row.content}`.slice( From a353284fea8a043e9cb4a3092543b7b4870e0aae Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:37:49 +0200 Subject: [PATCH 052/199] feat(polls): post as plain text, limited to 10 options of 55 characters like Discord polls --- src/core/services/movies.ts | 3 ++- src/core/services/polls.ts | 16 ++++++---------- src/domain/poll.ts | 8 +++++--- src/infra/discord/commands/movies.ts | 4 ++-- src/infra/discord/commands/polls.ts | 2 +- tests/core/services/polls.test.ts | 4 ++-- 6 files changed, 18 insertions(+), 19 deletions(-) diff --git a/src/core/services/movies.ts b/src/core/services/movies.ts index ecb3db7..d2ea2ac 100644 --- a/src/core/services/movies.ts +++ b/src/core/services/movies.ts @@ -1,4 +1,5 @@ import { + maxOptionLength, movieLabel, parseFutureWhen, parseWhen, @@ -114,7 +115,7 @@ export function createMovieService(deps: Deps) { creatorId: actor.userId, question: '🎬 What should we watch next?', options: candidates.map((m) => ({ - label: movieLabel(m).slice(0, 100), + label: movieLabel(m).slice(0, maxOptionLength), ref: String(m.id), })), closesAt, diff --git a/src/core/services/polls.ts b/src/core/services/polls.ts index 8163933..8c18bc5 100644 --- a/src/core/services/polls.ts +++ b/src/core/services/polls.ts @@ -62,13 +62,13 @@ export function pollView(poll: PollWithOptions, results: PollResults): Message { const showCounts = poll.showResults === 'live' || !open; const lines = results.options.map((option) => showCounts - ? `**${option.label}**\n${bar(option.votes, results.voters)} ${option.votes}` + ? `${bar(option.votes, results.voters)} ${option.votes} · **${option.label}**` : `• ${option.label}`, ); const outcome = !open && results.winners.length > 0 - ? `\n\n${describeOutcome(results, 'Winner')}` - : ''; + ? [describeOutcome(results, 'Winner')] + : []; const footer = [ `Poll #${poll.id}`, poll.multiple ? 'multiple choice' : 'single choice', @@ -78,13 +78,9 @@ export function pollView(poll: PollWithOptions, results: PollResults): Message { ].join(' · '); return { - embeds: [ - { - title: poll.question, - description: `${lines.join('\n')}${outcome}`, - footer, - }, - ], + content: [`# ${poll.question}`, ...lines, ...outcome, `-# ${footer}`].join( + '\n', + ), controls: open ? [ [ diff --git a/src/domain/poll.ts b/src/domain/poll.ts index 8b498eb..c5865f7 100644 --- a/src/domain/poll.ts +++ b/src/domain/poll.ts @@ -1,6 +1,8 @@ import { UserError } from './errors'; -export const maxPollOptions = 25; +export const maxPollOptions = 10; + +export const maxOptionLength = 55; export type Tally = { options: Array; @@ -43,8 +45,8 @@ export function validatePollOptions(labels: readonly string[]): string[] { ); } - if (trimmed.some((label) => label === '' || label.length > 100)) { - throw new UserError('Options must be 1–100 characters.'); + if (trimmed.some((label) => label === '' || label.length > maxOptionLength)) { + throw new UserError(`Options must be 1–${maxOptionLength} characters.`); } if ( diff --git a/src/infra/discord/commands/movies.ts b/src/infra/discord/commands/movies.ts index dfd7e39..080ff09 100644 --- a/src/infra/discord/commands/movies.ts +++ b/src/infra/discord/commands/movies.ts @@ -5,7 +5,7 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import type { MovieService } from '~/core/services'; -import { discordTime, movieLabel, userMention } from '~/domain'; +import { discordTime, maxPollOptions, movieLabel, userMention } from '~/domain'; import { toActor } from '../actor'; import { bySubcommand, deferred } from '../define'; import type { Feature } from '../module'; @@ -58,7 +58,7 @@ const data = new SlashCommandBuilder() .setName('count') .setDescription('How many movies (default 10)') .setMinValue(2) - .setMaxValue(25), + .setMaxValue(maxPollOptions), ) .addStringOption((o) => o.setName('closes').setDescription('When voting ends (default 2d)'), diff --git a/src/infra/discord/commands/polls.ts b/src/infra/discord/commands/polls.ts index 84d205b..a20716e 100644 --- a/src/infra/discord/commands/polls.ts +++ b/src/infra/discord/commands/polls.ts @@ -217,7 +217,7 @@ export function pollCommands(polls: PollService): Feature { await respond( interaction, - [`**${poll.question}**`, ...lines, winner] + [`# ${poll.question}`, ...lines, winner] .join('\n') .slice(0, 2000), ); diff --git a/tests/core/services/polls.test.ts b/tests/core/services/polls.test.ts index 1464ffa..6ee70b3 100644 --- a/tests/core/services/polls.test.ts +++ b/tests/core/services/polls.test.ts @@ -130,7 +130,7 @@ describe.skipIf(noDatabase)('poll service', () => { [poll.options[0]?.id ?? 0], ); - expect(JSON.stringify(view.embeds)).not.toContain('█'); + expect(view.content).not.toContain('█'); }); it('closes on schedule, shows the winner and removes controls', async () => { @@ -155,7 +155,7 @@ describe.skipIf(noDatabase)('poll service', () => { if (closed) { const view = pollView(closed, await repository.results(closed)); - expect(JSON.stringify(view.embeds)).toContain('Winner'); + expect(view.content).toContain('Winner'); expect(view.controls).toEqual([]); } From 4c2d4a9ca9f8dce3c17cc7f4393b9a61b11325e5 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:42:52 +0200 Subject: [PATCH 053/199] =?UTF-8?q?feat(events):=20date,=20time=20and=20pl?= =?UTF-8?q?ace=20lines=20with=20optional=20=F0=9F=97=93=EF=B8=8F=20?= =?UTF-8?q?=F0=9F=95=90=20=F0=9F=93=8D=20icons?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- drizzle/0007_event_icons.sql | 1 + drizzle/meta/0007_snapshot.json | 1529 ++++++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/core/ports/events.ts | 1 + src/core/services/events.ts | 38 +- src/core/services/movies.ts | 1 + src/domain/time.ts | 9 +- src/infra/db/events/model.ts | 2 + src/infra/discord/commands/events.ts | 10 + src/infra/web/app.ts | 5 + tests/core/services/events.test.ts | 24 + 11 files changed, 1616 insertions(+), 11 deletions(-) create mode 100644 drizzle/0007_event_icons.sql create mode 100644 drizzle/meta/0007_snapshot.json diff --git a/drizzle/0007_event_icons.sql b/drizzle/0007_event_icons.sql new file mode 100644 index 0000000..b39044b --- /dev/null +++ b/drizzle/0007_event_icons.sql @@ -0,0 +1 @@ +ALTER TABLE "events" ADD COLUMN "icons" boolean DEFAULT true NOT NULL; \ No newline at end of file diff --git a/drizzle/meta/0007_snapshot.json b/drizzle/meta/0007_snapshot.json new file mode 100644 index 0000000..45bb35f --- /dev/null +++ b/drizzle/meta/0007_snapshot.json @@ -0,0 +1,1529 @@ +{ + "id": "82115765-7d96-4f12-9c4f-01550eca46a1", + "prevId": "e35670ef-b1eb-4e4b-aa0d-686e6a9ca60d", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.announcements": { + "name": "announcements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mention_role_ids": { + "name": "mention_role_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "mention_everyone": { + "name": "mention_everyone", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "status": { + "name": "status", + "type": "announcement_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "announcements_guild_idx": { + "name": "announcements_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthday_settings": { + "name": "birthday_settings", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hour": { + "name": "hour", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 9 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.birthdays": { + "name": "birthdays", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "month": { + "name": "month", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "birthday_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "last_announced_year": { + "name": "last_announced_year", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "birthdays_date_idx": { + "name": "birthdays_date_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "birthdays_guild_id_user_id_pk": { + "name": "birthdays_guild_id_user_id_pk", + "columns": [ + "guild_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_rsvps": { + "name": "event_rsvps", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "rsvp_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "event_rsvps_status_idx": { + "name": "event_rsvps_status_idx", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_rsvps_event_id_events_id_fk": { + "name": "event_rsvps_event_id_events_id_fk", + "tableFrom": "event_rsvps", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "event_rsvps_event_id_user_id_pk": { + "name": "event_rsvps_event_id_user_id_pk", + "columns": [ + "event_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organizer_id": { + "name": "organizer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capacity": { + "name": "capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "mention_role_id": { + "name": "mention_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_minutes": { + "name": "reminder_minutes", + "type": "integer[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "icons": { + "name": "icons", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "discord_event_id": { + "name": "discord_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "event_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "events_guild_start_idx": { + "name": "events_guild_start_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_screenings": { + "name": "movie_screenings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suggestion_id": { + "name": "suggestion_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "watched_at": { + "name": "watched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "movie_screenings_guild_idx": { + "name": "movie_screenings_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "watched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "movie_screenings_suggestion_id_movie_suggestions_id_fk": { + "name": "movie_screenings_suggestion_id_movie_suggestions_id_fk", + "tableFrom": "movie_screenings", + "tableTo": "movie_suggestions", + "columnsFrom": [ + "suggestion_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.movie_suggestions": { + "name": "movie_suggestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_title": { + "name": "normalized_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_by": { + "name": "suggested_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "movie_suggestions_unique_idx": { + "name": "movie_suggestions_unique_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"movie_suggestions\".\"removed_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_permissions": { + "name": "role_permissions", + "schema": "", + "columns": { + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "role_permissions_guild_id_role_id_permission_pk": { + "name": "role_permissions_guild_id_role_id_permission_pk", + "columns": [ + "guild_id", + "role_id", + "permission" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_options": { + "name": "poll_options", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "poll_options_poll_id_polls_id_fk": { + "name": "poll_options_poll_id_polls_id_fk", + "tableFrom": "poll_options", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "poll_options_position_unique": { + "name": "poll_options_position_unique", + "nullsNotDistinct": false, + "columns": [ + "poll_id", + "position" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.poll_votes": { + "name": "poll_votes", + "schema": "", + "columns": { + "poll_id": { + "name": "poll_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "poll_votes_option_idx": { + "name": "poll_votes_option_idx", + "columns": [ + { + "expression": "option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "poll_votes_poll_id_polls_id_fk": { + "name": "poll_votes_poll_id_polls_id_fk", + "tableFrom": "poll_votes", + "tableTo": "polls", + "columnsFrom": [ + "poll_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "poll_votes_option_id_poll_options_id_fk": { + "name": "poll_votes_option_id_poll_options_id_fk", + "tableFrom": "poll_votes", + "tableTo": "poll_options", + "columnsFrom": [ + "option_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "poll_votes_poll_id_user_id_option_id_pk": { + "name": "poll_votes_poll_id_user_id_option_id_pk", + "columns": [ + "poll_id", + "user_id", + "option_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.polls": { + "name": "polls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "multiple": { + "name": "multiple", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "anonymous": { + "name": "anonymous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_results": { + "name": "show_results", + "type": "poll_result_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'live'" + }, + "closes_at": { + "name": "closes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "poll_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "polls_guild_status_idx": { + "name": "polls_guild_status_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "polls_source_idx": { + "name": "polls_source_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_notifications": { + "name": "redmine_notifications", + "schema": "", + "columns": { + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "redmine_notifications_subscription_id_redmine_subscriptions_id_fk": { + "name": "redmine_notifications_subscription_id_redmine_subscriptions_id_fk", + "tableFrom": "redmine_notifications", + "tableTo": "redmine_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "redmine_notifications_subscription_id_key_pk": { + "name": "redmine_notifications_subscription_id_key_pk", + "columns": [ + "subscription_id", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.redmine_subscriptions": { + "name": "redmine_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "project_name": { + "name": "project_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checkpoint": { + "name": "checkpoint", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "redmine_subscriptions_unique": { + "name": "redmine_subscriptions_unique", + "nullsNotDistinct": false, + "columns": [ + "channel_id", + "project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reminders": { + "name": "reminders", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "recurrence": { + "name": "recurrence", + "type": "reminder_recurrence", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "reminder_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reminders_user_idx": { + "name": "reminders_user_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panel_roles": { + "name": "role_panel_roles", + "schema": "", + "columns": { + "panel_id": { + "name": "panel_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "role_panel_roles_panel_id_role_panels_id_fk": { + "name": "role_panel_roles_panel_id_role_panels_id_fk", + "tableFrom": "role_panel_roles", + "tableTo": "role_panels", + "columnsFrom": [ + "panel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "role_panel_roles_panel_id_role_id_pk": { + "name": "role_panel_roles_panel_id_role_id_pk", + "columns": [ + "panel_id", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.role_panels": { + "name": "role_panels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "guild_id": { + "name": "guild_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "role_panel_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "role_panels_guild_idx": { + "name": "role_panels_guild_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "role_panels_reaction_channel_idx": { + "name": "role_panels_reaction_channel_idx", + "columns": [ + { + "expression": "guild_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"role_panels\".\"kind\" = 'reaction'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "role_panels_message_id_unique": { + "name": "role_panels_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.announcement_status": { + "name": "announcement_status", + "schema": "public", + "values": [ + "draft", + "scheduled", + "published", + "cancelled" + ] + }, + "public.birthday_visibility": { + "name": "birthday_visibility", + "schema": "public", + "values": [ + "public", + "announce", + "private" + ] + }, + "public.event_status": { + "name": "event_status", + "schema": "public", + "values": [ + "scheduled", + "cancelled" + ] + }, + "public.rsvp_status": { + "name": "rsvp_status", + "schema": "public", + "values": [ + "going", + "maybe", + "not_going" + ] + }, + "public.poll_result_visibility": { + "name": "poll_result_visibility", + "schema": "public", + "values": [ + "live", + "closed" + ] + }, + "public.poll_status": { + "name": "poll_status", + "schema": "public", + "values": [ + "open", + "closed", + "cancelled" + ] + }, + "public.reminder_recurrence": { + "name": "reminder_recurrence", + "schema": "public", + "values": [ + "daily", + "weekly", + "monthly" + ] + }, + "public.reminder_status": { + "name": "reminder_status", + "schema": "public", + "values": [ + "active", + "done", + "cancelled", + "failed" + ] + }, + "public.role_panel_kind": { + "name": "role_panel_kind", + "schema": "public", + "values": [ + "reaction", + "select" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 2259366..9900a56 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -50,6 +50,13 @@ "when": 1794824856256, "tag": "0006_simplify_announcement_status", "breakpoints": true + }, + { + "idx": 7, + "version": "7", + "when": 1794825575233, + "tag": "0007_event_icons", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/core/ports/events.ts b/src/core/ports/events.ts index 0c1e3e1..26dc454 100644 --- a/src/core/ports/events.ts +++ b/src/core/ports/events.ts @@ -19,6 +19,7 @@ export type Event = { capacity: number | null; mentionRoleId: string | null; reminderMinutes: number[]; + icons: boolean; discordEventId: string | null; status: 'scheduled' | 'cancelled'; createdAt: Date; diff --git a/src/core/services/events.ts b/src/core/services/events.ts index 0292004..2609d88 100644 --- a/src/core/services/events.ts +++ b/src/core/services/events.ts @@ -9,6 +9,7 @@ import { requireMentionable, requireZone, roleMention, + sameCalendarDay, UserError, userMention, type Actor, @@ -53,37 +54,52 @@ export type EventRequest = { reminders?: string; timezone?: string; native?: boolean; + icons?: boolean; }; export type EventChanges = Partial< Pick< EventRequest, - 'title' | 'start' | 'end' | 'description' | 'location' | 'capacity' + | 'title' + | 'start' + | 'end' + | 'description' + | 'location' + | 'capacity' + | 'icons' > >; export function eventView(event: Event, counts: RsvpCounts): Message { const cancelled = event.status === 'cancelled'; - const until = event.endsAt ? ` – ${discordTime(event.endsAt, 'f')}` : ''; + const icon = (emoji: string) => (event.icons ? `${emoji} ` : ''); + const endStyle = + event.endsAt !== null && + sameCalendarDay(event.startsAt, event.endsAt, event.timezone) + ? 't' + : 'f'; + const end = + event.endsAt === null ? '' : ` – ${discordTime(event.endsAt, endStyle)}`; const going = event.capacity === null ? String(counts.going) : `${counts.going} / ${event.capacity}`; + const details = [ + `${icon('🗓️')}${discordTime(event.startsAt, 'D')} (${discordTime(event.startsAt, 'R')})`, + `${icon('🕐')}${discordTime(event.startsAt, 't')}${end}`, + ...(event.location === null ? [] : [`${icon('📍')}${event.location}`]), + ]; return { embeds: [ { title: cancelled ? `[Cancelled] ${event.title}` : event.title, color: cancelled ? 0x80_80_80 : 0x2b_8a_3e, - ...(event.description !== null && { description: event.description }), + description: [ + ...(event.description === null ? [] : [event.description, '']), + ...details, + ].join('\n'), fields: [ - { - name: 'When', - value: `${discordTime(event.startsAt)} (${discordTime(event.startsAt, 'R')})${until}`, - }, - ...(event.location === null - ? [] - : [{ name: 'Where', value: event.location }]), { name: 'Organizer', value: userMention(event.organizerId), @@ -382,6 +398,7 @@ export function createEventService(deps: Deps) { capacity: request.capacity ?? null, mentionRoleId: request.mentionRoleId ?? null, reminderMinutes: parseReminderMinutes(request.reminders), + icons: request.icons ?? true, }, request.native ?? false, ); @@ -415,6 +432,7 @@ export function createEventService(deps: Deps) { description: changes.description ?? event.description, location: changes.location ?? event.location, capacity: changes.capacity ?? event.capacity, + icons: changes.icons ?? event.icons, startsAt, endsAt, }); diff --git a/src/core/services/movies.ts b/src/core/services/movies.ts index d2ea2ac..6daa62d 100644 --- a/src/core/services/movies.ts +++ b/src/core/services/movies.ts @@ -139,6 +139,7 @@ export function createMovieService(deps: Deps) { capacity: night.capacity ?? null, mentionRoleId: null, reminderMinutes: [60], + icons: true, }); await movies.recordScreening({ diff --git a/src/domain/time.ts b/src/domain/time.ts index 636735f..2afa00d 100644 --- a/src/domain/time.ts +++ b/src/domain/time.ts @@ -180,6 +180,13 @@ export function calendarDay(date: Date, zone: string): CalendarDay { }; } +export function sameCalendarDay(a: Date, b: Date, zone: string): boolean { + return ( + formatCalendarDay(calendarDay(a, zone)) === + formatCalendarDay(calendarDay(b, zone)) + ); +} + export function zonedTime(day: CalendarDay, hour: number, zone: string): Date { return new Date( new TZDate(day.year, day.month - 1, day.day, hour, 0, 0, zone).getTime(), @@ -188,7 +195,7 @@ export function zonedTime(day: CalendarDay, hour: number, zone: string): Date { export function discordTime( date: Date, - style: 'F' | 'R' | 'f' | 'D' = 'F', + style: 'F' | 'R' | 'f' | 'D' | 't' = 'F', ): string { return ``; } diff --git a/src/infra/db/events/model.ts b/src/infra/db/events/model.ts index 820d539..99a9bb0 100644 --- a/src/infra/db/events/model.ts +++ b/src/infra/db/events/model.ts @@ -1,4 +1,5 @@ import { + boolean, index, integer, pgEnum, @@ -33,6 +34,7 @@ export const events = pgTable( capacity: integer('capacity'), mentionRoleId: text('mention_role_id'), reminderMinutes: integer('reminder_minutes').array().notNull().default([]), + icons: boolean('icons').notNull().default(true), discordEventId: text('discord_event_id'), status: eventStatus('status').notNull().default('scheduled'), createdAt: timestamp('created_at', { withTimezone: true }) diff --git a/src/infra/discord/commands/events.ts b/src/infra/discord/commands/events.ts index 4d3b031..0d1dac6 100644 --- a/src/infra/discord/commands/events.ts +++ b/src/infra/discord/commands/events.ts @@ -82,6 +82,9 @@ const data = new SlashCommandBuilder() o .setName('native') .setDescription('Also create a Discord scheduled event'), + ) + .addBooleanOption((o) => + o.setName('icons').setDescription('Show 🗓️ 🕐 📍 icons (default yes)'), ), ) .addSubcommand((sub) => @@ -108,6 +111,9 @@ const data = new SlashCommandBuilder() .setName('capacity') .setDescription('Maximum attendees') .setMinValue(1), + ) + .addBooleanOption((o) => + o.setName('icons').setDescription('Show 🗓️ 🕐 📍 icons'), ), ) .addSubcommand((sub) => @@ -175,6 +181,7 @@ export function eventCommands(events: EventService): Feature { execute: bySubcommand({ create: deferred(async (interaction) => { const capacity = interaction.options.getInteger('capacity'); + const icons = interaction.options.getBoolean('icons'); const mention = interaction.options.getRole('mention'); const fields = [ 'description', @@ -199,6 +206,7 @@ export function eventCommands(events: EventService): Feature { interaction.channelId, native: interaction.options.getBoolean('native') ?? false, ...(capacity !== null && { capacity }), + ...(icons !== null && { icons }), ...(mention && { mentionRoleId: mention.id }), }); @@ -209,6 +217,7 @@ export function eventCommands(events: EventService): Feature { }), edit: deferred(async (interaction) => { const capacity = interaction.options.getInteger('capacity'); + const icons = interaction.options.getBoolean('icons'); const fields = [ 'title', 'start', @@ -229,6 +238,7 @@ export function eventCommands(events: EventService): Feature { { ...changes, ...(capacity !== null && { capacity }), + ...(icons !== null && { icons }), }, ); diff --git a/src/infra/web/app.ts b/src/infra/web/app.ts index c42709c..33b9091 100644 --- a/src/infra/web/app.ts +++ b/src/infra/web/app.ts @@ -396,6 +396,10 @@ export function createWebApp(deps: Deps) { > Also create a Discord event +
@@ -443,6 +447,7 @@ export function createWebApp(deps: Deps) { start: field(context.form, 'start') ?? '', channelId: field(context.form, 'channelId') ?? '', native: context.form.get('native') === '1', + icons: context.form.get('icons') === '1', ...(capacity !== undefined && { capacity: Number(capacity) }), ...Object.fromEntries( optional.flatMap((name) => { diff --git a/tests/core/services/events.test.ts b/tests/core/services/events.test.ts index 16f12a2..c6d08e8 100644 --- a/tests/core/services/events.test.ts +++ b/tests/core/services/events.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { Calendar, Scheduler } from '~/core/ports'; import { createEventService, + eventView, parseReminderMinutes, reminderText, } from '~/core/services'; @@ -29,6 +30,7 @@ const base = () => ({ capacity: null, mentionRoleId: null, reminderMinutes: [], + icons: true, }); describe('event helpers', () => { @@ -38,6 +40,28 @@ describe('event helpers', () => { expect(() => parseReminderMinutes('1,2,3,4')).toThrow(UserError); }); + it('shows date, time and place with icons unless they are turned off', () => { + const event = { + ...base(), + id: 1, + messageId: null, + discordEventId: null, + status: 'scheduled' as const, + createdAt: new Date(), + startsAt: new Date('2026-11-20T16:00:00Z'), + endsAt: new Date('2026-11-20T19:00:00Z'), + location: 'Room 101', + }; + const counts = { going: 0, maybe: 0, not_going: 0 }; + const text = (icons: boolean) => + eventView({ ...event, icons }, counts).embeds?.[0]?.description ?? ''; + + expect(text(true)).toContain('🗓️ – '); + expect(text(true)).toContain('📍 Room 101'); + expect(text(false)).not.toMatch(/🗓️|🕐|📍/u); + }); + it('keeps reminder pings under the Discord message limit', () => { const going = Array.from( { length: 200 }, From 715172bdce7013a604b054ab20f3798c10f59eab Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 12:45:42 +0200 Subject: [PATCH 054/199] feat(events): reminder choices, end time read from the start, no timezone option --- src/core/services/events.ts | 34 +++++++++++++++++++--------- src/infra/discord/commands/events.ts | 21 +++++++++++------ src/infra/web/app.ts | 30 ++++++++++++++++-------- 3 files changed, 57 insertions(+), 28 deletions(-) diff --git a/src/core/services/events.ts b/src/core/services/events.ts index 2609d88..a0b0651 100644 --- a/src/core/services/events.ts +++ b/src/core/services/events.ts @@ -7,7 +7,6 @@ import { parseFutureWhen, parseWhen, requireMentionable, - requireZone, roleMention, sameCalendarDay, UserError, @@ -52,7 +51,6 @@ export type EventRequest = { capacity?: number; mentionRoleId?: string; reminders?: string; - timezone?: string; native?: boolean; icons?: boolean; }; @@ -127,12 +125,20 @@ export function eventView(event: Event, counts: RsvpCounts): Message { }; } +export const reminderChoices = [ + { label: '1 hour before', value: '60' }, + { label: '15 minutes before', value: '15' }, + { label: '1 day before', value: '1440' }, + { label: '1 day and 1 hour before', value: '1440,60' }, + { label: 'No reminders', value: 'none' }, +] as const; + export function parseReminderMinutes(value: string | undefined): number[] { if (value === undefined) { return [60]; } - if (value.trim() === '') { + if (value.trim() === '' || value === 'none') { return []; } @@ -379,18 +385,24 @@ export function createEventService(deps: Deps) { requireMentionable(actor, role); } - const timezone = - request.timezone === undefined - ? deps.timezone - : requireZone(request.timezone); + const { timezone } = deps; + const startsAt = parseFutureWhen(request.start, timezone); + const endsAt = + request.end === undefined + ? null + : parseWhen(request.end, timezone, startsAt); + + if (endsAt && endsAt <= startsAt) { + throw new UserError('The end must be after the start.'); + } + const event = await publish( { guildId: actor.guildId, title: request.title, description: request.description ?? null, - startsAt: parseFutureWhen(request.start, timezone), - endsAt: - request.end === undefined ? null : parseWhen(request.end, timezone), + startsAt, + endsAt, timezone, location: request.location ?? null, organizerId: actor.userId, @@ -421,7 +433,7 @@ export function createEventService(deps: Deps) { const endsAt = changes.end === undefined ? event.endsAt - : parseWhen(changes.end, event.timezone); + : parseWhen(changes.end, event.timezone, startsAt); if (endsAt && endsAt <= startsAt) { throw new UserError('The end must be after the start.'); diff --git a/src/infra/discord/commands/events.ts b/src/infra/discord/commands/events.ts index 0d1dac6..e02bc64 100644 --- a/src/infra/discord/commands/events.ts +++ b/src/infra/discord/commands/events.ts @@ -5,7 +5,11 @@ import { type SlashCommandIntegerOption, } from 'discord.js'; import { rsvpStatuses, type RsvpStatus } from '~/core/ports'; -import { rsvpLabels, type EventService } from '~/core/services'; +import { + reminderChoices, + rsvpLabels, + type EventService, +} from '~/core/services'; import { channelMention, discordTime, userMention, UserError } from '~/domain'; import { toActor } from '../actor'; import { bySubcommand, deferred } from '../define'; @@ -47,7 +51,9 @@ const data = new SlashCommandBuilder() .setDescription('Description') .setMaxLength(2000), ) - .addStringOption((o) => o.setName('end').setDescription('End time')) + .addStringOption((o) => + o.setName('end').setDescription('e.g. 21:00 or 3h after the start'), + ) .addStringOption((o) => o.setName('location').setDescription('Place or link').setMaxLength(200), ) @@ -73,10 +79,12 @@ const data = new SlashCommandBuilder() .addStringOption((o) => o .setName('reminders') - .setDescription('Minutes before start, e.g. "60,15" (default 60)'), - ) - .addStringOption((o) => - o.setName('timezone').setDescription('IANA timezone for the times'), + .setDescription( + 'When to remind people who are going (default 1 hour before)', + ) + .addChoices( + reminderChoices.map(({ label, value }) => ({ name: label, value })), + ), ) .addBooleanOption((o) => o @@ -188,7 +196,6 @@ export function eventCommands(events: EventService): Feature { 'end', 'location', 'reminders', - 'timezone', ] as const; const extras = Object.fromEntries( fields.flatMap((name) => { diff --git a/src/infra/web/app.ts b/src/infra/web/app.ts index 33b9091..d258e5f 100644 --- a/src/infra/web/app.ts +++ b/src/infra/web/app.ts @@ -6,11 +6,12 @@ import type { Directory, Logger, } from '~/core/ports'; -import type { - AnnouncementService, - EventService, - PermissionService, - PollService, +import { + reminderChoices, + type AnnouncementService, + type EventService, + type PermissionService, + type PollService, } from '~/core/services'; import { UserError, type Actor, type RoleInfo } from '~/domain'; import { html, raw, type Html } from '~/lib'; @@ -370,9 +371,11 @@ export function createWebApp(deps: Deps) { /> + -
- - - - - - - - - - - - ${list.map( - (a) => - html` - - - - - - - `, - )} - -
#StatusChannelTitleWhen
${a.id} - ${a.status} - ${ - a.failure === null - ? '' - : html`
${a.failure}` - } -
${channelName(context, a.channelId)}${a.title ?? a.content.slice(0, 60)}${date(a.publishedAt ?? a.scheduledAt)}${psaActions(context, a)}
`, - ), - }; - }, - }, - { - method: 'POST', - pattern: /^\/psa$/, - handle: async (context) => { - const action = context.form.get('action'); - const draft = psaDraft(context); - - if (action === 'preview') { - const view = services.announcements.view({ - ...draft, - title: draft.title === '' ? null : draft.title, - id: 0, - guildId: deps.guildId, - authorId: context.actor.userId, - status: 'draft', - scheduledAt: null, - publishedAt: null, - messageId: null, - failure: null, - createdAt: new Date(), - }); - - return { - body: page( - 'Public service announcements', - '/psa', - context.flash, - psaForm( - context, - html`

Preview

- ${messagePreview(view, context.guild.names)}`, - ), - ), - }; - } - - const created = await services.announcements.draft( - context.actor, - draft, - ); - - if (action === 'publish') { - await services.announcements.publish(context.actor, created.id); - - return redirect('/psa', { notice: `PSA #${created.id} published.` }); - } - - if (action === 'schedule') { - const scheduled = await services.announcements.schedule( - context.actor, - created.id, - field(context.form, 'when') ?? '', - ); - - return redirect('/psa', { - notice: `PSA #${created.id} scheduled for ${date(scheduled.scheduledAt)} UTC.`, - }); - } - - return redirect('/psa', { notice: `Draft #${created.id} saved.` }); - }, - }, - { - method: 'POST', - pattern: /^\/psa\/(\d+)\/(publish|cancel)$/, - handle: async (context, [id = '', action]) => { - await (action === 'publish' - ? services.announcements.publish(context.actor, Number(id)) - : services.announcements.cancel(context.actor, Number(id))); - - return redirect('/psa', { - notice: `PSA #${id} ${action === 'publish' ? 'published' : 'cancelled'}.`, - }); - }, - }, - { - method: 'GET', - pattern: /^\/events$/, - handle: async (context) => { - const upcoming = await services.events.upcoming(deps.guildId); - - return { - body: page( - 'Events', - context.path, - context.flash, - html`
- ${context.csrf} - - - - - - ${channelSelect(context)} - - - - -
-
- - - - - - - - - - - - ${upcoming.map( - (e) => - html` - - - - - - `, - )} - -
#TitleStartsChannel
${e.id}${e.title}${date(e.startsAt)} UTC${channelName(context, e.channelId)} - ${button(context, `/events/${e.id}/cancel`, 'Cancel')} -
`, - ), - }; - }, - }, - { - method: 'POST', - pattern: /^\/events$/, - handle: async (context) => { - const optional = [ - 'end', - 'description', - 'location', - 'reminders', - ] as const; - const capacity = field(context.form, 'capacity'); - const event = await services.events.create(context.actor, { - title: field(context.form, 'title') ?? '', - start: field(context.form, 'start') ?? '', - channelId: field(context.form, 'channelId') ?? '', - native: context.form.get('native') === '1', - icons: context.form.get('icons') === '1', - ...(capacity !== undefined && { capacity: Number(capacity) }), - ...Object.fromEntries( - optional.flatMap((name) => { - const value = field(context.form, name); - - return value === undefined ? [] : [[name, value]]; - }), - ), - }); - - return redirect('/events', { notice: `Event #${event.id} created.` }); - }, - }, - { - method: 'POST', - pattern: /^\/events\/(\d+)\/cancel$/, - handle: async (context, [id = '']) => { - await services.events.cancel(context.actor, Number(id)); - - return redirect('/events', { notice: `Event #${id} cancelled.` }); - }, - }, - { - method: 'GET', - pattern: /^\/polls$/, - handle: async (context) => { - const open = await services.polls.open(deps.guildId); - - return { - body: page( - 'Polls', - context.path, - context.flash, - html`
- ${context.csrf} - - - ${channelSelect(context)} - - - - -
-
- - - - - - - - - - - ${open.map( - (p) => - html` - - - - - `, - )} - -
#QuestionCloses
${p.id}${p.question}${date(p.closesAt)} - ${button(context, `/polls/${p.id}/close`, 'Close')} -
`, - ), - }; - }, - }, - { - method: 'POST', - pattern: /^\/polls$/, - handle: async (context) => { - const closes = field(context.form, 'closes'); - const poll = await services.polls.create(context.actor, { - question: field(context.form, 'question') ?? '', - options: (context.form.get('options') ?? '') - .split('\n') - .filter((line) => line.trim() !== ''), - channelId: field(context.form, 'channelId') ?? '', - multiple: context.form.get('multiple') === '1', - anonymous: context.form.get('anonymous') === '1', - showResults: - context.form.get('results') === 'closed' ? 'closed' : 'live', - ...(closes !== undefined && { closes }), - }); - - return redirect('/polls', { notice: `Poll #${poll.id} started.` }); - }, - }, - { - method: 'POST', - pattern: /^\/polls\/(\d+)\/close$/, - handle: async (context, [id = '']) => { - await services.polls.close(context.actor, Number(id)); - - return redirect('/polls', { notice: `Poll #${id} closed.` }); - }, - }, - { - method: 'GET', - pattern: /^\/permissions$/, - handle: async (context) => { - const grants = await services.permissions.list(context.actor); - const roleName = (id: string) => - context.guild.names.roles.get(id) ?? id; - - return { - body: page( - 'Permissions', - context.path, - context.flash, - html`

Discord administrators hold every permission.

-
- ${context.csrf} - - -
- -
-
- - - - - - - - - - ${grants.map( - (g) => - html` - - - - `, - )} - -
RolePermission
@${roleName(g.roleId)}${g.permission} -
- ${context.csrf} -
-
`, - ), - }; - }, - }, - { - method: 'POST', - pattern: /^\/permissions$/, - handle: async (context) => { - const action = - context.form.get('action') === 'revoke' ? 'revoke' : 'grant'; - const permission = field(context.form, 'permission') ?? ''; - const changed = await services.permissions[action]( - context.actor, - field(context.form, 'roleId') ?? '', - permission, - ); - - const verb = action === 'grant' ? 'Granted' : 'Revoked'; - - return redirect('/permissions', { - notice: changed ? `${verb} ${permission}.` : 'Nothing changed.', - }); - }, - }, - ]; - - const readForm = (request: IncomingMessage): Promise
=> - new Promise((resolve, reject) => { - const chunks: Buffer[] = []; - let size = 0; - - request.on('data', (chunk: Buffer) => { - size += chunk.length; - - if (size > maxBodyBytes) { - reject(new UserError('That form is too large.')); - request.destroy(); - } else { - chunks.push(chunk); - } - }); - request.on('end', () => { - resolve(new URLSearchParams(Buffer.concat(chunks).toString('utf8'))); - }); - request.on('error', reject); - }); - - const send = ( - response: ServerResponse, - status: number, - body: string, - headers: Record = {}, - ) => { - response.writeHead(status, { - 'Content-Type': 'text/html; charset=utf-8', - 'Content-Security-Policy': - "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'", - 'X-Content-Type-Options': 'nosniff', - 'Referrer-Policy': 'same-origin', - ...headers, - }); - response.end(body); - }; - - const sameOrigin = (request: IncomingMessage) => { - const origin = request.headers.origin; - - return ( - origin === undefined || new URL(origin).host === request.headers.host - ); - }; - - const findRoute = (method: string, path: string) => - routes - .map((route) => ({ - route, - params: route.method === method ? route.pattern.exec(path) : null, - })) - .find((candidate) => candidate.params !== null); - - const plain = ( - response: ServerResponse, - status: number, - title: string, - body: Html, - ) => { - send(response, status, page(title, '', {}, body).value); - }; - - const actorFor = (request: IncomingMessage) => - deps.auth.authenticate({ - headers: Object.fromEntries( - Object.entries(request.headers).map(([name, value]) => [ - name, - Array.isArray(value) ? value.join(', ') : value, - ]), - ), - }); - - const serve = async ( - request: IncomingMessage, - response: ServerResponse, - url: URL, - ): Promise => { - const method = request.method === 'POST' ? 'POST' : 'GET'; - const match = findRoute(method, url.pathname); - - if (!match?.params) { - plain( - response, - 404, - 'Not found', - html`

Back to the overview

`, - ); - - return; - } - - const actor = await actorFor(request); - - if (!actor) { - plain( - response, - 401, - 'Sign in required', - html`

Sign-in is not set up.

`, - ); - - return; - } - - const form = - method === 'POST' ? await readForm(request) : new URLSearchParams(); - - if ( - method === 'POST' && - (!sameOrigin(request) || form.get('csrf') !== csrfToken) - ) { - plain( - response, - 403, - 'Forbidden', - html`

This form expired. Reload the page and try again.

`, - ); - - return; - } - - const flash: Flash = Object.fromEntries( - ['notice', 'error'].flatMap((key) => { - const value = url.searchParams.get(key); - - return value === null ? [] : [[key, value]]; - }), - ); - const result = await match.route.handle( - { - actor, - form, - path: url.pathname, - flash, - csrf: html``, - guild: await guildData(), - }, - match.params.slice(1), - ); - - if ('redirect' in result) { - send(response, 303, '', { Location: result.redirect }); - } else { - send(response, result.status ?? 200, result.body.value); - } - }; - - return { - handle: async ( - request: IncomingMessage, - response: ServerResponse, - ): Promise => { - const url = new URL(request.url ?? '/', 'http://localhost'); - - try { - await serve(request, response, url); - } catch (error) { - if (error instanceof UserError) { - const section = url.pathname.split('/').slice(0, 2).join('/') || '/'; - - send(response, 303, '', { - Location: location(section, { error: error.message }), - }); - - return; - } - - const ref = randomUUID().slice(0, 8); - - log.error( - { err: error, ref, path: url.pathname }, - 'Web request failed', - ); - plain( - response, - 500, - 'Something went wrong', - html`

Reference: ${ref}

`, - ); - } - }, - }; -} - -export type WebApp = ReturnType; diff --git a/src/infra/web/app.tsx b/src/infra/web/app.tsx new file mode 100644 index 0000000..a756ae5 --- /dev/null +++ b/src/infra/web/app.tsx @@ -0,0 +1,168 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { Hono } from 'hono'; +import { bodyLimit } from 'hono/body-limit'; +import { csrf } from 'hono/csrf'; +import { HTTPException } from 'hono/http-exception'; +import { secureHeaders } from 'hono/secure-headers'; +import { UserError } from '~/domain'; +import { back, type Env, type WebDeps } from './context'; +import { eventPages } from './events'; +import { Layout } from './layout'; +import { permissionPages } from './permissions'; +import { pollPages } from './polls'; +import { psaPages } from './psa'; + +const style = `${readFileSync( + createRequire(import.meta.url).resolve( + '@picocss/pico/css/pico.classless.min.css', + ), + 'utf8', +)} +td form { display: inline-block; margin: 0 .25rem 0 0; } +td button { padding: .25rem .75rem; margin: 0; } +.notice { padding: .5rem .75rem; border-radius: 6px; background: #dafbe1; color: #1a7f37; } +.error { padding: .5rem .75rem; border-radius: 6px; background: #ffebe9; color: #cf222e; } +.discord { background: #313338; color: #dbdee1; padding: .75rem 1rem; border-radius: 8px; margin-bottom: 1rem; } +.discord .h1 { font-size: 1.5rem; font-weight: 700; } +.mention { background: #3c4270; color: #c9cdfb; border-radius: 3px; padding: 0 .15rem; } +`; + +function Message(props: Readonly<{ title: string; text: string }>) { + return ( + +

{props.text}

+

+ Back to the overview +

+
+ ); +} + +export function createWebApp(deps: WebDeps) { + const { guildId, auth, directory, services, log } = deps; + const app = new Hono(); + + app.use( + secureHeaders({ + contentSecurityPolicy: { + defaultSrc: ["'none'"], + styleSrc: ["'self'"], + formAction: ["'self'"], + frameAncestors: ["'none'"], + }, + referrerPolicy: 'same-origin', + }), + ); + app.get('/style.css', (c) => + c.body(style, 200, { 'Content-Type': 'text/css; charset=utf-8' }), + ); + app.use( + bodyLimit({ + maxSize: 64 * 1024, + onError: (c) => + c.html( + , + 413, + ), + }), + ); + app.use(csrf()); + app.use(async (c, next) => { + const actor = await auth.authenticate({ + headers: Object.fromEntries(c.req.raw.headers), + }); + + if (!actor) { + return c.html( + , + 401, + ); + } + + const [channels, roles] = await Promise.all([ + directory.channels(guildId), + directory.roles(guildId), + ]); + const roleNames = new Map(roles.map((role) => [role.id, role.name])); + const channelNames = new Map( + channels.map((channel) => [channel.id, channel.name]), + ); + + c.set('actor', actor); + c.set('guild', { + channels, + roles, + roleName: (id) => roleNames.get(id) ?? 'unknown role', + channelName: (id) => `#${channelNames.get(id) ?? id}`, + }); + + return next(); + }); + + app.get('/', async (c) => { + const [announcements, events, polls] = await Promise.all([ + services.announcements.list(guildId), + services.events.upcoming(guildId), + services.polls.open(guildId), + ]); + const pending = announcements.filter( + (a) => a.status === 'scheduled' || a.status === 'draft', + ); + + return c.html( + + + , + ); + }); + app.route('/psa', psaPages(deps)); + app.route('/events', eventPages(deps)); + app.route('/polls', pollPages(deps)); + app.route('/permissions', permissionPages(deps)); + + app.notFound((c) => + c.html(, 404), + ); + app.onError((error, c) => { + if (error instanceof UserError) { + const section = `/${c.req.path.split('/')[1] ?? ''}`; + + return back(c, section, { error: error.message }); + } + + if (error instanceof HTTPException && error.status === 403) { + return c.html( + , + 403, + ); + } + + const ref = randomUUID().slice(0, 8); + + log.error({ err: error, ref, path: c.req.path }, 'Web request failed'); + + return c.html( + , + 500, + ); + }); + + return app; +} + +export type WebApp = ReturnType; diff --git a/src/infra/web/context.ts b/src/infra/web/context.ts new file mode 100644 index 0000000..e1f942d --- /dev/null +++ b/src/infra/web/context.ts @@ -0,0 +1,81 @@ +import type { Context } from 'hono'; +import type { + Authenticator, + ChannelInfo, + Directory, + Logger, +} from '~/core/ports'; +import type { + AnnouncementService, + EventService, + PermissionService, + PollService, +} from '~/core/services'; +import type { Actor, RoleInfo } from '~/domain'; + +export type WebServices = { + announcements: AnnouncementService; + events: EventService; + polls: PollService; + permissions: PermissionService; +}; + +export type WebDeps = { + guildId: string; + timezone: string; + auth: Authenticator; + directory: Directory; + services: WebServices; + log: Logger; +}; + +export type Guild = { + channels: ChannelInfo[]; + roles: RoleInfo[]; + roleName: (id: string) => string; + channelName: (id: string) => string; +}; + +export type Env = { Variables: { actor: Actor; guild: Guild } }; + +export type Flash = { notice?: string; error?: string }; + +export type Form = FormData; + +export const field = (form: Form, name: string) => { + const value = form.get(name); + const text = typeof value === 'string' ? value.trim() : ''; + + return text === '' ? undefined : text; +}; + +export const checked = (form: Form, name: string) => form.get(name) === '1'; + +export const flashOf = (c: Context): Flash => { + const notice = c.req.query('notice'); + const error = c.req.query('error'); + + return { + ...(notice !== undefined && { notice }), + ...(error !== undefined && { error }), + }; +}; + +export const withFlash = (path: string, flash: Flash) => { + const query = new URLSearchParams(Object.entries(flash)).toString(); + + return query === '' ? path : `${path}?${query}`; +}; + +export const back = (c: Context, path: string, flash: Flash) => + c.redirect(withFlash(path, flash), 303); + +export const formatter = (timezone: string) => { + const format = new Intl.DateTimeFormat('en-GB', { + dateStyle: 'medium', + timeStyle: 'short', + timeZone: timezone, + }); + + return (date: Date | null) => (date === null ? '' : format.format(date)); +}; diff --git a/src/infra/web/events.tsx b/src/infra/web/events.tsx new file mode 100644 index 0000000..b92e786 --- /dev/null +++ b/src/infra/web/events.tsx @@ -0,0 +1,126 @@ +import { Hono } from 'hono'; +import { reminderChoices } from '~/core/services'; +import { + back, + checked, + field, + flashOf, + formatter, + type Env, + type WebDeps, +} from './context'; +import { ActionButton, ChannelSelect, Checkbox, Layout } from './layout'; + +const optional = ['end', 'description', 'location', 'reminders'] as const; + +export function eventPages({ guildId, services, timezone }: WebDeps) { + const date = formatter(timezone); + + return new Hono() + .get('/', async (c) => { + const upcoming = await services.events.upcoming(guildId); + const { guild } = c.var; + + return c.html( + + + +
+ + +
+ + + + {props.preview} +
+ + + + +
+ + ); +} + +function Recent( + props: Readonly<{ + list: Announcement[]; + guild: Guild; + date: (value: Date | null) => string; + }>, +) { + return ( + + + + + + + + + + + + {props.list.map((a) => ( + + + + + + + + + ))} + +
#StatusChannelTitleWhen +
{a.id} + {a.status} + {a.failure === null ? null : ( + <> +
+ {a.failure} + + )} +
{props.guild.channelName(a.channelId)}{a.title ?? a.content.slice(0, 60)}{props.date(a.publishedAt ?? a.scheduledAt)} + {a.status === 'draft' || a.status === 'scheduled' ? ( + <> + + + + ) : null} +
+ ); +} + +export function psaPages({ guildId, services, timezone }: WebDeps) { + const date = formatter(timezone); + + return new Hono() + .get('/', async (c) => { + const list = await services.announcements.list(guildId); + + return c.html( + + +

Recent

+ +
, + ); + }) + .post('/', async (c) => { + const form = await c.req.formData(); + const action = form.get('action'); + const draft = draftOf(form); + const { actor, guild } = c.var; + + if (action === 'preview') { + const view = services.announcements.view({ + ...draft, + title: draft.title === '' ? null : draft.title, + id: 0, + guildId, + authorId: actor.userId, + status: 'draft', + scheduledAt: null, + publishedAt: null, + messageId: null, + failure: null, + createdAt: new Date(), + }); + + return c.html( + + +

Preview

+ + + } + /> +
, + ); + } + + const created = await services.announcements.draft(actor, draft); + + if (action === 'publish') { + await services.announcements.publish(actor, created.id); + + return back(c, '/psa', { notice: `PSA #${created.id} published.` }); + } + + if (action === 'schedule') { + const scheduled = await services.announcements.schedule( + actor, + created.id, + field(form, 'when') ?? '', + ); + + return back(c, '/psa', { + notice: `PSA #${created.id} scheduled for ${date(scheduled.scheduledAt)}.`, + }); + } + + return back(c, '/psa', { notice: `Draft #${created.id} saved.` }); + }) + .post('/:id{[0-9]+}/:action{publish|cancel}', async (c) => { + const id = Number(c.req.param('id')); + const publish = c.req.param('action') === 'publish'; + + await (publish + ? services.announcements.publish(c.var.actor, id) + : services.announcements.cancel(c.var.actor, id)); + + return back(c, '/psa', { + notice: `PSA #${id} ${publish ? 'published' : 'cancelled'}.`, + }); + }); +} diff --git a/src/infra/web/server.ts b/src/infra/web/server.ts index 899097a..74d16e7 100644 --- a/src/infra/web/server.ts +++ b/src/infra/web/server.ts @@ -1,4 +1,4 @@ -import { createServer } from 'node:http'; +import { serve } from '@hono/node-server'; import type { Logger } from '~/core/ports'; import type { WebApp } from './app'; @@ -6,17 +6,19 @@ export async function startWebServer( app: WebApp, options: { port: number; host: string; log: Logger }, ): Promise<() => Promise> { - const server = createServer((request, response) => { - app.handle(request, response).catch((error: unknown) => { - options.log.error({ err: error }, 'Web handler crashed'); - response.destroy(); - }); - }); + const server = await new Promise>( + (resolve, reject) => { + const started = serve( + { fetch: app.fetch, port: options.port, hostname: options.host }, + () => { + resolve(started); + }, + ); + + started.once('error', reject); + }, + ); - await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(options.port, options.host, resolve); - }); options.log.info( { host: options.host, port: options.port }, 'Web UI listening', @@ -31,6 +33,5 @@ export async function startWebServer( resolve(); } }); - server.closeAllConnections(); }); } diff --git a/src/lib/html.ts b/src/lib/html.ts deleted file mode 100644 index bce17eb..0000000 --- a/src/lib/html.ts +++ /dev/null @@ -1,51 +0,0 @@ -const marker = Symbol('html'); - -export type Html = { readonly [marker]: true; readonly value: string }; - -const escapes: Record = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', -}; - -export const escapeHtml = (text: string) => - text.replaceAll(/[&<>"']/g, (character) => escapes[character] ?? character); - -export const raw = (value: string): Html => ({ [marker]: true, value }); - -const isHtml = (value: unknown): value is Html => - typeof value === 'object' && value !== null && marker in value; - -type Value = - Html | string | number | boolean | null | undefined | readonly Value[]; - -const isList = (value: Value): value is readonly Value[] => - Array.isArray(value); - -function render(value: Value): string { - if (isList(value)) { - return value.map((item) => render(item)).join(''); - } - - if (isHtml(value)) { - return value.value; - } - - if (value === null || value === undefined || value === false) { - return ''; - } - - return escapeHtml(String(value)); -} - -export function html(strings: TemplateStringsArray, ...values: Value[]): Html { - return raw( - strings.reduce( - (out, part, index) => - out + part + (index < values.length ? render(values[index]) : ''), - '', - ), - ); -} diff --git a/src/lib/index.ts b/src/lib/index.ts index a9f221e..780df27 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -1,2 +1 @@ export * from './async'; -export * from './html'; diff --git a/tests/infra/web/app.test.ts b/tests/infra/web/app.test.ts index 3cc57fe..4877583 100644 --- a/tests/infra/web/app.test.ts +++ b/tests/infra/web/app.test.ts @@ -1,6 +1,4 @@ -import { createServer, type Server } from 'node:http'; -import type { AddressInfo } from 'node:net'; -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { beforeAll, describe, expect, it, vi } from 'vitest'; import type { Scheduler } from '~/core/ports'; import { createAnnouncementService, @@ -16,7 +14,7 @@ import { createPollRepository, } from '~/infra/db'; import type { Permission, PermissionDefinition } from '~/domain'; -import { createWebApp, localOperator } from '~/infra/web'; +import { createWebApp, localOperator, type WebApp } from '~/infra/web'; import { noDatabase, snowflake, testDb } from '../../db'; import { actor, @@ -32,8 +30,7 @@ describe.skipIf(noDatabase)('web UI', () => { const guildId = snowflake(); const { messenger } = fakeMessenger(); const directory = fakeDirectory([role({ id: teamId, name: 'Team' })]); - let server: Server; - let base = ''; + let app: WebApp; directory.channels.mockResolvedValue([ { id: 'general', name: 'general', kind: 'text' }, @@ -54,8 +51,10 @@ describe.skipIf(noDatabase)('web UI', () => { log: silentLog, timezone: 'Europe/Tallinn', }; - const app = createWebApp({ + + app = createWebApp({ guildId, + timezone: 'Europe/Tallinn', auth: localOperator(async () => actor({ guildId, administrator: true })), directory, log: silentLog, @@ -89,32 +88,15 @@ describe.skipIf(noDatabase)('web UI', () => { }), }, }); - - server = createServer( - (request, response) => void app.handle(request, response), - ); - await new Promise((resolve) => { - server.listen(0, '127.0.0.1', resolve); - }); - base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); - afterAll( - () => - new Promise((resolve) => { - server.close(() => { - resolve(); - }); - }), - ); - - const csrf = async (path: string) => { - const page = await (await fetch(`${base}${path}`)).text(); - - return /name="csrf" value="([0-9a-f]+)"/.exec(page)?.[1] ?? ''; - }; + const get = (path: string) => app.request(`http://localhost${path}`); - const post = (path: string, fields: Record) => { + const post = ( + path: string, + fields: Record, + origin = 'http://localhost', + ) => { const body = new URLSearchParams(); for (const [name, value] of Object.entries(fields)) { @@ -123,15 +105,15 @@ describe.skipIf(noDatabase)('web UI', () => { } } - return fetch(`${base}${path}`, { + return app.request(`http://localhost${path}`, { method: 'POST', body, - redirect: 'manual', + headers: { Origin: origin }, }); }; it('renders the PSA composer with channels and mentionable roles', async () => { - const response = await fetch(`${base}/psa`); + const response = await get('/psa'); const page = await response.text(); expect(response.status).toBe(200); @@ -142,12 +124,19 @@ describe.skipIf(noDatabase)('web UI', () => { ); }); - it('rejects forms without the CSRF token', async () => { - const response = await post('/psa', { - channelId: 'general', - content: 'x', - action: 'publish', - }); + it('serves the stylesheet the pages link to', async () => { + const response = await get('/style.css'); + + expect(response.headers.get('content-type')).toContain('text/css'); + expect(await response.text()).toContain('.discord'); + }); + + it('rejects forms posted from another site', async () => { + const response = await post( + '/psa', + { channelId: 'general', content: 'x', action: 'publish' }, + 'https://evil.example', + ); expect(response.status).toBe(403); expect(messenger.send).not.toHaveBeenCalled(); @@ -155,7 +144,6 @@ describe.skipIf(noDatabase)('web UI', () => { it('previews without posting, escaping user text', async () => { const response = await post('/psa', { - csrf: await csrf('/psa'), channelId: 'general', title: 'Hi', content: `Meeting <@&${teamId}> **now**`, @@ -171,7 +159,6 @@ describe.skipIf(noDatabase)('web UI', () => { it('publishes a PSA with the chosen role mentions', async () => { const response = await post('/psa', { - csrf: await csrf('/psa'), channelId: 'general', title: 'Hackathon', content: 'Sign up today', @@ -192,7 +179,6 @@ describe.skipIf(noDatabase)('web UI', () => { it('shows service errors as a message instead of failing', async () => { const response = await post('/psa', { - csrf: await csrf('/psa'), channelId: 'general', content: ' ', action: 'draft', @@ -206,7 +192,6 @@ describe.skipIf(noDatabase)('web UI', () => { it('creates polls', async () => { const poll = await post('/polls', { - csrf: await csrf('/polls'), question: 'Lunch?', options: 'Pizza\nSushi', channelId: 'general', @@ -216,6 +201,6 @@ describe.skipIf(noDatabase)('web UI', () => { }); it('returns 404 for unknown pages', async () => { - expect((await fetch(`${base}/nope`)).status).toBe(404); + expect((await get('/nope')).status).toBe(404); }); }); diff --git a/tests/lib/html.test.ts b/tests/lib/html.test.ts deleted file mode 100644 index 7e02ba0..0000000 --- a/tests/lib/html.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { html, raw } from '~/lib'; - -describe('html', () => { - it('escapes interpolated values but not nested html', () => { - const name = ''; - - expect(html`

${name}

`.value).toBe( - '

<script>"x"</script>

', - ); - const inner = html`${'a&b'}`; - - expect(html`
${inner}
`.value).toBe('
a&b
'); - expect(html`${[raw(''), 'x', null, false]}`.value).toBe('x'); - }); -}); diff --git a/tsconfig.json b/tsconfig.json index f0a6744..0e8cc90 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,8 @@ "module": "ESNext", "moduleResolution": "bundler", "types": ["node"], + "jsx": "react-jsx", + "jsxImportSource": "hono/jsx", "strict": true, "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, From 28cb195b5a910623cede12e73f804a79f4f8063f Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 13:17:27 +0200 Subject: [PATCH 058/199] refactor(web): real stylesheet, Pico from the CDN, keyed lists and typed buttons --- Dockerfile | 1 + README.md | 4 +- eslint.config.ts | 12 + package.json | 2 +- pnpm-lock.yaml | 1258 ++++++++++++++++++++++++++++++++- public/app.css | 45 ++ src/infra/web/app.tsx | 43 +- src/infra/web/context.ts | 16 + src/infra/web/events.tsx | 6 +- src/infra/web/layout.tsx | 92 +-- src/infra/web/permissions.tsx | 12 +- src/infra/web/polls.tsx | 2 +- src/infra/web/preview.tsx | 103 +-- src/infra/web/psa.tsx | 88 +-- tests/infra/web/app.test.ts | 2 +- 15 files changed, 1498 insertions(+), 188 deletions(-) create mode 100644 public/app.css diff --git a/Dockerfile b/Dockerfile index 7bd290f..a661311 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,6 +18,7 @@ WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY --from=build /app/dist ./dist COPY drizzle ./drizzle +COPY public ./public COPY package.json ./ USER node CMD ["node", "--enable-source-maps", "dist/index.mjs"] diff --git a/README.md b/README.md index 6f13e18..05faaf7 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,9 @@ it on the host's loopback). Reach it from elsewhere through an SSH tunnel, not a public proxy. Sign-in plugs in through the `Authenticator` port. The pages are server-rendered [Hono](https://hono.dev) JSX styled by -[Pico.css](https://picocss.com) (classless, so plain form markup looks right). +[Pico.css](https://picocss.com) (classless, so plain form markup looks right), +loaded from jsDelivr. Our own styles are in `public/app.css`; every file in +`public/` is served as is. Each section is one file in `src/infra/web/` that returns a small Hono app; to add a page, write one and mount it with `app.route()` in `app.tsx`. Forms post back to the same path, so there is no client-side JavaScript. diff --git a/eslint.config.ts b/eslint.config.ts index 99d8299..264abbe 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -2,6 +2,7 @@ import js from '@eslint/js'; import type { Linter } from 'eslint'; import { defineConfig, globalIgnores } from 'eslint/config'; import tseslint from 'typescript-eslint'; +import react from 'eslint-plugin-react'; import { configs as sonarConfigs } from 'eslint-plugin-sonarjs'; import unicorn from 'eslint-plugin-unicorn'; import prettier from 'eslint-config-prettier'; @@ -176,6 +177,17 @@ export default defineConfig( rules: unicornRules, }, + { + files: ['**/*.tsx'], + plugins: { react }, + settings: { react: { version: '19' } }, + rules: { + 'react/jsx-key': ['error', { checkFragmentShorthand: true }], + 'react/no-array-index-key': 'error', + 'react/button-has-type': 'error', + }, + }, + { files: javascriptFiles, languageOptions: { diff --git a/package.json b/package.json index 627f4f0..bcaa0c0 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,6 @@ "dependencies": { "@date-fns/tz": "^1.5.0", "@hono/node-server": "^2.1.8", - "@picocss/pico": "^2.1.1", "date-fns": "^4.4.0", "discord.js": "^14.28.1", "drizzle-orm": "^0.45.4", @@ -46,6 +45,7 @@ "eslint-config-prettier": "^10.1.8", "eslint-import-resolver-typescript": "^4.4.5", "eslint-plugin-import-x": "^4.18.1", + "eslint-plugin-react": "^7.37.5", "eslint-plugin-sonarjs": "^4.2.2", "eslint-plugin-unicorn": "^79.0.0", "globals": "^17.14.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 02254a1..4e0c0f4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,9 +14,6 @@ importers: '@hono/node-server': specifier: ^2.1.8 version: 2.1.8(hono@4.13.18) - '@picocss/pico': - specifier: ^2.1.1 - version: 2.1.1 date-fns: specifier: ^4.4.0 version: 4.4.0 @@ -69,6 +66,9 @@ importers: eslint-plugin-import-x: specifier: ^4.18.1 version: 4.18.1(@typescript-eslint/utils@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0)) + eslint-plugin-react: + specifier: ^7.37.5 + version: 7.37.5(eslint@10.15.0(jiti@2.7.0)) eslint-plugin-sonarjs: specifier: ^4.2.2 version: 4.2.2(eslint@10.15.0(jiti@2.7.0)) @@ -714,9 +714,6 @@ packages: '@oxc-project/types@0.158.0': resolution: {integrity: sha512-xZ66qA4WmLbTLlxH3mqMd8f9UKbaOzOT0ATwFf4DH/14pMgpUrtqtjyYzOQmgfl2a0iRAAMbQ9G1th/67jRzGw==} - '@picocss/pico@2.1.1': - resolution: {integrity: sha512-kIDugA7Ps4U+2BHxiNHmvgPIQDWPDU4IeU6TNRdvXQM1uZX+FibqDQT2xUOnnO2yq/LUHcwnGlu1hvf4KfXnMg==} - '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -1226,14 +1223,53 @@ packages: ajv@6.15.0: resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + array-buffer-byte-length@1.0.2: + resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} + engines: {node: '>= 0.4'} + + array-includes@3.2.0: + resolution: {integrity: sha512-VXY5eFRarnXcYxwBjJzPmEhH55+rmP79/+ueDhi0F+TuqfHCItagIHqxeUZrmgrOPa31QTh9H85DjX3FfJ0FTg==} + engines: {node: '>= 0.4'} + + array.prototype.findlast@1.2.5: + resolution: {integrity: sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==} + engines: {node: '>= 0.4'} + + array.prototype.flat@1.3.3: + resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==} + engines: {node: '>= 0.4'} + + array.prototype.flatmap@1.3.3: + resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==} + engines: {node: '>= 0.4'} + + array.prototype.tosorted@1.1.4: + resolution: {integrity: sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==} + engines: {node: '>= 0.4'} + + arraybuffer.prototype.slice@1.0.4: + resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} + engines: {node: '>= 0.4'} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} + async-function@1.0.0: + resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} + engines: {node: '>= 0.4'} + atomic-sleep@1.0.0: resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} engines: {node: '>=8.0.0'} + available-typed-arrays@1.0.7: + resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} + engines: {node: '>= 0.4'} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -1243,6 +1279,9 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + brace-expansion@1.1.22: + resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==} + brace-expansion@5.0.13: resolution: {integrity: sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==} engines: {node: 20 || >=22} @@ -1274,6 +1313,18 @@ packages: cacheable@2.5.0: resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + call-bind@1.0.9: + resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==} + engines: {node: '>= 0.4'} + + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + caniuse-lite@1.0.30001826: resolution: {integrity: sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==} @@ -1301,6 +1352,9 @@ packages: resolution: {integrity: sha512-+2AvZKjJaNq9GQljm3tr0utwrig5BL+jgJGvz5rDpGKNIp+ojcRXWUwBbh/sGIi1QCprR6PsKFakub+w1v+4hQ==} engines: {node: '>= 12.0.0'} + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + core-js-compat@3.51.0: resolution: {integrity: sha512-52r6fkXgxv4GLMjmFcMWRx7X9bw071xTTdrDcdyPGRqU2oE+9pCG0bAOMifSBdLw0JRBZKEF0q3B55qPlLuE8g==} engines: {node: '>=6.4.0'} @@ -1313,6 +1367,18 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + data-view-buffer@1.0.2: + resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} + engines: {node: '>= 0.4'} + + data-view-byte-length@1.0.2: + resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==} + engines: {node: '>= 0.4'} + + data-view-byte-offset@1.0.1: + resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} + engines: {node: '>= 0.4'} + date-fns@4.4.0: resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==} @@ -1334,6 +1400,14 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + defu@6.1.7: resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} @@ -1359,6 +1433,10 @@ packages: resolution: {integrity: sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==} engines: {node: '>=18'} + doctrine@2.1.0: + resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} + engines: {node: '>=0.10.0'} + drizzle-kit@0.31.11: resolution: {integrity: sha512-YCYqxTLIB2OCqf6w9/Vef13baBVbwQIPcbT4Y56AfO6B9ajZhDhD8Jkveg/hJvT/iuMloKD/IYYkyMMNhr7Kqg==} hasBin: true @@ -1467,6 +1545,10 @@ packages: oxc-resolver: optional: true + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + electron-to-chromium@1.5.485: resolution: {integrity: sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw==} @@ -1485,12 +1567,48 @@ packages: resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} engines: {node: '>=20.19.0'} + es-abstract-get@1.0.0: + resolution: {integrity: sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==} + engines: {node: '>= 0.4'} + + es-abstract@1.24.2: + resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==} + engines: {node: '>= 0.4'} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-iterator-helpers@1.4.0: + resolution: {integrity: sha512-c/A0P0oxkACDc+cKWw8evLXK83oBKgn0qPOqCYT4x9uolpCIJAcYvJC9QYKNDRPsTeGyCrQ326jrvgZWdCdK5Q==} + engines: {node: '>= 0.4'} + es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} es-module-lexer@3.0.4: resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==} + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + es-shim-unscopables@1.1.0: + resolution: {integrity: sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==} + engines: {node: '>= 0.4'} + + es-to-primitive@1.3.4: + resolution: {integrity: sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==} + engines: {node: '>= 0.4'} + esbuild@0.18.20: resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==} engines: {node: '>=12'} @@ -1555,6 +1673,12 @@ packages: eslint-import-resolver-node: optional: true + eslint-plugin-react@7.37.5: + resolution: {integrity: sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==} + engines: {node: '>=4'} + peerDependencies: + eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7 + eslint-plugin-sonarjs@4.2.2: resolution: {integrity: sha512-usNF9GfP89ibwhfxpZaCMW40sC7UEOusDgDCk7lyqAhh4AYdbBaAgLVL5Y/QS0jSed8eJ2ACGH6zzE8ezd/yZQ==} peerDependencies: @@ -1660,14 +1784,44 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + for-each@0.3.5: + resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} + engines: {node: '>= 0.4'} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + function.prototype.name@1.2.0: + resolution: {integrity: sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==} + engines: {node: '>= 0.4'} + functional-red-black-tree@1.0.1: resolution: {integrity: sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==} + functions-have-names@1.2.3: + resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} + + generator-function@2.0.1: + resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} + engines: {node: '>= 0.4'} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + get-symbol-description@1.1.0: + resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} + engines: {node: '>= 0.4'} + get-tsconfig@4.14.3: resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==} @@ -1683,10 +1837,41 @@ packages: resolution: {integrity: sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==} engines: {node: '>=18'} + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + has-bigints@1.1.0: + resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} + engines: {node: '>= 0.4'} + + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + + has-proto@1.2.0: + resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==} + engines: {node: '>= 0.4'} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + hashery@1.5.1: resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} engines: {node: '>=20'} + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + help-me@5.0.0: resolution: {integrity: sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==} @@ -1727,6 +1912,26 @@ packages: resolution: {integrity: sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==} engines: {node: '>=12'} + internal-slot@1.1.0: + resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} + engines: {node: '>= 0.4'} + + is-array-buffer@3.0.5: + resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==} + engines: {node: '>= 0.4'} + + is-async-function@2.1.1: + resolution: {integrity: sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==} + engines: {node: '>= 0.4'} + + is-bigint@1.1.0: + resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} + engines: {node: '>= 0.4'} + + is-boolean-object@1.2.2: + resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==} + engines: {node: '>= 0.4'} + is-builtin-module@5.0.0: resolution: {integrity: sha512-f4RqJKBUe5rQkJ2eJEJBXSticB3hGbN9j0yxxMQFqIW89Jp9WYFtzfTcRlstDKVUTRzSOTLKRfO9vIztenwtxA==} engines: {node: '>=18.20'} @@ -1734,17 +1939,100 @@ packages: is-bun-module@2.0.0: resolution: {integrity: sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==} + is-callable@1.2.7: + resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} + engines: {node: '>= 0.4'} + + is-core-module@2.18.0: + resolution: {integrity: sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==} + engines: {node: '>= 0.4'} + + is-data-view@1.0.2: + resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==} + engines: {node: '>= 0.4'} + + is-date-object@1.1.0: + resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==} + engines: {node: '>= 0.4'} + + is-document.all@1.0.0: + resolution: {integrity: sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==} + engines: {node: '>= 0.4'} + is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} + is-finalizationregistry@1.1.1: + resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} + engines: {node: '>= 0.4'} + + is-generator-function@1.1.2: + resolution: {integrity: sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==} + engines: {node: '>= 0.4'} + is-glob@4.0.3: resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} engines: {node: '>=0.10.0'} + is-map@2.0.3: + resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==} + engines: {node: '>= 0.4'} + + is-negative-zero@2.0.3: + resolution: {integrity: sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==} + engines: {node: '>= 0.4'} + + is-number-object@1.1.1: + resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==} + engines: {node: '>= 0.4'} + + is-regex@1.2.1: + resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} + engines: {node: '>= 0.4'} + + is-set@2.0.3: + resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} + engines: {node: '>= 0.4'} + + is-shared-array-buffer@1.0.4: + resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==} + engines: {node: '>= 0.4'} + + is-string@1.1.1: + resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==} + engines: {node: '>= 0.4'} + + is-symbol@1.1.1: + resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==} + engines: {node: '>= 0.4'} + + is-typed-array@1.1.15: + resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} + engines: {node: '>= 0.4'} + + is-weakmap@2.0.2: + resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} + engines: {node: '>= 0.4'} + + is-weakref@1.1.1: + resolution: {integrity: sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==} + engines: {node: '>= 0.4'} + + is-weakset@2.0.4: + resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==} + engines: {node: '>= 0.4'} + + isarray@2.0.5: + resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} + isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + iterator.prototype@1.1.5: + resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==} + engines: {node: '>= 0.4'} + jiti@2.7.0: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true @@ -1753,6 +2041,9 @@ packages: resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} engines: {node: '>=10'} + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} @@ -1768,6 +2059,10 @@ packages: resolution: {integrity: sha512-eQQBjBnsVtGacsG9uJNB8qOr3yA8rga4wAaGG1qRcBzSIvfhERLrWxMAM1hp5fcS6Abo8M4+bUBTekYR0qTPQw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + jsx-ast-utils@3.3.5: + resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==} + engines: {node: '>=4.0'} + keyv@5.6.0: resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} @@ -1862,6 +2157,10 @@ packages: lodash@4.18.1: resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + luxon@3.7.2: resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} engines: {node: '>=12'} @@ -1872,6 +2171,10 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + mdn-data@2.37.2: resolution: {integrity: sha512-rz9YOBGItdSbe7HcSArUbhiAv4SB/4DKRYg96CSFS2CcIYMbUvBtZlzA1NCbk2AdgbmYwMqwNblLpR441lLeiQ==} @@ -1946,6 +2249,9 @@ packages: resolution: {integrity: sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==} engines: {node: 20 || >=22} + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} @@ -1965,6 +2271,10 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + node-exports-info@1.6.2: + resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==} + engines: {node: '>= 0.4'} + node-releases@2.0.64: resolution: {integrity: sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==} engines: {node: '>=18'} @@ -1973,6 +2283,34 @@ packages: resolution: {integrity: sha512-TMB1uHiGsHRGv1uYclfhivcnf0/PdFp2pNqRxXjncaAsjYMoisaQJI+SSZCqRq+VliwRTC8tsMQfmrWjDMhkPQ==} engines: {node: '>=20'} + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + object-inspect@1.13.4: + resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} + engines: {node: '>= 0.4'} + + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + + object.assign@4.1.7: + resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==} + engines: {node: '>= 0.4'} + + object.entries@1.1.9: + resolution: {integrity: sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==} + engines: {node: '>= 0.4'} + + object.fromentries@2.0.8: + resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==} + engines: {node: '>= 0.4'} + + object.values@1.2.1: + resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} + engines: {node: '>= 0.4'} + obug@3.0.0: resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} @@ -1988,6 +2326,10 @@ packages: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} + own-keys@1.0.2: + resolution: {integrity: sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==} + engines: {node: '>= 0.4'} + p-limit@3.1.0: resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} engines: {node: '>=10'} @@ -2007,6 +2349,9 @@ packages: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + pg-boss@12.38.2: resolution: {integrity: sha512-nvB9hB2cDJGSPUwYjN/Mth+EE3zvxffkp7uKXIiYloMAaxSoEiutmZi9mpSW85hNCcPChf3yicNXdwhIWkv2nA==} engines: {node: '>=22.12.0'} @@ -2073,6 +2418,10 @@ packages: resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==} engines: {node: '>=4'} + possible-typed-array-names@1.1.0: + resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} + engines: {node: '>= 0.4'} + postcss@8.5.33: resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} engines: {node: ^10 || ^12 || >=14} @@ -2109,6 +2458,9 @@ packages: process-warning@5.1.1: resolution: {integrity: sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==} + prop-types@15.8.1: + resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} + pump@3.0.4: resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} @@ -2130,6 +2482,9 @@ packages: resolution: {integrity: sha512-Y3NoRtprEEZQD8RfxMCfS0ZTqc4e+i18OrXEXAvpM6TfC/3y+0L5rNbZiSnbBBEkDfFzbpd8o+cE8q3/anjMGA==} engines: {node: '>=22'} + react-is@16.13.1: + resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} + real-require@1.0.0: resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==} @@ -2137,10 +2492,18 @@ packages: resolution: {integrity: sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + reflect.getprototypeof@1.0.10: + resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} + engines: {node: '>= 0.4'} + regexp-ast-analysis@0.7.1: resolution: {integrity: sha512-sZuz1dYW/ZsfG17WSAG7eS85r5a0dDsvg+7BiiYR5o6lKCAtUrEwdmRmaGF6rwVj3LcmAeYkOWKEPlbPzN3Y3A==} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + regexp.prototype.flags@1.5.4: + resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} + engines: {node: '>= 0.4'} + regjsparser@0.13.4: resolution: {integrity: sha512-EWV80YgFaVgFrjGCAsV7oybp4GOxbls5RzBg8OB0nKEVXsBJR1JlV8Di1JhCROg3MzTfe1RI8yitIm1eOs68iA==} hasBin: true @@ -2152,6 +2515,11 @@ packages: resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + resolve@2.0.0-next.7: + resolution: {integrity: sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==} + engines: {node: '>= 0.4'} + hasBin: true + rolldown-plugin-dts@0.30.2: resolution: {integrity: sha512-Q3wRlwawifZeN1llb1BaeZfimmJMF/WHzm7z5ieZ8g2CWHQM0gvVWLYPbgBglsXJqcd405gc+3LS2NzSevbYNQ==} engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} @@ -2187,6 +2555,18 @@ packages: rrule-temporal@2.2.9: resolution: {integrity: sha512-5Bc+IxlGKZtOF/JtkM+39VtK9uYvg1NRWGzZCy2QQj9KFZ4mMMa949GMtGv0Ud/bzyk2KuGhwxmVDuq8cnbzuA==} + safe-array-concat@1.1.4: + resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} + engines: {node: '>=0.4'} + + safe-push-apply@1.0.0: + resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==} + engines: {node: '>= 0.4'} + + safe-regex-test@1.1.0: + resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} + engines: {node: '>= 0.4'} + safe-stable-stringify@2.5.0: resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} engines: {node: '>=10'} @@ -2198,6 +2578,10 @@ packages: secure-json-parse@4.1.1: resolution: {integrity: sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==} + semver@6.3.2: + resolution: {integrity: sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==} + hasBin: true + semver@7.8.6: resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} @@ -2207,6 +2591,18 @@ packages: resolution: {integrity: sha512-FT1EL2Pz7lAWA48I6Qb1qHEvGT9ZGz2pb1sYZ9Dhu2t+RmHN6O12WMu7HzFcqFRQaUWEl3Q+++EYBTrZpCoykQ==} engines: {node: '>=20'} + set-function-length@1.2.2: + resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} + engines: {node: '>= 0.4'} + + set-function-name@2.0.2: + resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} + engines: {node: '>= 0.4'} + + set-proto@1.0.0: + resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} + engines: {node: '>= 0.4'} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -2215,6 +2611,22 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} + engines: {node: '>= 0.4'} + + side-channel-map@1.0.1: + resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} + engines: {node: '>= 0.4'} + + side-channel-weakmap@1.0.2: + resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} + engines: {node: '>= 0.4'} + + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + sonic-boom@4.2.1: resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} @@ -2243,6 +2655,29 @@ packages: std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + stop-iteration-iterator@1.1.0: + resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} + engines: {node: '>= 0.4'} + + string.prototype.matchall@4.1.0: + resolution: {integrity: sha512-tHNHTxInrYLCga9O9YGxWA3G9/nnzQw8UGAyqGx3Ar1pSTTzIuM4woFSq4SowkXCjJIwq5sIiQvEfRI9tCH1qQ==} + engines: {node: '>= 0.4'} + + string.prototype.repeat@1.0.0: + resolution: {integrity: sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==} + + string.prototype.trim@1.2.11: + resolution: {integrity: sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==} + engines: {node: '>= 0.4'} + + string.prototype.trimend@1.0.10: + resolution: {integrity: sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==} + engines: {node: '>= 0.4'} + + string.prototype.trimstart@1.0.8: + resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} + engines: {node: '>= 0.4'} + strip-indent@4.1.1: resolution: {integrity: sha512-SlyRoSkdh1dYP0PzclLE7r0M9sgbFKKMFXpFRUMNuKhQSbC6VQIGzq3E0qsfvGJaUFJPGv6Ws1NZ/haTAjfbMA==} engines: {node: '>=12'} @@ -2251,6 +2686,10 @@ packages: resolution: {integrity: sha512-ErcwpJBYr8EfX/Br7JauOIGXoRE92w0hVtuS9j92UFgbATxA+WRSIZksSUDzEeItfWB/0QCEprTZT55RSINUHQ==} engines: {node: '>=22'} + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + tagged-tag@1.0.0: resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} engines: {node: '>=20'} @@ -2336,6 +2775,22 @@ packages: resolution: {integrity: sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==} engines: {node: '>=20'} + typed-array-buffer@1.0.3: + resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} + engines: {node: '>= 0.4'} + + typed-array-byte-length@1.0.3: + resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==} + engines: {node: '>= 0.4'} + + typed-array-byte-offset@1.0.5: + resolution: {integrity: sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==} + engines: {node: '>= 0.4'} + + typed-array-length@1.0.8: + resolution: {integrity: sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==} + engines: {node: '>= 0.4'} + typescript-eslint@8.72.2: resolution: {integrity: sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2348,6 +2803,10 @@ packages: engines: {node: '>=14.17'} hasBin: true + unbox-primitive@1.1.0: + resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} + engines: {node: '>= 0.4'} + unconfig-core@7.5.0: resolution: {integrity: sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==} @@ -2461,6 +2920,22 @@ packages: jsdom: optional: true + which-boxed-primitive@1.1.1: + resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} + engines: {node: '>= 0.4'} + + which-builtin-type@1.2.1: + resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==} + engines: {node: '>= 0.4'} + + which-collection@1.0.2: + resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} + engines: {node: '>= 0.4'} + + which-typed-array@1.1.24: + resolution: {integrity: sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==} + engines: {node: '>= 0.4'} + which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} @@ -2921,8 +3396,6 @@ snapshots: '@oxc-project/types@0.158.0': {} - '@picocss/pico@2.1.1': {} - '@pinojs/redact@0.4.0': {} '@quansync/fs@1.1.0': @@ -3292,14 +3765,84 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 + array-buffer-byte-length@1.0.2: + dependencies: + call-bound: 1.0.4 + is-array-buffer: 3.0.5 + + array-includes@3.2.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + es-shim-unscopables: 1.1.0 + is-string: 1.1.1 + math-intrinsics: 1.1.0 + + array.prototype.findlast@1.2.5: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + es-shim-unscopables: 1.1.0 + + array.prototype.flat@1.3.3: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-shim-unscopables: 1.1.0 + + array.prototype.flatmap@1.3.3: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-shim-unscopables: 1.1.0 + + array.prototype.tosorted@1.1.4: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-shim-unscopables: 1.1.0 + + arraybuffer.prototype.slice@1.0.4: + dependencies: + array-buffer-byte-length: 1.0.2 + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + is-array-buffer: 3.0.5 + assertion-error@2.0.1: {} + async-function@1.0.0: {} + atomic-sleep@1.0.0: {} + available-typed-arrays@1.0.7: + dependencies: + possible-typed-array-names: 1.1.0 + + balanced-match@1.0.2: {} + balanced-match@4.0.4: {} baseline-browser-mapping@2.11.37: {} + brace-expansion@1.1.22: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + brace-expansion@5.0.13: dependencies: balanced-match: 4.0.4 @@ -3330,6 +3873,23 @@ snapshots: keyv: 5.6.0 qified: 0.10.1 + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + call-bind@1.0.9: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + get-intrinsic: 1.3.0 + set-function-length: 1.2.2 + + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + caniuse-lite@1.0.30001826: {} chai@6.3.0: {} @@ -3346,6 +3906,8 @@ snapshots: comment-parser@1.4.9: {} + concat-map@0.0.1: {} + core-js-compat@3.51.0: dependencies: browserslist: 4.29.5 @@ -3360,6 +3922,24 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 + data-view-buffer@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + data-view-byte-length@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + data-view-byte-offset@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + date-fns@4.4.0: {} dateformat@4.6.3: {} @@ -3374,6 +3954,18 @@ snapshots: deep-is@0.1.4: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + defu@6.1.7: {} dequal@2.0.3: {} @@ -3407,6 +3999,10 @@ snapshots: - bufferutil - utf-8-validate + doctrine@2.1.0: + dependencies: + esutils: 2.0.3 + drizzle-kit@0.31.11: dependencies: '@drizzle-team/brocli': 0.10.2 @@ -3422,6 +4018,12 @@ snapshots: dts-resolver@3.0.0: {} + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + electron-to-chromium@1.5.485: {} empathic@2.1.0: {} @@ -3434,10 +4036,121 @@ snapshots: entities@9.0.0: {} + es-abstract-get@1.0.0: + dependencies: + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + is-callable: 1.2.7 + object-inspect: 1.13.4 + + es-abstract@1.24.2: + dependencies: + array-buffer-byte-length: 1.0.2 + arraybuffer.prototype.slice: 1.0.4 + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + data-view-buffer: 1.0.2 + data-view-byte-length: 1.0.2 + data-view-byte-offset: 1.0.1 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + es-set-tostringtag: 2.1.0 + es-to-primitive: 1.3.4 + function.prototype.name: 1.2.0 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + get-symbol-description: 1.1.0 + globalthis: 1.0.4 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + has-proto: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + internal-slot: 1.1.0 + is-array-buffer: 3.0.5 + is-callable: 1.2.7 + is-data-view: 1.0.2 + is-negative-zero: 2.0.3 + is-regex: 1.2.1 + is-set: 2.0.3 + is-shared-array-buffer: 1.0.4 + is-string: 1.1.1 + is-typed-array: 1.1.15 + is-weakref: 1.1.1 + math-intrinsics: 1.1.0 + object-inspect: 1.13.4 + object-keys: 1.1.1 + object.assign: 4.1.7 + own-keys: 1.0.2 + regexp.prototype.flags: 1.5.4 + safe-array-concat: 1.1.4 + safe-push-apply: 1.0.0 + safe-regex-test: 1.1.0 + set-proto: 1.0.0 + stop-iteration-iterator: 1.1.0 + string.prototype.trim: 1.2.11 + string.prototype.trimend: 1.0.10 + string.prototype.trimstart: 1.0.8 + typed-array-buffer: 1.0.3 + typed-array-byte-length: 1.0.3 + typed-array-byte-offset: 1.0.5 + typed-array-length: 1.0.8 + unbox-primitive: 1.1.0 + which-typed-array: 1.1.24 + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-iterator-helpers@1.4.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-set-tostringtag: 2.1.0 + function-bind: 1.1.2 + get-intrinsic: 1.3.0 + globalthis: 1.0.4 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + has-proto: 1.2.0 + has-symbols: 1.1.0 + internal-slot: 1.1.0 + iterator.prototype: 1.1.5 + math-intrinsics: 1.1.0 + es-module-lexer@2.3.2: {} es-module-lexer@3.0.4: {} + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + es-shim-unscopables@1.1.0: + dependencies: + hasown: 2.0.4 + + es-to-primitive@1.3.4: + dependencies: + es-abstract-get: 1.0.0 + es-define-property: 1.0.1 + es-errors: 1.3.0 + is-callable: 1.2.7 + is-date-object: 1.1.0 + is-symbol: 1.1.1 + esbuild@0.18.20: optionalDependencies: '@esbuild/android-arm': 0.18.20 @@ -3570,6 +4283,28 @@ snapshots: transitivePeerDependencies: - supports-color + eslint-plugin-react@7.37.5(eslint@10.15.0(jiti@2.7.0)): + dependencies: + array-includes: 3.2.0 + array.prototype.findlast: 1.2.5 + array.prototype.flatmap: 1.3.3 + array.prototype.tosorted: 1.1.4 + doctrine: 2.1.0 + es-iterator-helpers: 1.4.0 + eslint: 10.15.0(jiti@2.7.0) + estraverse: 5.3.0 + hasown: 2.0.4 + jsx-ast-utils: 3.3.5 + minimatch: 3.1.5 + object.entries: 1.1.9 + object.fromentries: 2.0.8 + object.values: 1.2.1 + prop-types: 15.8.1 + resolve: 2.0.0-next.7 + semver: 6.3.2 + string.prototype.matchall: 4.1.0 + string.prototype.repeat: 1.0.0 + eslint-plugin-sonarjs@4.2.2(eslint@10.15.0(jiti@2.7.0)): dependencies: '@eslint-community/regexpp': 4.12.3 @@ -3723,11 +4458,57 @@ snapshots: flatted@3.4.4: {} + for-each@0.3.5: + dependencies: + is-callable: 1.2.7 + fsevents@2.3.3: optional: true + function-bind@1.1.2: {} + + function.prototype.name@1.2.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + es-define-property: 1.0.1 + es-errors: 1.3.0 + functions-have-names: 1.2.3 + has-property-descriptors: 1.0.2 + hasown: 2.0.4 + is-callable: 1.2.7 + is-document.all: 1.0.0 + functional-red-black-tree@1.0.1: {} + functions-have-names@1.2.3: {} + + generator-function@2.0.1: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + + get-symbol-description@1.1.0: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + get-tsconfig@4.14.3: dependencies: resolve-pkg-maps: 1.0.0 @@ -3742,10 +4523,37 @@ snapshots: globals@17.14.0: {} + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + + gopd@1.2.0: {} + + has-bigints@1.1.0: {} + + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + + has-proto@1.2.0: + dependencies: + dunder-proto: 1.0.1 + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + hashery@1.5.1: dependencies: hookified: 1.15.1 + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + help-me@5.0.0: {} hono@4.13.18: {} @@ -3770,6 +4578,35 @@ snapshots: indent-string@5.0.0: {} + internal-slot@1.1.0: + dependencies: + es-errors: 1.3.0 + hasown: 2.0.4 + side-channel: 1.1.1 + + is-array-buffer@3.0.5: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + + is-async-function@2.1.1: + dependencies: + async-function: 1.0.0 + call-bound: 1.0.4 + get-proto: 1.0.1 + has-tostringtag: 1.0.2 + safe-regex-test: 1.1.0 + + is-bigint@1.1.0: + dependencies: + has-bigints: 1.1.0 + + is-boolean-object@1.2.2: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + is-builtin-module@5.0.0: dependencies: builtin-modules: 5.5.0 @@ -3778,18 +4615,112 @@ snapshots: dependencies: semver: 7.8.6 + is-callable@1.2.7: {} + + is-core-module@2.18.0: + dependencies: + hasown: 2.0.4 + + is-data-view@1.0.2: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + is-typed-array: 1.1.15 + + is-date-object@1.1.0: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-document.all@1.0.0: + dependencies: + call-bound: 1.0.4 + is-extglob@2.1.1: {} + is-finalizationregistry@1.1.1: + dependencies: + call-bound: 1.0.4 + + is-generator-function@1.1.2: + dependencies: + call-bound: 1.0.4 + generator-function: 2.0.1 + get-proto: 1.0.1 + has-tostringtag: 1.0.2 + safe-regex-test: 1.1.0 + is-glob@4.0.3: dependencies: is-extglob: 2.1.1 + is-map@2.0.3: {} + + is-negative-zero@2.0.3: {} + + is-number-object@1.1.1: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-regex@1.2.1: + dependencies: + call-bound: 1.0.4 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + is-set@2.0.3: {} + + is-shared-array-buffer@1.0.4: + dependencies: + call-bound: 1.0.4 + + is-string@1.1.1: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-symbol@1.1.1: + dependencies: + call-bound: 1.0.4 + has-symbols: 1.1.0 + safe-regex-test: 1.1.0 + + is-typed-array@1.1.15: + dependencies: + which-typed-array: 1.1.24 + + is-weakmap@2.0.2: {} + + is-weakref@1.1.1: + dependencies: + call-bound: 1.0.4 + + is-weakset@2.0.4: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + + isarray@2.0.5: {} + isexe@2.0.0: {} + iterator.prototype@1.1.5: + dependencies: + define-data-property: 1.1.4 + es-object-atoms: 1.1.2 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + has-symbols: 1.1.0 + set-function-name: 2.0.2 + jiti@2.7.0: {} joycon@3.1.1: {} + js-tokens@4.0.0: {} + jsesc@3.1.0: {} json-schema-traverse@0.4.1: {} @@ -3798,6 +4729,13 @@ snapshots: jsx-ast-utils-x@0.1.0: {} + jsx-ast-utils@3.3.5: + dependencies: + array-includes: 3.2.0 + array.prototype.flat: 1.3.3 + object.assign: 4.1.7 + object.values: 1.2.1 + keyv@5.6.0: dependencies: '@keyv/serialize': 1.1.1 @@ -3866,6 +4804,10 @@ snapshots: lodash@4.18.1: {} + loose-envify@1.4.0: + dependencies: + js-tokens: 4.0.0 + luxon@3.7.2: {} magic-bytes.js@1.13.1: {} @@ -3874,6 +4816,8 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + math-intrinsics@1.1.0: {} + mdn-data@2.37.2: {} micromark-core-commonmark@2.0.4: @@ -4017,6 +4961,10 @@ snapshots: '@isaacs/nonrecursive-glob-match': 1.1.0 brace-expansion: 5.0.13 + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.22 + minimist@1.2.8: {} ms@2.1.3: {} @@ -4027,10 +4975,53 @@ snapshots: natural-compare@1.4.0: {} + node-exports-info@1.6.2: + dependencies: + array.prototype.flatmap: 1.3.3 + es-errors: 1.3.0 + object.entries: 1.1.9 + semver: 6.3.2 + node-releases@2.0.64: {} non-error@0.1.0: {} + object-assign@4.1.1: {} + + object-inspect@1.13.4: {} + + object-keys@1.1.1: {} + + object.assign@4.1.7: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + has-symbols: 1.1.0 + object-keys: 1.1.1 + + object.entries@1.1.9: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + + object.fromentries@2.0.8: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + + object.values@1.2.1: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + obug@3.0.0: {} on-exit-leak-free@2.1.2: {} @@ -4048,6 +5039,13 @@ snapshots: type-check: 0.4.0 word-wrap: 1.2.5 + own-keys@1.0.2: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + object-keys: 1.1.1 + safe-push-apply: 1.0.0 + p-limit@3.1.0: dependencies: yocto-queue: 0.1.0 @@ -4064,6 +5062,8 @@ snapshots: path-key@3.1.1: {} + path-parse@1.0.7: {} + pg-boss@12.38.2(@opentelemetry/api@1.10.0): dependencies: '@opentelemetry/api': 1.10.0 @@ -4151,6 +5151,8 @@ snapshots: pluralize@8.0.0: {} + possible-typed-array-names@1.1.0: {} + postcss@8.5.33: dependencies: nanoid: 3.3.20 @@ -4175,6 +5177,12 @@ snapshots: process-warning@5.1.1: {} + prop-types@15.8.1: + dependencies: + loose-envify: 1.4.0 + object-assign: 4.1.1 + react-is: 16.13.1 + pump@3.0.4: dependencies: end-of-stream: 1.4.5 @@ -4192,17 +5200,39 @@ snapshots: quote-js-string@0.1.0: {} + react-is@16.13.1: {} + real-require@1.0.0: {} refa@0.12.1: dependencies: '@eslint-community/regexpp': 4.12.3 + reflect.getprototypeof@1.0.10: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + which-builtin-type: 1.2.1 + regexp-ast-analysis@0.7.1: dependencies: '@eslint-community/regexpp': 4.12.3 refa: 0.12.1 + regexp.prototype.flags@1.5.4: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-errors: 1.3.0 + get-proto: 1.0.1 + gopd: 1.2.0 + set-function-name: 2.0.2 + regjsparser@0.13.4: dependencies: jsesc: 3.1.0 @@ -4211,6 +5241,15 @@ snapshots: resolve-pkg-maps@1.0.0: {} + resolve@2.0.0-next.7: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.18.0 + node-exports-info: 1.6.2 + object-keys: 1.1.1 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + rolldown-plugin-dts@0.30.2(rolldown@1.3.2)(typescript@6.0.3): dependencies: dts-resolver: 3.0.0 @@ -4272,6 +5311,25 @@ snapshots: dependencies: temporal-spec: 1.0.1 + safe-array-concat@1.1.4: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + has-symbols: 1.1.0 + isarray: 2.0.5 + + safe-push-apply@1.0.0: + dependencies: + es-errors: 1.3.0 + isarray: 2.0.5 + + safe-regex-test@1.1.0: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-regex: 1.2.1 + safe-stable-stringify@2.5.0: {} scslre@0.3.0: @@ -4282,6 +5340,8 @@ snapshots: secure-json-parse@4.1.1: {} + semver@6.3.2: {} + semver@7.8.6: {} serialize-error@13.1.0: @@ -4289,12 +5349,62 @@ snapshots: non-error: 0.1.0 type-fest: 5.10.0 + set-function-length@1.2.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + function-bind: 1.1.2 + get-intrinsic: 1.3.0 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + + set-function-name@2.0.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + functions-have-names: 1.2.3 + has-property-descriptors: 1.0.2 + + set-proto@1.0.0: + dependencies: + dunder-proto: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 shebang-regex@3.0.0: {} + side-channel-list@1.0.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + + side-channel-map@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + + side-channel-weakmap@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + side-channel-map: 1.0.1 + + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + sonic-boom@4.2.1: dependencies: atomic-sleep: 1.0.0 @@ -4318,10 +5428,62 @@ snapshots: std-env@4.3.0: {} + stop-iteration-iterator@1.1.0: + dependencies: + es-errors: 1.3.0 + internal-slot: 1.1.0 + + string.prototype.matchall@4.1.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + get-intrinsic: 1.3.0 + gopd: 1.2.0 + has-symbols: 1.1.0 + internal-slot: 1.1.0 + regexp.prototype.flags: 1.5.4 + set-function-name: 2.0.2 + side-channel: 1.1.1 + + string.prototype.repeat@1.0.0: + dependencies: + define-properties: 1.2.1 + es-abstract: 1.24.2 + + string.prototype.trim@1.2.11: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-data-property: 1.1.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + has-property-descriptors: 1.0.2 + safe-regex-test: 1.1.0 + + string.prototype.trimend@1.0.10: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + + string.prototype.trimstart@1.0.8: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + strip-indent@4.1.1: {} strip-json-comments@5.1.0: {} + supports-preserve-symlinks-flag@1.0.0: {} + tagged-tag@1.0.0: {} temporal-spec@1.0.1: {} @@ -4390,6 +5552,38 @@ snapshots: dependencies: tagged-tag: 1.0.0 + typed-array-buffer@1.0.3: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-typed-array: 1.1.15 + + typed-array-byte-length@1.0.3: + dependencies: + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + has-proto: 1.2.0 + is-typed-array: 1.1.15 + + typed-array-byte-offset@1.0.5: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + is-typed-array: 1.1.15 + reflect.getprototypeof: 1.0.10 + + typed-array-length@1.0.8: + dependencies: + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + is-typed-array: 1.1.15 + possible-typed-array-names: 1.1.0 + reflect.getprototypeof: 1.0.10 + typescript-eslint@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3): dependencies: '@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3) @@ -4403,6 +5597,13 @@ snapshots: typescript@6.0.3: {} + unbox-primitive@1.1.0: + dependencies: + call-bound: 1.0.4 + has-bigints: 1.1.0 + has-symbols: 1.1.0 + which-boxed-primitive: 1.1.1 + unconfig-core@7.5.0: dependencies: '@quansync/fs': 1.1.0 @@ -4489,6 +5690,47 @@ snapshots: transitivePeerDependencies: - msw + which-boxed-primitive@1.1.1: + dependencies: + is-bigint: 1.1.0 + is-boolean-object: 1.2.2 + is-number-object: 1.1.1 + is-string: 1.1.1 + is-symbol: 1.1.1 + + which-builtin-type@1.2.1: + dependencies: + call-bound: 1.0.4 + function.prototype.name: 1.2.0 + has-tostringtag: 1.0.2 + is-async-function: 2.1.1 + is-date-object: 1.1.0 + is-finalizationregistry: 1.1.1 + is-generator-function: 1.1.2 + is-regex: 1.2.1 + is-weakref: 1.1.1 + isarray: 2.0.5 + which-boxed-primitive: 1.1.1 + which-collection: 1.0.2 + which-typed-array: 1.1.24 + + which-collection@1.0.2: + dependencies: + is-map: 2.0.3 + is-set: 2.0.3 + is-weakmap: 2.0.2 + is-weakset: 2.0.4 + + which-typed-array@1.1.24: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + for-each: 0.3.5 + get-proto: 1.0.1 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + which@2.0.2: dependencies: isexe: 2.0.0 diff --git a/public/app.css b/public/app.css new file mode 100644 index 0000000..269a745 --- /dev/null +++ b/public/app.css @@ -0,0 +1,45 @@ +td form { + display: inline-block; + margin: 0 0.25rem 0 0; +} + +td button { + margin: 0; + padding: 0.25rem 0.75rem; +} + +.notice, +.error { + padding: 0.5rem 0.75rem; + border-radius: 6px; +} + +.notice { + background: #dafbe1; + color: #1a7f37; +} + +.error { + background: #ffebe9; + color: #cf222e; +} + +.discord { + margin-bottom: 1rem; + padding: 0.75rem 1rem; + border-radius: 8px; + background: #313338; + color: #dbdee1; +} + +.discord .h1 { + font-size: 1.5rem; + font-weight: 700; +} + +.mention { + padding: 0 0.15rem; + border-radius: 3px; + background: #3c4270; + color: #c9cdfb; +} diff --git a/src/infra/web/app.tsx b/src/infra/web/app.tsx index a756ae5..d6da78d 100644 --- a/src/infra/web/app.tsx +++ b/src/infra/web/app.tsx @@ -1,38 +1,22 @@ import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { createRequire } from 'node:module'; +import { serveStatic } from '@hono/node-server/serve-static'; import { Hono } from 'hono'; import { bodyLimit } from 'hono/body-limit'; import { csrf } from 'hono/csrf'; import { HTTPException } from 'hono/http-exception'; import { secureHeaders } from 'hono/secure-headers'; import { UserError } from '~/domain'; -import { back, type Env, type WebDeps } from './context'; +import { back, guildOf, type Env, type WebDeps } from './context'; import { eventPages } from './events'; import { Layout } from './layout'; import { permissionPages } from './permissions'; import { pollPages } from './polls'; import { psaPages } from './psa'; -const style = `${readFileSync( - createRequire(import.meta.url).resolve( - '@picocss/pico/css/pico.classless.min.css', - ), - 'utf8', -)} -td form { display: inline-block; margin: 0 .25rem 0 0; } -td button { padding: .25rem .75rem; margin: 0; } -.notice { padding: .5rem .75rem; border-radius: 6px; background: #dafbe1; color: #1a7f37; } -.error { padding: .5rem .75rem; border-radius: 6px; background: #ffebe9; color: #cf222e; } -.discord { background: #313338; color: #dbdee1; padding: .75rem 1rem; border-radius: 8px; margin-bottom: 1rem; } -.discord .h1 { font-size: 1.5rem; font-weight: 700; } -.mention { background: #3c4270; color: #c9cdfb; border-radius: 3px; padding: 0 .15rem; } -`; - -function Message(props: Readonly<{ title: string; text: string }>) { +function Message({ title, text }: Readonly<{ title: string; text: string }>) { return ( - -

{props.text}

+ +

{text}

Back to the overview

@@ -48,16 +32,14 @@ export function createWebApp(deps: WebDeps) { secureHeaders({ contentSecurityPolicy: { defaultSrc: ["'none'"], - styleSrc: ["'self'"], + styleSrc: ["'self'", 'https://cdn.jsdelivr.net'], formAction: ["'self'"], frameAncestors: ["'none'"], }, referrerPolicy: 'same-origin', }), ); - app.get('/style.css', (c) => - c.body(style, 200, { 'Content-Type': 'text/css; charset=utf-8' }), - ); + app.use(serveStatic({ root: 'public' })); app.use( bodyLimit({ maxSize: 64 * 1024, @@ -85,18 +67,9 @@ export function createWebApp(deps: WebDeps) { directory.channels(guildId), directory.roles(guildId), ]); - const roleNames = new Map(roles.map((role) => [role.id, role.name])); - const channelNames = new Map( - channels.map((channel) => [channel.id, channel.name]), - ); c.set('actor', actor); - c.set('guild', { - channels, - roles, - roleName: (id) => roleNames.get(id) ?? 'unknown role', - channelName: (id) => `#${channelNames.get(id) ?? id}`, - }); + c.set('guild', guildOf(channels, roles)); return next(); }); diff --git a/src/infra/web/context.ts b/src/infra/web/context.ts index e1f942d..6e185d9 100644 --- a/src/infra/web/context.ts +++ b/src/infra/web/context.ts @@ -36,6 +36,22 @@ export type Guild = { channelName: (id: string) => string; }; +export function guildOf(channels: ChannelInfo[], roles: RoleInfo[]): Guild { + const roleNames = new Map( + roles.map((role) => [role.id, role.name]), + ); + const channelNames = new Map( + channels.map((channel) => [channel.id, channel.name]), + ); + + return { + channels, + roles, + roleName: (id: string): string => roleNames.get(id) ?? 'unknown role', + channelName: (id: string): string => `#${channelNames.get(id) ?? id}`, + }; +} + export type Env = { Variables: { actor: Actor; guild: Guild } }; export type Flash = { notice?: string; error?: string }; diff --git a/src/infra/web/events.tsx b/src/infra/web/events.tsx index b92e786..e329a62 100644 --- a/src/infra/web/events.tsx +++ b/src/infra/web/events.tsx @@ -56,7 +56,9 @@ export function eventPages({ guildId, services, timezone }: WebDeps) { Reminders @@ -77,7 +79,7 @@ export function eventPages({ guildId, services, timezone }: WebDeps) { {upcoming.map((e) => ( - + {e.id} {e.title} {date(e.startsAt)} diff --git a/src/infra/web/layout.tsx b/src/infra/web/layout.tsx index f8f63bd..73fb561 100644 --- a/src/infra/web/layout.tsx +++ b/src/infra/web/layout.tsx @@ -9,21 +9,23 @@ const sections = [ ['/permissions', 'Permissions'], ] as const; -export function Layout( - props: Readonly<{ - title: string; - path: string; - flash?: Flash; - children?: Child; - }>, -) { +const pico = + 'https://cdn.jsdelivr.net/npm/@picocss/pico@2.1.1/css/pico.classless.min.css'; + +export function Layout({ + title, + path, + flash = {}, + children, +}: Readonly<{ title: string; path: string; flash?: Flash; children?: Child }>) { return ( - {`${props.title} · LAPbot`} - + {`${title} · LAPbot`} + +
@@ -35,10 +37,10 @@ export function Layout(
    {sections.map(([href, label]) => ( -
  • +
  • {label} @@ -48,66 +50,68 @@ export function Layout(
-

{props.title}

- {props.flash?.notice === undefined ? null : ( +

{title}

+ {flash.notice === undefined ? null : (

- {props.flash.notice} + {flash.notice}

)} - {props.flash?.error === undefined ? null : ( + {flash.error === undefined ? null : ( )} - {props.children} + {children}
); } -export function ChannelSelect( - props: Readonly<{ guild: Guild; name?: string }>, -) { +export function ChannelSelect({ + guild, + name = 'channelId', +}: Readonly<{ guild: Guild; name?: string }>) { return ( ); } -export function Checkbox( - props: Readonly<{ - name: string; - label: string; - checked?: boolean; - value?: string; - }>, -) { +export function Checkbox({ + name, + label, + checked = false, + value = '1', +}: Readonly<{ + name: string; + label: string; + checked?: boolean; + value?: string; +}>) { return ( ); } -export function ActionButton( - props: Readonly<{ action: string; label: string }>, -) { +export function ActionButton({ + action, + label, +}: Readonly<{ action: string; label: string }>) { return ( -
- + +
); } diff --git a/src/infra/web/permissions.tsx b/src/infra/web/permissions.tsx index 767d85c..f066932 100644 --- a/src/infra/web/permissions.tsx +++ b/src/infra/web/permissions.tsx @@ -19,7 +19,9 @@ export function permissionPages({ services }: WebDeps) { {guild.roles .filter((role) => !role.managed) .map((role) => ( - + ))} @@ -27,14 +29,14 @@ export function permissionPages({ services }: WebDeps) { Permission - @@ -48,7 +50,7 @@ export function permissionPages({ services }: WebDeps) { {grants.map((grant) => ( - + @{guild.roleName(grant.roleId)} {grant.permission} @@ -59,7 +61,7 @@ export function permissionPages({ services }: WebDeps) { name="permission" value={grant.permission} /> - diff --git a/src/infra/web/polls.tsx b/src/infra/web/polls.tsx index f5f8b22..38778b6 100644 --- a/src/infra/web/polls.tsx +++ b/src/infra/web/polls.tsx @@ -57,7 +57,7 @@ export function pollPages({ guildId, services, timezone }: WebDeps) { {open.map((p) => ( - + {p.id} {p.question} {date(p.closesAt)} diff --git a/src/infra/web/preview.tsx b/src/infra/web/preview.tsx index 210c62d..15ddc98 100644 --- a/src/infra/web/preview.tsx +++ b/src/infra/web/preview.tsx @@ -3,59 +3,66 @@ import type { Guild } from './context'; const token = /(<@&\d+>|<@\d+>|<#\d+>|@everyone|\*\*[^*]+\*\*)/; -function Inline(props: Readonly<{ text: string; guild: Guild }>) { - return ( - <> - {props.text.split(token).map((part) => { - const role = /^<@&(\d+)>$/.exec(part)?.[1]; - const channel = /^<#(\d+)>$/.exec(part)?.[1]; - - if (role !== undefined) { - return @{props.guild.roleName(role)}; - } - - if (/^<@\d+>$/.test(part)) { - return @user; - } - - if (channel !== undefined) { - return ( - #{props.guild.channelName(channel)} - ); - } - - if (part === '@everyone') { - return @everyone; - } - - if (part.startsWith('**') && part.endsWith('**')) { - return {part.slice(2, -2)}; - } - - return <>{part}; - })} - - ); +function withOffsets(parts: readonly string[], separator = 0) { + let offset = 0; + + return parts.map((part) => { + const start = offset; + + offset += part.length + separator; + + return { part, start }; + }); +} + +function Piece({ part, guild }: Readonly<{ part: string; guild: Guild }>) { + const role = /^<@&(\d+)>$/.exec(part)?.[1]; + const channel = /^<#(\d+)>$/.exec(part)?.[1]; + + if (role !== undefined) { + return @{guild.roleName(role)}; + } + + if (/^<@\d+>$/.test(part)) { + return @user; + } + + if (channel !== undefined) { + return #{guild.channelName(channel)}; + } + + if (part === '@everyone') { + return @everyone; + } + + if (part.startsWith('**') && part.endsWith('**')) { + return {part.slice(2, -2)}; + } + + return {part}; +} + +function Line({ text, guild }: Readonly<{ text: string; guild: Guild }>) { + const heading = text.startsWith('# '); + const body = heading ? text.slice(2) : text; + const pieces = withOffsets( + body.split(token).filter((part) => part !== ''), + ).map(({ part, start }) => ); + + return heading ?
{pieces}
:
{pieces}
; } -export function MessagePreview( - props: Readonly<{ message: Message; guild: Guild }>, -) { - const lines = (props.message.content ?? '').split('\n'); +export function MessagePreview({ + message, + guild, +}: Readonly<{ message: Message; guild: Guild }>) { + const lines = withOffsets((message.content ?? '').split('\n'), 1); return (
- {lines.map((line) => - line.startsWith('# ') ? ( -
- -
- ) : ( -
- -
- ), - )} + {lines.map(({ part, start }) => ( + + ))}
); } diff --git a/src/infra/web/psa.tsx b/src/infra/web/psa.tsx index a7b9a14..d994869 100644 --- a/src/infra/web/psa.tsx +++ b/src/infra/web/psa.tsx @@ -31,12 +31,11 @@ function draftOf(form: Form) { type Draft = ReturnType; -function MentionPicker( - props: Readonly<{ guild: Guild; draft: Draft | undefined }>, -) { - const roles = props.guild.roles.filter( - (role) => !role.everyone && !role.managed, - ); +function MentionPicker({ + guild, + draft, +}: Readonly<{ guild: Guild; draft: Draft | undefined }>) { + const roles = guild.roles.filter((role) => !role.everyone && !role.managed); return (
@@ -44,67 +43,72 @@ function MentionPicker( - {roles.map((role) => ( + {roles.map(({ id, name }) => ( ))}
); } -function Composer( - props: Readonly<{ guild: Guild; draft?: Draft; preview?: Child }>, -) { +const actions = [ + ['preview', 'Preview'], + ['draft', 'Save draft'], + ['schedule', 'Schedule'], + ['publish', 'Publish now'], +] as const; + +function Composer({ + guild, + draft, + preview, +}: Readonly<{ guild: Guild; draft?: Draft; preview?: Child }>) { return (
- + - + - {props.preview} + {preview}
- - - - + {actions.map(([value, label]) => ( + + ))}
); } -function Recent( - props: Readonly<{ - list: Announcement[]; - guild: Guild; - date: (value: Date | null) => string; - }>, -) { +function Recent({ + list, + guild, + date, +}: Readonly<{ + list: Announcement[]; + guild: Guild; + date: (value: Date | null) => string; +}>) { return ( @@ -118,8 +122,8 @@ function Recent( - {props.list.map((a) => ( - + {list.map((a) => ( + - + - + - + {grants.map((grant) => ( - + - +
{a.id} {a.status} @@ -130,9 +134,9 @@ function Recent( )} {props.guild.channelName(a.channelId)}{guild.channelName(a.channelId)} {a.title ?? a.content.slice(0, 60)}{props.date(a.publishedAt ?? a.scheduledAt)}{date(a.publishedAt ?? a.scheduledAt)} {a.status === 'draft' || a.status === 'scheduled' ? ( <> diff --git a/tests/infra/web/app.test.ts b/tests/infra/web/app.test.ts index 4877583..c2c5fd4 100644 --- a/tests/infra/web/app.test.ts +++ b/tests/infra/web/app.test.ts @@ -125,7 +125,7 @@ describe.skipIf(noDatabase)('web UI', () => { }); it('serves the stylesheet the pages link to', async () => { - const response = await get('/style.css'); + const response = await get('/app.css'); expect(response.headers.get('content-type')).toContain('text/css'); expect(await response.text()).toContain('.discord'); From da7d2f5420bea00dcb3e18aff2647dea588620f7 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 13:20:18 +0200 Subject: [PATCH 059/199] refactor(web): call it a server, not a guild --- README.md | 2 +- src/infra/web/app.tsx | 4 ++-- src/infra/web/context.ts | 6 +++--- src/infra/web/events.tsx | 6 +++--- src/infra/web/layout.tsx | 8 ++++---- src/infra/web/permissions.tsx | 6 +++--- src/infra/web/polls.tsx | 2 +- src/infra/web/preview.tsx | 18 +++++++++--------- src/infra/web/psa.tsx | 32 ++++++++++++++++---------------- 9 files changed, 42 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 05faaf7..6e69592 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ drizzle/ SQL migrations barrel (`~/core/services`, never `~/core/services/roles`). The domain depends on nothing, core depends only on the domain, and only `infra/discord` may import discord.js. -- **Services take an `Actor`** (guild, user, roles, administrator), not a +- **Services take an `Actor`** (server, user, roles, administrator), not a Discord member, and enforce permissions themselves. Any adapter that can produce an actor (Discord now, a web UI later) gets the same rules. - **Messages are transport-neutral** (`domain/message.ts`): content, embeds, diff --git a/src/infra/web/app.tsx b/src/infra/web/app.tsx index d6da78d..0951d02 100644 --- a/src/infra/web/app.tsx +++ b/src/infra/web/app.tsx @@ -6,7 +6,7 @@ import { csrf } from 'hono/csrf'; import { HTTPException } from 'hono/http-exception'; import { secureHeaders } from 'hono/secure-headers'; import { UserError } from '~/domain'; -import { back, guildOf, type Env, type WebDeps } from './context'; +import { back, serverOf, type Env, type WebDeps } from './context'; import { eventPages } from './events'; import { Layout } from './layout'; import { permissionPages } from './permissions'; @@ -69,7 +69,7 @@ export function createWebApp(deps: WebDeps) { ]); c.set('actor', actor); - c.set('guild', guildOf(channels, roles)); + c.set('server', serverOf(channels, roles)); return next(); }); diff --git a/src/infra/web/context.ts b/src/infra/web/context.ts index 6e185d9..57c2ea3 100644 --- a/src/infra/web/context.ts +++ b/src/infra/web/context.ts @@ -29,14 +29,14 @@ export type WebDeps = { log: Logger; }; -export type Guild = { +export type Server = { channels: ChannelInfo[]; roles: RoleInfo[]; roleName: (id: string) => string; channelName: (id: string) => string; }; -export function guildOf(channels: ChannelInfo[], roles: RoleInfo[]): Guild { +export function serverOf(channels: ChannelInfo[], roles: RoleInfo[]): Server { const roleNames = new Map( roles.map((role) => [role.id, role.name]), ); @@ -52,7 +52,7 @@ export function guildOf(channels: ChannelInfo[], roles: RoleInfo[]): Guild { }; } -export type Env = { Variables: { actor: Actor; guild: Guild } }; +export type Env = { Variables: { actor: Actor; server: Server } }; export type Flash = { notice?: string; error?: string }; diff --git a/src/infra/web/events.tsx b/src/infra/web/events.tsx index e329a62..eba03d7 100644 --- a/src/infra/web/events.tsx +++ b/src/infra/web/events.tsx @@ -19,7 +19,7 @@ export function eventPages({ guildId, services, timezone }: WebDeps) { return new Hono() .get('/', async (c) => { const upcoming = await services.events.upcoming(guildId); - const { guild } = c.var; + const { server } = c.var; return c.html( @@ -46,7 +46,7 @@ export function eventPages({ guildId, services, timezone }: WebDeps) { Location - +
{e.id} {e.title} {date(e.startsAt)}{guild.channelName(e.channelId)}{server.channelName(e.channelId)} ) { +}: Readonly<{ server: Server; name?: string }>) { return (
@{guild.roleName(grant.roleId)}@{server.roleName(grant.roleId)} {grant.permission}
diff --git a/src/infra/web/polls.tsx b/src/infra/web/polls.tsx index 38778b6..6131f14 100644 --- a/src/infra/web/polls.tsx +++ b/src/infra/web/polls.tsx @@ -28,7 +28,7 @@ export function pollPages({ guildId, services, timezone }: WebDeps) { Options (one per line, up to 10) - +
{guild.channelName(a.channelId)}{server.channelName(a.channelId)} {a.title ?? a.content.slice(0, 60)} {date(a.publishedAt ?? a.scheduledAt)} @@ -164,9 +164,9 @@ export function psaPages({ guildId, services, timezone }: WebDeps) { return c.html( - +

Recent

- +
, ); }) @@ -174,7 +174,7 @@ export function psaPages({ guildId, services, timezone }: WebDeps) { const form = await c.req.formData(); const action = form.get('action'); const draft = draftOf(form); - const { actor, guild } = c.var; + const { actor, server } = c.var; if (action === 'preview') { const view = services.announcements.view({ @@ -194,12 +194,12 @@ export function psaPages({ guildId, services, timezone }: WebDeps) { return c.html(

Preview

- + } /> From db3690b57c3cd697ae959a8689f117fa81ca97be Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 13:27:31 +0200 Subject: [PATCH 060/199] fix(scheduler): job types without colons, which pg-boss rejects as queue names --- src/core/services/announcements.ts | 2 +- src/core/services/birthdays.ts | 4 ++-- src/core/services/events.ts | 2 +- src/core/services/polls.ts | 2 +- src/core/services/redmine.ts | 4 ++-- src/core/services/reminders.ts | 2 +- tests/app.test.ts | 10 +++++++++- tests/core/services/reminders.test.ts | 2 +- 8 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/core/services/announcements.ts b/src/core/services/announcements.ts index 279ff7b..d88553d 100644 --- a/src/core/services/announcements.ts +++ b/src/core/services/announcements.ts @@ -174,7 +174,7 @@ export function createAnnouncementService(deps: Deps) { }; const publishJob = defineJob({ - type: 'announcements:publish', + type: 'announcements.publish', payload: z.object({ announcementId: z.number().int() }), handle: async ({ announcementId }) => { const announcement = await announcements.find(announcementId); diff --git a/src/core/services/birthdays.ts b/src/core/services/birthdays.ts index 3a4196a..e296f53 100644 --- a/src/core/services/birthdays.ts +++ b/src/core/services/birthdays.ts @@ -58,7 +58,7 @@ export function createBirthdayService(deps: Deps) { deps; const removeRoleJob = defineJob({ - type: 'birthdays:remove-role', + type: 'birthdays.remove-role', payload: z.object({ guildId: z.string(), userId: z.string(), @@ -132,7 +132,7 @@ export function createBirthdayService(deps: Deps) { }; const dailyJob = defineJob({ - type: 'birthdays:daily', + type: 'birthdays.daily', payload: z.object({ guildId: z.string() }), handle: async ({ guildId }) => { const settings = await birthdays.settings(guildId); diff --git a/src/core/services/events.ts b/src/core/services/events.ts index a0b0651..882cb46 100644 --- a/src/core/services/events.ts +++ b/src/core/services/events.ts @@ -204,7 +204,7 @@ export function createEventService(deps: Deps) { deps; const remindJob = defineJob({ - type: 'events:remind', + type: 'events.remind', payload: z.object({ eventId: z.number().int(), minutes: z.number().int() }), handle: async ({ eventId, minutes }) => { const event = await events.find(eventId); diff --git a/src/core/services/polls.ts b/src/core/services/polls.ts index 8c18bc5..65ca748 100644 --- a/src/core/services/polls.ts +++ b/src/core/services/polls.ts @@ -141,7 +141,7 @@ export function createPollService(deps: Deps) { }; const closeJob = defineJob({ - type: 'polls:close', + type: 'polls.close', payload: z.object({ pollId: z.number().int() }), handle: async ({ pollId }) => { if (await polls.finish(pollId, 'closed')) { diff --git a/src/core/services/redmine.ts b/src/core/services/redmine.ts index 8197cce..ae92184 100644 --- a/src/core/services/redmine.ts +++ b/src/core/services/redmine.ts @@ -120,7 +120,7 @@ export function createRedmineService(deps: Deps) { }; const pollJob = defineJob({ - type: 'redmine:poll', + type: 'redmine.poll', payload: z.object({}), handle: async () => { const known = await client.listStatuses().catch(() => []); @@ -135,7 +135,7 @@ export function createRedmineService(deps: Deps) { }); const deadlineJob = defineJob({ - type: 'redmine:deadlines', + type: 'redmine.deadlines', payload: z.object({}), handle: async () => { const tomorrow = formatCalendarDay( diff --git a/src/core/services/reminders.ts b/src/core/services/reminders.ts index 5fcaee8..aa470b5 100644 --- a/src/core/services/reminders.ts +++ b/src/core/services/reminders.ts @@ -58,7 +58,7 @@ export function createReminderService(deps: Deps) { }; const deliverJob = defineJob({ - type: 'reminders:deliver', + type: 'reminders.deliver', payload: z.object({ reminderId: z.number().int() }), handle: async ({ reminderId }) => { const reminder = await reminders.find(reminderId); diff --git a/tests/app.test.ts b/tests/app.test.ts index 2efcaec..bfb7186 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -4,7 +4,7 @@ import type { } from 'discord.js'; import { pino } from 'pino'; import { describe, expect, it } from 'vitest'; -import { createRegistry } from '~/app'; +import { compose, createRegistry } from '~/app'; import type { Config } from '~/config'; const config = { @@ -99,6 +99,14 @@ describe('composition root', () => { expect(sizes.filter(({ size }) => size > 4000)).toEqual([]); }); + it('names every job so pg-boss accepts it as a queue', () => { + const { jobs } = compose(config, pino({ level: 'silent' })); + + expect( + [...jobs.keys()].filter((type) => !/^[\w.\-/]+$/.test(type)), + ).toEqual([]); + }); + it('only requires permissions that some feature declares', () => { const declared = new Set(registry.permissions.keys()); const used = [...registry.commands.values()].flatMap((c) => diff --git a/tests/core/services/reminders.test.ts b/tests/core/services/reminders.test.ts index 7718dd3..68321af 100644 --- a/tests/core/services/reminders.test.ts +++ b/tests/core/services/reminders.test.ts @@ -48,7 +48,7 @@ describe.skipIf(noDatabase)('reminder service', () => { }); expect(scheduler.schedule).toHaveBeenCalledWith( - expect.objectContaining({ type: 'reminders:deliver' }), + expect.objectContaining({ type: 'reminders.deliver' }), { reminderId: reminder.id }, { runAt: reminder.runAt, From 69d19d2dbe445b2835713fcc0c89eabe63057cf2 Mon Sep 17 00:00:00 2001 From: Oluwatobiloba Promise Temitope Date: Mon, 16 Nov 2026 13:40:22 +0200 Subject: [PATCH 061/199] fix(web): use full Pico for grids, button groups and compact table buttons --- public/app.css | 15 +++++++++------ src/infra/web/events.tsx | 6 ++++-- src/infra/web/layout.tsx | 10 ++++++---- src/infra/web/polls.tsx | 6 ++++-- src/infra/web/psa.tsx | 18 ++++++++++++------ 5 files changed, 35 insertions(+), 20 deletions(-) diff --git a/public/app.css b/public/app.css index 269a745..fbd2a1f 100644 --- a/public/app.css +++ b/public/app.css @@ -4,24 +4,27 @@ td form { } td button { + --pico-form-element-spacing-vertical: 0.25rem; + --pico-form-element-spacing-horizontal: 0.75rem; + margin: 0; - padding: 0.25rem 0.75rem; + font-size: 0.875rem; } .notice, .error { padding: 0.5rem 0.75rem; - border-radius: 6px; + border-radius: var(--pico-border-radius); } .notice { - background: #dafbe1; - color: #1a7f37; + background: var(--pico-ins-color); + color: var(--pico-primary-inverse); } .error { - background: #ffebe9; - color: #cf222e; + background: var(--pico-del-color); + color: var(--pico-primary-inverse); } .discord { diff --git a/src/infra/web/events.tsx b/src/infra/web/events.tsx index eba03d7..a4e4334 100644 --- a/src/infra/web/events.tsx +++ b/src/infra/web/events.tsx @@ -63,8 +63,10 @@ export function eventPages({ guildId, services, timezone }: WebDeps) { - - +
+ + +
diff --git a/src/infra/web/layout.tsx b/src/infra/web/layout.tsx index 026362f..9cb3aa6 100644 --- a/src/infra/web/layout.tsx +++ b/src/infra/web/layout.tsx @@ -10,7 +10,7 @@ const sections = [ ] as const; const pico = - 'https://cdn.jsdelivr.net/npm/@picocss/pico@2.1.1/css/pico.classless.min.css'; + 'https://cdn.jsdelivr.net/npm/@picocss/pico@2.1.1/css/pico.min.css'; export function Layout({ title, @@ -28,7 +28,7 @@ export function Layout({ -
+
-
+

{title}

{flash.notice === undefined ? null : (

@@ -111,7 +111,9 @@ export function ActionButton({ }: Readonly<{ action: string; label: string }>) { return (
- + ); } diff --git a/src/infra/web/polls.tsx b/src/infra/web/polls.tsx index 6131f14..aa16537 100644 --- a/src/infra/web/polls.tsx +++ b/src/infra/web/polls.tsx @@ -29,8 +29,10 @@ export function pollPages({ guildId, services, timezone }: WebDeps) { + +

+ + +
+ + ); +} + +function fieldsOf(form: Form) { + const capacity = field(form, 'capacity'); + + return { + ...Object.fromEntries( + textFields.flatMap((name) => { + const value = field(form, name); + + return value === undefined ? [] : [[name, value]]; + }), + ), + icons: checked(form, 'icons'), + ...(capacity !== undefined && { capacity: Number(capacity) }), + }; +} export function eventPages({ guildId, services, timezone }: WebDeps) { const date = formatter(timezone); + const time = inputTime(timezone); return new Hono() .get('/', async (c) => { @@ -23,52 +107,6 @@ export function eventPages({ guildId, services, timezone }: WebDeps) { return c.html( -
- -
- - -
- +
- - + +
); @@ -207,16 +206,13 @@ export function eventPages({
- +
diff --git a/src/infra/web/layout.tsx b/src/infra/web/layout.tsx index 75fa8cc..0b0267d 100644 --- a/src/infra/web/layout.tsx +++ b/src/infra/web/layout.tsx @@ -1,6 +1,6 @@ import type { Child } from 'hono/jsx'; import { managePermissions, type Permission } from '~/domain'; -import type { Flash, Server } from './context'; +import type { Flash } from './context'; const sections: ReadonlyArray< readonly [href: string, label: string, permission?: Permission] @@ -100,109 +100,3 @@ export function Layout({ ); } - -export function ChannelOptions({ - server, - selected, -}: Readonly<{ server: Server; selected?: string | undefined }>) { - return ( - <> - {server.channels.map(({ id, name }) => ( - - ))} - - ); -} - -export function ChannelSelect({ - server, - name = 'channelId', - selected, -}: Readonly<{ server: Server; name?: string; selected?: string | undefined }>) { - return ( - - ); -} - -export function Checkbox({ - name, - label, - checked = false, - value = '1', -}: Readonly<{ - name: string; - label: string; - checked?: boolean; - value?: string; -}>) { - return ( - - ); -} - -export function ActionButton({ - action, - label, -}: Readonly<{ action: string; label: string }>) { - return ( - - - - ); -} - -export type Choice = { name: string; value: string; label: string }; - -export function MultiSelect({ - label, - placeholder, - choices, - selected, -}: Readonly<{ - label: string; - placeholder: string; - choices: readonly Choice[]; - selected: ReadonlySet; -}>) { - const picked = choices.filter(({ value }) => selected.has(value)); - - return ( -
- {label} - -
- ); -} diff --git a/src/infra/web/movies.tsx b/src/infra/web/movies.tsx index 978641c..e742211 100644 --- a/src/infra/web/movies.tsx +++ b/src/infra/web/movies.tsx @@ -1,8 +1,9 @@ +import { Input, Textarea, ActionButton } from './ui'; import { Hono } from 'hono'; import type { MovieSuggestion } from '~/core/ports'; import { movieLabel, movieLinks } from '~/domain'; import { back, field, flashOf, owns, type Env, type WebDeps } from './context'; -import { ActionButton, Layout } from './layout'; +import { Layout } from './layout'; const linksOf = (value: string | undefined) => (value ?? '').split('\n').filter((line) => line.trim() !== ''); @@ -111,27 +112,22 @@ export function moviePages({ guildId, services, directory }: WebDeps) { >
- - -
- - + + - + {preview} -
+ {actions .filter(([, , , needs]) => needs === undefined || can.has(needs)) .map(([value, label, variant]) => ( @@ -123,7 +123,7 @@ function Composer({ {label} ))} -
+ ); } diff --git a/src/infra/web/roles.tsx b/src/infra/web/roles.tsx index 03d5549..fec44f7 100644 --- a/src/infra/web/roles.tsx +++ b/src/infra/web/roles.tsx @@ -1,7 +1,9 @@ +import { Select } from './ui'; import { Hono } from 'hono'; import { selfAssignProblem, UserError } from '~/domain'; import { back, field, flashOf, type Env, type WebDeps } from './context'; -import { ChannelSelect, Layout } from './layout'; +import { Layout } from './layout'; +import { ChannelSelect } from './selectors'; const emojis = [ '1️⃣', @@ -209,17 +211,14 @@ export function rolePages({ services }: WebDeps) {
Add a role
- +
- - - - - - - - - - - {list.map((a) => ( - - - - - - - - - ))} - -
#StatusChannelTitleWhen -
{a.id} - {a.status} - {a.failure === null ? null : ( - <> -
- {a.failure} - - )} -
{server.channelName(a.channelId)}{a.title ?? a.content.slice(0, 60)}{date(a.publishedAt ?? a.scheduledAt)} - {a.status === 'draft' || a.status === 'scheduled' ? ( - <> - {publisher ? ( - - ) : null} - {publisher || a.authorId === userId ? ( - - ) : null} - - ) : null} -
- ); -} - -export function psaPages({ guildId, services, timezone }: WebDeps) { - const date = formatter(timezone); - - return new Hono() - .use(async (c, next) => { - if (!allows(c, 'announcement:create')) { - throw new UserError('You need the "announcement:create" permission.'); - } - - await next(); - }) - .get('/', async (c) => { - const list = await services.announcements.list(c.var.actor); - - return c.html( - New PSA} - > - - , - ); - }) - .get('/new', (c) => - c.html( - - - , - ), - ) - .post('/', async (c) => { - const form = await c.req.formData(); - const action = form.get('action'); - const draft = draftOf(form); - const { actor, server } = c.var; - - if (action === 'preview') { - const view = services.announcements.view({ - ...draft, - title: draft.title === '' ? null : draft.title, - id: 0, - guildId, - authorId: actor.userId, - status: 'draft', - scheduledAt: null, - publishedAt: null, - messageId: null, - failure: null, - createdAt: new Date(), - }); - - return c.html( - - -

Preview

- - - } - /> -
, - ); - } - - const created = await services.announcements.draft(actor, draft); - - if (action === 'publish') { - await services.announcements.publish(actor, created.id); - - return back(c, '/post/announcements', { - notice: `PSA #${created.id} published.`, - }); - } - - if (action === 'schedule') { - const scheduled = await services.announcements.schedule( - actor, - created.id, - field(form, 'when') ?? '', - ); - - return back(c, '/post/announcements', { - notice: `PSA #${created.id} scheduled for ${date(scheduled.scheduledAt)}.`, - }); - } - - return back(c, '/post/announcements', { - notice: `Draft #${created.id} saved.`, - }); - }) - .post(String.raw`/:id{\d+}/publish`, async (c) => { - const id = Number(c.req.param('id')); - - await services.announcements.publish(c.var.actor, id); - - return back(c, '/post/announcements', { - notice: `PSA #${id} published.`, - }); - }) - .post(String.raw`/:id{\d+}/cancel`, async (c) => { - const id = Number(c.req.param('id')); - - await services.announcements.cancel(c.var.actor, id); - - return back(c, '/post/announcements', { - notice: `PSA #${id} cancelled.`, - }); - }); -} diff --git a/src/web/pages/post/events.tsx b/src/web/pages/post/events.tsx deleted file mode 100644 index d788ed7..0000000 --- a/src/web/pages/post/events.tsx +++ /dev/null @@ -1,288 +0,0 @@ -import { Input, Select, Textarea } from '~/web/components/controls'; -import { ActionButton } from '~/web/components/actions'; -import { Checkbox } from '~/web/components/choices'; -import { visibleRecords } from '~/core/helpers/visibility'; -import { Hono } from 'hono'; -import type { Event } from '~/features/events/model'; -import { reminderChoices } from '~/features/events/service'; -import { UserError } from '~/core/errors'; -import { - allows, - back, - checked, - field, - flashOf, - formatter, - inputTime, - owns, - type Env, - type Form, - type WebDeps, -} from '~/web/context'; -import { Layout } from '~/web/layout'; -import { ChannelSelect } from '~/web/components/selectors'; - -const textFields = [ - 'title', - 'start', - 'end', - 'description', - 'location', -] as const; - -function EventFields({ - event, - time, -}: Readonly<{ event?: Event; time: (date: Date | null) => string }>) { - return ( - <> - -
- - -
- -
- - -
- - ); -} - -function fieldsOf(form: Form) { - const capacity = field(form, 'capacity'); - - return { - ...Object.fromEntries( - textFields.flatMap((name) => { - const value = field(form, name); - - return value === undefined ? [] : [[name, value]]; - }), - ), - icons: checked(form, 'icons'), - ...(capacity !== undefined && { capacity: Number(capacity) }), - }; -} - -function changesOf(form: Form) { - const capacity = field(form, 'capacity'); - - return { - ...fieldsOf(form), - ...(form.has('description') && { - description: field(form, 'description') ?? null, - }), - ...(form.has('location') && { location: field(form, 'location') ?? null }), - ...(form.has('end') && { end: field(form, 'end') ?? null }), - ...(form.has('capacity') && { - capacity: capacity === undefined ? null : Number(capacity), - }), - }; -} - -export function eventPages({ - guildId, - services, - timezone, - directory, -}: WebDeps) { - const date = formatter(timezone); - const time = inputTime(timezone); - - return new Hono() - .get('/', async (c) => { - const upcoming = await visibleRecords( - directory, - c.var.actor, - await services.events.upcoming(guildId), - ); - const { server } = c.var; - - return c.html( - New event - ) : null - } - > - - - - - - - - - - - {upcoming.map((e) => ( - - - - - - - - ))} - -
#TitleStartsChannel -
{e.id}{e.title}{date(e.startsAt)}{server.channelName(e.channelId)} - {owns(c, e.organizerId, 'event:manage') ? ( - <> - - Edit - {' '} - - - ) : null} -
-
, - ); - }) - .get('/new', (c) => { - if (!allows(c, 'event:create')) { - throw new UserError('You need the "event:create" permission.'); - } - - const { server } = c.var; - - return c.html( - -
- -
- - -
-
- - -
- - -
, - ); - }) - .post('/', async (c) => { - const form = await c.req.formData(); - const reminders = field(form, 'reminders'); - const event = await services.events.create(c.var.actor, { - title: '', - start: '', - ...fieldsOf(form), - channelId: field(form, 'channelId') ?? '', - native: checked(form, 'native'), - ...(reminders !== undefined && { reminders }), - }); - - return back(c, '/post/events', { notice: `Event #${event.id} created.` }); - }) - .get('/:id{\\d+}', async (c) => { - const event = await services.events.get( - c.var.actor, - Number(c.req.param('id')), - ); - - if (!owns(c, event.organizerId, 'event:manage')) { - throw new UserError('Only the organizer can edit this event.'); - } - - return c.html( - -
- -
- -
- - -
, - ); - }) - .post('/:id{\\d+}', async (c) => { - const id = Number(c.req.param('id')); - - await services.events.edit( - c.var.actor, - id, - changesOf(await c.req.formData()), - ); - - return back(c, '/post/events', { notice: `Event #${id} updated.` }); - }) - .post('/:id{\\d+}/cancel', async (c) => { - const id = Number(c.req.param('id')); - - await services.events.cancel(c.var.actor, id); - - return back(c, '/post/events', { notice: `Event #${id} cancelled.` }); - }); -} diff --git a/src/web/pages/post/polls.tsx b/src/web/pages/post/polls.tsx deleted file mode 100644 index b26c2ad..0000000 --- a/src/web/pages/post/polls.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import { Input, Select, Textarea } from '~/web/components/controls'; -import { ActionButton } from '~/web/components/actions'; -import { Checkbox } from '~/web/components/choices'; -import { visibleRecords } from '~/core/helpers/visibility'; -import { Hono } from 'hono'; -import { UserError } from '~/core/errors'; -import { - allows, - back, - checked, - field, - flashOf, - formatter, - owns, - type Env, - type WebDeps, -} from '~/web/context'; -import { Layout } from '~/web/layout'; -import { ChannelSelect } from '~/web/components/selectors'; - -export function pollPages({ guildId, services, timezone, directory }: WebDeps) { - const date = formatter(timezone); - - return new Hono() - .get('/', async (c) => { - const open = await visibleRecords( - directory, - c.var.actor, - await services.polls.open(guildId), - ); - - return c.html( - New poll - ) : null - } - > - - - - - - - - - - {open.map((p) => ( - - - - - - - ))} - -
#QuestionCloses -
{p.id}{p.question}{date(p.closesAt)} - {owns(c, p.creatorId, 'poll:manage') ? ( - <> - - - ) : null} -
-
, - ); - }) - .get('/new', (c) => { - if (!allows(c, 'poll:create')) { - throw new UserError('You need the "poll:create" permission.'); - } - - return c.html( - -
- - + + + {preview} + + {actions + .filter(([, , , needs]) => needs === undefined || can.has(needs)) + .map(([value, label, variant]) => ( + + ))} + + + ); +} diff --git a/src/web/post/announcements/index.tsx b/src/web/post/announcements/index.tsx new file mode 100644 index 0000000..13e834c --- /dev/null +++ b/src/web/post/announcements/index.tsx @@ -0,0 +1,43 @@ +import type { Permission } from '~/core/permission'; +import type { Announcement } from '~/features/announcements/model'; +import type { Flash, Server } from '~/web/context'; +import { Layout } from '~/web/layout'; +import { Recent } from './list'; + +const title = 'Announcements'; + +interface Props { + readonly list: Announcement[]; + readonly server: Server; + readonly date: (value: Date | null) => string; + readonly can: ReadonlySet; + readonly userId: string; + readonly flash: Flash; +} + +export function AnnouncementPage({ + list, + server, + date, + can, + userId, + flash, +}: Props) { + return ( + New PSA} + > + + + ); +} diff --git a/src/web/post/announcements/list.tsx b/src/web/post/announcements/list.tsx new file mode 100644 index 0000000..5d27b95 --- /dev/null +++ b/src/web/post/announcements/list.tsx @@ -0,0 +1,72 @@ +import type { Permission } from '~/core/permission'; +import type { Announcement } from '~/features/announcements/model'; +import { ActionButton } from '~/web/components/actions'; +import { type Server } from '~/web/context'; + +export function Recent({ + list, + server, + date, + can, + userId, +}: Readonly<{ + list: Announcement[]; + server: Server; + date: (value: Date | null) => string; + can: ReadonlySet; + userId: string; +}>) { + const publisher = can.has('announcement:publish'); + + return ( + + + + + + + + + + + + {list.map((a) => ( + + + + + + + + + ))} + +
#StatusChannelTitleWhen +
{a.id} + {a.status} + {a.failure === null ? null : ( + <> +
+ {a.failure} + + )} +
{server.channelName(a.channelId)}{a.title ?? a.content.slice(0, 60)}{date(a.publishedAt ?? a.scheduledAt)} + {a.status === 'draft' || a.status === 'scheduled' ? ( + <> + {publisher ? ( + + ) : null} + {publisher || a.authorId === userId ? ( + + ) : null} + + ) : null} +
+ ); +} diff --git a/src/web/post/announcements/mentions.tsx b/src/web/post/announcements/mentions.tsx new file mode 100644 index 0000000..4e02281 --- /dev/null +++ b/src/web/post/announcements/mentions.tsx @@ -0,0 +1,30 @@ +import { MultiSelect } from '~/web/components/choices'; +import { type Server } from '~/web/context'; +import type { Draft } from './submission'; + +export function MentionPicker({ + server, + draft, +}: Readonly<{ server: Server; draft: Draft | undefined }>) { + const roles = server.roles.filter((role) => !role.everyone && !role.managed); + const selected = new Set([ + ...(draft?.mentionEveryone === true ? ['1'] : []), + ...(draft?.mentionRoleIds ?? []), + ]); + + return ( + ({ + name: 'role', + value: id, + label: `@${name}`, + })), + ]} + /> + ); +} diff --git a/src/web/post/announcements/preview.tsx b/src/web/post/announcements/preview.tsx new file mode 100644 index 0000000..41d3dc1 --- /dev/null +++ b/src/web/post/announcements/preview.tsx @@ -0,0 +1,32 @@ +import type { Message } from '~/core/message'; +import type { Permission } from '~/core/permission'; +import { MessagePreview } from '~/web/components/preview'; +import { type Server } from '~/web/context'; +import { Layout } from '~/web/layout'; +import { Composer } from './form'; +import type { Draft } from './submission'; + +interface Props { + readonly server: Server; + readonly can: ReadonlySet; + readonly draft: Draft; + readonly view: Message; +} + +export function AnnouncementPreviewPage({ server, can, draft, view }: Props) { + return ( + + +

Preview

+ + + } + /> +
+ ); +} diff --git a/src/web/post/announcements/routes.tsx b/src/web/post/announcements/routes.tsx new file mode 100644 index 0000000..532cd7d --- /dev/null +++ b/src/web/post/announcements/routes.tsx @@ -0,0 +1,126 @@ +import { Hono } from 'hono'; +import { UserError } from '~/core/errors'; +import { + allows, + back, + field, + flashOf, + formatter, + type Env, + type WebDeps, +} from '~/web/context'; +import { NewAnnouncementPage } from './create'; +import { AnnouncementPage } from './index'; +import { AnnouncementPreviewPage } from './preview'; +import { draftOf } from './submission'; + +export function announcementRoutes({ guildId, services, timezone }: WebDeps) { + const date = formatter(timezone); + + return new Hono() + .use(async (c, next) => { + if (!allows(c, 'announcement:create')) { + throw new UserError('You need the "announcement:create" permission.'); + } + + await next(); + }) + .get('/', async (c) => { + const list = await services.announcements.list(c.var.actor); + + return c.html( + , + ); + }) + .get('/new', (c) => + c.html( + , + ), + ) + .post('/', async (c) => { + const form = await c.req.formData(); + const action = form.get('action'); + const draft = draftOf(form); + const { actor } = c.var; + + if (action === 'preview') { + const view = services.announcements.view({ + ...draft, + title: draft.title === '' ? null : draft.title, + id: 0, + guildId, + authorId: actor.userId, + status: 'draft', + scheduledAt: null, + publishedAt: null, + messageId: null, + failure: null, + createdAt: new Date(), + }); + + return c.html( + , + ); + } + + const created = await services.announcements.draft(actor, draft); + + if (action === 'publish') { + await services.announcements.publish(actor, created.id); + + return back(c, '/post/announcements', { + notice: `PSA #${created.id} published.`, + }); + } + + if (action === 'schedule') { + const scheduled = await services.announcements.schedule( + actor, + created.id, + field(form, 'when') ?? '', + ); + + return back(c, '/post/announcements', { + notice: `PSA #${created.id} scheduled for ${date(scheduled.scheduledAt)}.`, + }); + } + + return back(c, '/post/announcements', { + notice: `Draft #${created.id} saved.`, + }); + }) + .post(String.raw`/:id{\d+}/publish`, async (c) => { + const id = Number(c.req.param('id')); + + await services.announcements.publish(c.var.actor, id); + + return back(c, '/post/announcements', { + notice: `PSA #${id} published.`, + }); + }) + .post(String.raw`/:id{\d+}/cancel`, async (c) => { + const id = Number(c.req.param('id')); + + await services.announcements.cancel(c.var.actor, id); + + return back(c, '/post/announcements', { + notice: `PSA #${id} cancelled.`, + }); + }); +} diff --git a/src/web/post/announcements/submission.ts b/src/web/post/announcements/submission.ts new file mode 100644 index 0000000..630049c --- /dev/null +++ b/src/web/post/announcements/submission.ts @@ -0,0 +1,16 @@ +import { checked, field, type Form } from '~/web/context'; + +export function draftOf(form: Form) { + const content = form.get('content'); + + return { + when: field(form, 'when') ?? '', + channelId: field(form, 'channelId') ?? '', + title: field(form, 'title') ?? '', + content: typeof content === 'string' ? content : '', + mentionRoleIds: form.getAll('role').map(String), + mentionEveryone: checked(form, 'everyone'), + }; +} + +export type Draft = ReturnType; diff --git a/src/web/post/events/create.tsx b/src/web/post/events/create.tsx new file mode 100644 index 0000000..f9c2f7d --- /dev/null +++ b/src/web/post/events/create.tsx @@ -0,0 +1,40 @@ +import type { Permission } from '~/core/permission'; +import { reminderChoices } from '~/features/events/service'; +import { Checkbox } from '~/web/components/choices'; +import { Select } from '~/web/components/controls'; +import { ChannelSelect } from '~/web/components/selectors'; +import type { Flash, Server } from '~/web/context'; +import { Layout } from '~/web/layout'; +import { EventFields } from './fields'; + +interface Props { + readonly time: (value: Date | null) => string; + readonly server: Server; + readonly can: ReadonlySet; + readonly flash: Flash; +} + +export function NewEventPage({ time, server, can, flash }: Props) { + return ( + +
+ +
+ + +
+
+ + +
+ + +
+ ); +} diff --git a/src/web/post/events/edit.tsx b/src/web/post/events/edit.tsx new file mode 100644 index 0000000..ad6b481 --- /dev/null +++ b/src/web/post/events/edit.tsx @@ -0,0 +1,36 @@ +import type { Permission } from '~/core/permission'; +import type { Event } from '~/features/events/model'; +import { Checkbox } from '~/web/components/choices'; +import type { Flash } from '~/web/context'; +import { Layout } from '~/web/layout'; +import { EventFields } from './fields'; + +interface Props { + readonly event: Event; + readonly time: (value: Date | null) => string; + readonly can: ReadonlySet; + readonly flash: Flash; +} + +export function EditEventPage({ event, time, can, flash }: Props) { + return ( + +
+ +
+ +
+ + +
+ ); +} diff --git a/src/web/post/events/fields.tsx b/src/web/post/events/fields.tsx new file mode 100644 index 0000000..25a2edf --- /dev/null +++ b/src/web/post/events/fields.tsx @@ -0,0 +1,57 @@ +import type { Event } from '~/features/events/model'; +import { Input, Textarea } from '~/web/components/controls'; + +export function EventFields({ + event, + time, +}: Readonly<{ event?: Event; time: (date: Date | null) => string }>) { + return ( + <> + +
+ + +
+ +
+ + +
+ + ); +} diff --git a/src/web/post/events/index.tsx b/src/web/post/events/index.tsx new file mode 100644 index 0000000..05db13b --- /dev/null +++ b/src/web/post/events/index.tsx @@ -0,0 +1,44 @@ +import type { Permission } from '~/core/permission'; +import type { Event } from '~/features/events/model'; +import type { Flash, Server } from '~/web/context'; +import { Layout } from '~/web/layout'; +import { EventList } from './list'; + +interface Props { + readonly upcoming: Event[]; + readonly date: (value: Date | null) => string; + readonly server: Server; + readonly can: ReadonlySet; + readonly flash: Flash; + readonly canManage: (ownerId: string) => boolean; +} + +export function EventPage({ + upcoming, + date, + server, + can, + flash, + canManage, +}: Props) { + return ( + New event + ) : null + } + > + + + ); +} diff --git a/src/web/post/events/list.tsx b/src/web/post/events/list.tsx new file mode 100644 index 0000000..e31241a --- /dev/null +++ b/src/web/post/events/list.tsx @@ -0,0 +1,48 @@ +import type { Event } from '~/features/events/model'; +import { ActionButton } from '~/web/components/actions'; +import type { Server } from '~/web/context'; + +interface Props { + readonly upcoming: Event[]; + readonly date: (value: Date | null) => string; + readonly server: Server; + readonly canManage: (ownerId: string) => boolean; +} +export function EventList({ upcoming, date, server, canManage }: Props) { + return ( + + + + + + + + + + + {upcoming.map((e) => ( + + + + + + + + ))} + +
#TitleStartsChannel +
{e.id}{e.title}{date(e.startsAt)}{server.channelName(e.channelId)} + {canManage(e.organizerId) ? ( + <> + + Edit + {' '} + + + ) : null} +
+ ); +} diff --git a/src/web/post/events/routes.tsx b/src/web/post/events/routes.tsx new file mode 100644 index 0000000..3be781c --- /dev/null +++ b/src/web/post/events/routes.tsx @@ -0,0 +1,114 @@ +import { Hono } from 'hono'; +import { UserError } from '~/core/errors'; +import { visibleRecords } from '~/core/helpers/visibility'; +import { + allows, + back, + checked, + field, + flashOf, + formatter, + inputTime, + owns, + type Env, + type WebDeps, +} from '~/web/context'; +import { NewEventPage } from './create'; +import { EditEventPage } from './edit'; +import { EventPage } from './index'; +import { changesOf, fieldsOf } from './submission'; + +export function eventRoutes({ + guildId, + services, + timezone, + directory, +}: WebDeps) { + const date = formatter(timezone); + const time = inputTime(timezone); + + return new Hono() + .get('/', async (c) => { + const upcoming = await visibleRecords( + directory, + c.var.actor, + await services.events.upcoming(guildId), + ); + + return c.html( + owns(c, ownerId, 'event:manage')} + />, + ); + }) + .get('/new', (c) => { + if (!allows(c, 'event:create')) { + throw new UserError('You need the "event:create" permission.'); + } + + return c.html( + , + ); + }) + .post('/', async (c) => { + const form = await c.req.formData(); + const reminders = field(form, 'reminders'); + const event = await services.events.create(c.var.actor, { + title: '', + start: '', + ...fieldsOf(form), + channelId: field(form, 'channelId') ?? '', + native: checked(form, 'native'), + ...(reminders !== undefined && { reminders }), + }); + + return back(c, '/post/events', { notice: `Event #${event.id} created.` }); + }) + .get('/:id{\\d+}', async (c) => { + const event = await services.events.get( + c.var.actor, + Number(c.req.param('id')), + ); + + if (!owns(c, event.organizerId, 'event:manage')) { + throw new UserError('Only the organizer can edit this event.'); + } + + return c.html( + , + ); + }) + .post('/:id{\\d+}', async (c) => { + const id = Number(c.req.param('id')); + + await services.events.edit( + c.var.actor, + id, + changesOf(await c.req.formData()), + ); + + return back(c, '/post/events', { notice: `Event #${id} updated.` }); + }) + .post('/:id{\\d+}/cancel', async (c) => { + const id = Number(c.req.param('id')); + + await services.events.cancel(c.var.actor, id); + + return back(c, '/post/events', { notice: `Event #${id} cancelled.` }); + }); +} diff --git a/src/web/post/events/submission.ts b/src/web/post/events/submission.ts new file mode 100644 index 0000000..a2452ce --- /dev/null +++ b/src/web/post/events/submission.ts @@ -0,0 +1,41 @@ +import { checked, field, type Form } from '~/web/context'; + +export const textFields = [ + 'title', + 'start', + 'end', + 'description', + 'location', +] as const; + +export function fieldsOf(form: Form) { + const capacity = field(form, 'capacity'); + + return { + ...Object.fromEntries( + textFields.flatMap((name) => { + const value = field(form, name); + + return value === undefined ? [] : [[name, value]]; + }), + ), + icons: checked(form, 'icons'), + ...(capacity !== undefined && { capacity: Number(capacity) }), + }; +} + +export function changesOf(form: Form) { + const capacity = field(form, 'capacity'); + + return { + ...fieldsOf(form), + ...(form.has('description') && { + description: field(form, 'description') ?? null, + }), + ...(form.has('location') && { location: field(form, 'location') ?? null }), + ...(form.has('end') && { end: field(form, 'end') ?? null }), + ...(form.has('capacity') && { + capacity: capacity === undefined ? null : Number(capacity), + }), + }; +} diff --git a/src/web/post/polls/create.tsx b/src/web/post/polls/create.tsx new file mode 100644 index 0000000..a2e696a --- /dev/null +++ b/src/web/post/polls/create.tsx @@ -0,0 +1,18 @@ +import type { Permission } from '~/core/permission'; +import type { Flash, Server } from '~/web/context'; +import { Layout } from '~/web/layout'; +import { PollForm } from './form'; + +interface Props { + readonly server: Server; + readonly can: ReadonlySet; + readonly flash: Flash; +} + +export function NewPollPage({ server, can, flash }: Props) { + return ( + + + + ); +} diff --git a/src/web/post/polls/form.tsx b/src/web/post/polls/form.tsx new file mode 100644 index 0000000..00d3401 --- /dev/null +++ b/src/web/post/polls/form.tsx @@ -0,0 +1,38 @@ +import { Checkbox } from '~/web/components/choices'; +import { Input, Select, Textarea } from '~/web/components/controls'; +import { ChannelSelect } from '~/web/components/selectors'; +import type { Server } from '~/web/context'; + +interface Props { + readonly server: Server; +} +export function PollForm({ server }: Props) { + return ( +
+ +