@meith/polls 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@meith/polls",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/polls"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "files": [
14
+ "src",
15
+ "!src/**/*.test.*",
16
+ "!src/**/*.type-test.*"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "dependencies": {
22
+ "@meith/i18n": "0.16.0",
23
+ "@meith/core": "0.16.0"
24
+ }
25
+ }
package/src/index.ts ADDED
@@ -0,0 +1,27 @@
1
+ export {
2
+ POLL_CHOICES_UNLIMITED,
3
+ POLL_OPTION_LENGTH_MAX,
4
+ POLL_OPTION_MAX,
5
+ POLL_QUESTION_MAX,
6
+ POLL_VOTERS_SHOWN_MAX,
7
+ PollService,
8
+ planPollEdit,
9
+ ThreadRatingService,
10
+ validatePoll,
11
+ } from './service'
12
+ export type {
13
+ NewPoll,
14
+ Poll,
15
+ PollEdit,
16
+ PollEditCapabilities,
17
+ PollEditOption,
18
+ PollEditPlan,
19
+ PollOption,
20
+ PollRepository,
21
+ PollSettings,
22
+ PollVote,
23
+ PollVoter,
24
+ ThreadRating,
25
+ ThreadRatingRepository,
26
+ ValidatedPoll,
27
+ } from './types'
package/src/service.ts ADDED
@@ -0,0 +1,231 @@
1
+ import { ForbiddenError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+
4
+ import type {
5
+ NewPoll,
6
+ Poll,
7
+ PollEdit,
8
+ PollEditCapabilities,
9
+ PollEditOption,
10
+ PollEditPlan,
11
+ PollRepository,
12
+ PollSettings,
13
+ ThreadRating,
14
+ ThreadRatingRepository,
15
+ ValidatedPoll,
16
+ } from './types'
17
+
18
+ export const POLL_QUESTION_MAX = 250
19
+ export const POLL_OPTION_MAX = 20
20
+ export const POLL_OPTION_LENGTH_MAX = 200
21
+ export const POLL_CHOICES_UNLIMITED = 0
22
+ export const POLL_VOTERS_SHOWN_MAX = 50
23
+
24
+ function trimmedQuestion(question: string): string {
25
+ const trimmed = question.trim()
26
+ if (trimmed.length === 0 || trimmed.length > POLL_QUESTION_MAX) {
27
+ throw new ValidationError(msg('error.polls.question-length', { max: POLL_QUESTION_MAX }))
28
+ }
29
+ return trimmed
30
+ }
31
+
32
+ function checkLabels(labels: readonly string[]): void {
33
+ if (labels.length < 2 || labels.length > POLL_OPTION_MAX) {
34
+ throw new ValidationError(msg('error.polls.option-count', { max: POLL_OPTION_MAX }))
35
+ }
36
+ if (labels.some((label) => label.length > POLL_OPTION_LENGTH_MAX)) {
37
+ throw new ValidationError(msg('error.polls.option-length', { max: POLL_OPTION_LENGTH_MAX }))
38
+ }
39
+ if (new Set(labels.map((label) => label.toLowerCase())).size !== labels.length) {
40
+ throw new ValidationError(msg('error.polls.poll-options-must-distinct'))
41
+ }
42
+ }
43
+
44
+ function checkClosesAt(closesAt: Date | null, now: Date): void {
45
+ if (closesAt !== null && closesAt <= now) {
46
+ throw new ValidationError(msg('error.polls.poll-must-close-future'))
47
+ }
48
+ }
49
+
50
+ function pollSettings(
51
+ input: {
52
+ readonly maxOptions?: number | undefined
53
+ readonly allowRevote?: boolean | undefined
54
+ readonly publicVotes?: boolean | undefined
55
+ },
56
+ optionCount: number,
57
+ ): PollSettings {
58
+ const maxOptions = input.maxOptions ?? 1
59
+ if (!Number.isInteger(maxOptions) || maxOptions < 0 || maxOptions > optionCount) {
60
+ throw new ValidationError(msg('error.polls.choice-limit', { max: optionCount }))
61
+ }
62
+ return {
63
+ maxOptions,
64
+ allowRevote: input.allowRevote ?? false,
65
+ publicVotes: input.publicVotes ?? false,
66
+ }
67
+ }
68
+
69
+ export function validatePoll(input: NewPoll, now = new Date()): ValidatedPoll {
70
+ const question = trimmedQuestion(input.question)
71
+ const options = input.options.map((option) => option.trim()).filter(Boolean)
72
+ checkLabels(options)
73
+ checkClosesAt(input.closesAt, now)
74
+ return { question, options, closesAt: input.closesAt, ...pollSettings(input, options.length) }
75
+ }
76
+
77
+ export function planPollEdit(poll: Poll, edit: PollEdit, now = new Date()): PollEditPlan {
78
+ const question = trimmedQuestion(edit.question)
79
+ const existing = new Map(poll.options.map((option) => [option.id, option]))
80
+ const options: PollEditOption[] = []
81
+ const kept = new Set<number>()
82
+
83
+ for (const option of edit.options) {
84
+ const label = option.label.trim()
85
+ if (label === '') continue
86
+ if (option.id === null) {
87
+ options.push({ id: null, label })
88
+ continue
89
+ }
90
+ if (!existing.has(option.id)) {
91
+ throw new ValidationError(msg('error.polls.option-not-on-poll'))
92
+ }
93
+ if (kept.has(option.id)) {
94
+ throw new ValidationError(msg('error.polls.poll-options-must-distinct'))
95
+ }
96
+ kept.add(option.id)
97
+ options.push({ id: option.id, label })
98
+ }
99
+
100
+ checkLabels(options.map((option) => option.label))
101
+
102
+ const removedOptionIds = poll.options
103
+ .filter((option) => !kept.has(option.id))
104
+ .map((option) => option.id)
105
+ if (removedOptionIds.some((id) => (existing.get(id)?.votes ?? 0) > 0)) {
106
+ throw new ValidationError(msg('error.polls.remove-voted-option'))
107
+ }
108
+
109
+ if (edit.closesAt?.getTime() !== poll.closesAt?.getTime()) checkClosesAt(edit.closesAt, now)
110
+
111
+ const settings = pollSettings(edit, options.length)
112
+ const cast = poll.options.reduce((sum, option) => sum + option.votes, 0)
113
+ if (settings.publicVotes && !poll.publicVotes && cast > 0) {
114
+ throw new ValidationError(msg('error.polls.public-after-voting'))
115
+ }
116
+
117
+ return {
118
+ pollId: poll.id,
119
+ question,
120
+ closesAt: edit.closesAt,
121
+ options,
122
+ removedOptionIds,
123
+ ...settings,
124
+ }
125
+ }
126
+
127
+ export class PollService {
128
+ constructor(
129
+ private readonly polls: PollRepository,
130
+ private readonly now: () => Date = () => new Date(),
131
+ ) {}
132
+
133
+ async attach(threadId: number, poll: NewPoll): Promise<void> {
134
+ await this.polls.create(threadId, validatePoll(poll, this.now()))
135
+ }
136
+
137
+ async vote(input: {
138
+ readonly threadId: number
139
+ readonly pollId: number
140
+ readonly optionIds: readonly number[]
141
+ readonly userId: number
142
+ readonly mayVote: boolean
143
+ }): Promise<void> {
144
+ if (!input.mayVote) throw new ForbiddenError(msg('error.polls.vote-polls'))
145
+
146
+ const poll = await this.load(input.threadId, input.pollId, input.userId)
147
+ if (poll.closesAt !== null && poll.closesAt <= this.now()) {
148
+ throw new ValidationError(msg('error.polls.poll-closed'))
149
+ }
150
+ if (poll.votedOptionIds.length > 0 && !poll.allowRevote) {
151
+ throw new ValidationError(msg('error.polls.already-voted'))
152
+ }
153
+
154
+ const chosen = [...new Set(input.optionIds)]
155
+ if (chosen.length === 0) throw new ValidationError(msg('error.polls.choose-option'))
156
+
157
+ const available = new Set(poll.options.map((option) => option.id))
158
+ if (chosen.some((id) => !available.has(id))) {
159
+ throw new ValidationError(msg('error.polls.option-not-on-poll'))
160
+ }
161
+ if (poll.maxOptions !== POLL_CHOICES_UNLIMITED && chosen.length > poll.maxOptions) {
162
+ throw new ValidationError(msg('error.polls.choose-at-most', { max: poll.maxOptions }))
163
+ }
164
+
165
+ const stored = await this.polls.vote({
166
+ threadId: input.threadId,
167
+ pollId: input.pollId,
168
+ optionIds: chosen,
169
+ userId: input.userId,
170
+ })
171
+ if (!stored) throw new ValidationError(msg('error.polls.poll-closed-already-voted'))
172
+ }
173
+
174
+ async edit(input: {
175
+ readonly threadId: number
176
+ readonly pollId: number
177
+ readonly edit: PollEdit
178
+ readonly capabilities: PollEditCapabilities
179
+ }): Promise<void> {
180
+ const { capabilities } = input
181
+ if (!capabilities.isAuthor && !capabilities.mayEditOthers) {
182
+ throw new ForbiddenError(msg('error.polls.edit-poll'))
183
+ }
184
+
185
+ const poll = await this.load(input.threadId, input.pollId, null)
186
+ this.enforceEditWindow(poll, capabilities)
187
+
188
+ if (!(await this.polls.applyEdit(planPollEdit(poll, input.edit, this.now())))) {
189
+ throw new ValidationError(msg('error.polls.poll-exist'))
190
+ }
191
+ }
192
+
193
+ private async load(threadId: number, pollId: number, userId: number | null): Promise<Poll> {
194
+ const poll = await this.polls.find(threadId, userId)
195
+ if (poll === null || poll.id !== pollId) {
196
+ throw new ValidationError(msg('error.polls.poll-exist'))
197
+ }
198
+ return poll
199
+ }
200
+
201
+ private enforceEditWindow(poll: Poll, capabilities: PollEditCapabilities): void {
202
+ if (!capabilities.isAuthor || capabilities.mayEditOthers || capabilities.bypassesWindow) return
203
+ if (capabilities.editWindowMinutes <= 0) return
204
+
205
+ const elapsed = (this.now().getTime() - poll.createdAt.getTime()) / 60_000
206
+ if (elapsed <= capabilities.editWindowMinutes) return
207
+
208
+ throw new ValidationError(
209
+ msg('error.polls.edit-window', { minutes: capabilities.editWindowMinutes }),
210
+ )
211
+ }
212
+ }
213
+
214
+ export class ThreadRatingService {
215
+ constructor(private readonly ratings: ThreadRatingRepository) {}
216
+
217
+ async rate(input: {
218
+ readonly threadId: number
219
+ readonly userId: number
220
+ readonly rating: number
221
+ readonly enabled: boolean
222
+ }): Promise<ThreadRating> {
223
+ if (!input.enabled) throw new ForbiddenError(msg('error.polls.thread-ratings-switched-off'))
224
+ if (!Number.isInteger(input.rating) || input.rating < 1 || input.rating > 5) {
225
+ throw new ValidationError(msg('error.polls.choose-rating-from-1-5'))
226
+ }
227
+ const result = await this.ratings.rate(input)
228
+ if (result === null) throw new ValidationError(msg('error.polls.thread-exist'))
229
+ return result
230
+ }
231
+ }
package/src/types.ts ADDED
@@ -0,0 +1,101 @@
1
+ export interface PollSettings {
2
+ readonly maxOptions: number
3
+ readonly allowRevote: boolean
4
+ readonly publicVotes: boolean
5
+ }
6
+
7
+ export interface NewPoll {
8
+ readonly question: string
9
+ readonly options: readonly string[]
10
+ readonly closesAt: Date | null
11
+ readonly maxOptions?: number | undefined
12
+ readonly allowRevote?: boolean | undefined
13
+ readonly publicVotes?: boolean | undefined
14
+ }
15
+
16
+ export interface ValidatedPoll extends PollSettings {
17
+ readonly question: string
18
+ readonly options: readonly string[]
19
+ readonly closesAt: Date | null
20
+ }
21
+
22
+ export interface PollVoter {
23
+ readonly userId: number
24
+ readonly username: string
25
+ readonly votedAt: Date | null
26
+ }
27
+
28
+ export interface PollOption {
29
+ readonly id: number
30
+ readonly label: string
31
+ readonly votes: number
32
+ readonly voters: readonly PollVoter[]
33
+ }
34
+
35
+ export interface Poll extends PollSettings {
36
+ readonly id: number
37
+ readonly threadId: number
38
+ readonly question: string
39
+ readonly closesAt: Date | null
40
+ readonly createdAt: Date
41
+ readonly options: readonly PollOption[]
42
+ readonly votedOptionIds: readonly number[]
43
+ }
44
+
45
+ export interface PollEditOption {
46
+ readonly id: number | null
47
+ readonly label: string
48
+ }
49
+
50
+ export interface PollEdit {
51
+ readonly question: string
52
+ readonly options: readonly PollEditOption[]
53
+ readonly closesAt: Date | null
54
+ readonly maxOptions?: number | undefined
55
+ readonly allowRevote?: boolean | undefined
56
+ readonly publicVotes?: boolean | undefined
57
+ }
58
+
59
+ export interface PollEditPlan extends PollSettings {
60
+ readonly pollId: number
61
+ readonly question: string
62
+ readonly closesAt: Date | null
63
+ readonly options: readonly PollEditOption[]
64
+ readonly removedOptionIds: readonly number[]
65
+ }
66
+
67
+ export interface PollVote {
68
+ readonly threadId: number
69
+ readonly pollId: number
70
+ readonly optionIds: readonly number[]
71
+ readonly userId: number
72
+ }
73
+
74
+ export interface PollEditCapabilities {
75
+ readonly isAuthor: boolean
76
+ readonly mayEditOthers: boolean
77
+ readonly editWindowMinutes: number
78
+ readonly bypassesWindow: boolean
79
+ }
80
+
81
+ export interface PollRepository {
82
+ create(threadId: number, poll: ValidatedPoll): Promise<void>
83
+ find(threadId: number, voterUserId: number | null): Promise<Poll | null>
84
+ vote(input: PollVote): Promise<boolean>
85
+ applyEdit(plan: PollEditPlan): Promise<boolean>
86
+ }
87
+
88
+ export interface ThreadRating {
89
+ readonly average: number
90
+ readonly count: number
91
+ readonly mine: number | null
92
+ }
93
+
94
+ export interface ThreadRatingRepository {
95
+ rate(input: {
96
+ readonly threadId: number
97
+ readonly userId: number
98
+ readonly rating: number
99
+ }): Promise<ThreadRating | null>
100
+ findRating(threadId: number, userId: number | null): Promise<ThreadRating | null>
101
+ }