@rothenbergt/backstage-plugin-roadmap-backend 1.0.0 → 1.0.1
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/dist/database/RoadmapDatabaseClient.cjs.js +13 -2
- package/dist/database/RoadmapDatabaseClient.cjs.js.map +1 -1
- package/dist/database/stores/FeaturesStore.cjs.js +24 -8
- package/dist/database/stores/FeaturesStore.cjs.js.map +1 -1
- package/dist/gitlab/RoadmapGitlabClient.cjs.js +75 -31
- package/dist/gitlab/RoadmapGitlabClient.cjs.js.map +1 -1
- package/dist/index.d.ts +11 -11
- package/dist/routes/commentsRouter.cjs.js +1 -1
- package/dist/routes/commentsRouter.cjs.js.map +1 -1
- package/dist/routes/featuresRouter.cjs.js +9 -3
- package/dist/routes/featuresRouter.cjs.js.map +1 -1
- package/dist/routes/votesRouter.cjs.js +15 -12
- package/dist/routes/votesRouter.cjs.js.map +1 -1
- package/dist/services/CommentService.cjs.js +4 -4
- package/dist/services/CommentService.cjs.js.map +1 -1
- package/dist/services/FeatureService.cjs.js +5 -5
- package/dist/services/FeatureService.cjs.js.map +1 -1
- package/dist/services/PermissionService.cjs.js +3 -0
- package/dist/services/PermissionService.cjs.js.map +1 -1
- package/package.json +2 -1
|
@@ -33,7 +33,7 @@ class RoadmapDatabaseClient {
|
|
|
33
33
|
this.votes = new VotesStore.VotesStore(knexInstance);
|
|
34
34
|
this.logger = logger;
|
|
35
35
|
}
|
|
36
|
-
/** Logs and normalizes store errors
|
|
36
|
+
/** Logs and normalizes store errors. NotFound passes through while anything else surfaces as an internal error. */
|
|
37
37
|
async run(operation, fn) {
|
|
38
38
|
try {
|
|
39
39
|
return await fn();
|
|
@@ -44,7 +44,7 @@ class RoadmapDatabaseClient {
|
|
|
44
44
|
this.logger.error(`Error during ${operation}`, {
|
|
45
45
|
error: String(error)
|
|
46
46
|
});
|
|
47
|
-
throw new
|
|
47
|
+
throw new Error(`Failed to ${operation}`, { cause: error });
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
async addComment(comment) {
|
|
@@ -102,6 +102,7 @@ class RoadmapDatabaseClient {
|
|
|
102
102
|
);
|
|
103
103
|
}
|
|
104
104
|
async getVoteCount(featureId) {
|
|
105
|
+
await this.requireFeatureExists(featureId);
|
|
105
106
|
const counts = await this.getVoteCounts([featureId]);
|
|
106
107
|
return counts[featureId] || 0;
|
|
107
108
|
}
|
|
@@ -109,11 +110,21 @@ class RoadmapDatabaseClient {
|
|
|
109
110
|
return this.run("get vote counts", () => this.votes.getCounts(featureIds));
|
|
110
111
|
}
|
|
111
112
|
async hasVoted(featureId, voter) {
|
|
113
|
+
await this.requireFeatureExists(featureId);
|
|
112
114
|
return this.run(
|
|
113
115
|
`check if user ${voter} has voted on feature ${featureId}`,
|
|
114
116
|
() => this.votes.hasVoted(featureId, voter)
|
|
115
117
|
);
|
|
116
118
|
}
|
|
119
|
+
async requireFeatureExists(featureId) {
|
|
120
|
+
const exists = await this.run(
|
|
121
|
+
`check feature ${featureId} exists`,
|
|
122
|
+
() => this.features.exists(featureId)
|
|
123
|
+
);
|
|
124
|
+
if (!exists) {
|
|
125
|
+
throw new errors.NotFoundError(`Feature with id ${featureId} not found`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
117
128
|
async hasVotedBatch(featureIds, voter) {
|
|
118
129
|
return this.run(
|
|
119
130
|
`check votes for user ${voter}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RoadmapDatabaseClient.cjs.js","sources":["../../src/database/RoadmapDatabaseClient.ts"],"sourcesContent":["import { Knex } from 'knex';\nimport {\n Feature,\n NewFeature,\n FeatureStatus,\n Comment,\n NewComment,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { RoadmapDatasource } from '../types';\nimport { LoggerService, DatabaseService } from '@backstage/backend-plugin-api';\nimport { NotFoundError, ConflictError } from '@backstage/errors';\nimport { resolvePackagePath } from '@backstage/backend-plugin-api';\nimport { FeaturesStore, CommentsStore, VotesStore } from './stores';\n\nconst migrationsDir = resolvePackagePath(\n '@rothenbergt/backstage-plugin-roadmap-backend',\n 'migrations',\n);\n\n/**\n * Knex-backed implementation of the RoadmapDatasource interface.\n *\n * Table access lives in the per-table stores (features/comments/votes);\n * this class aggregates them and wraps unexpected store failures in\n * ConflictError while letting NotFoundError pass through.\n */\nexport class RoadmapDatabaseClient implements RoadmapDatasource {\n static async create(options: {\n database: DatabaseService;\n logger: LoggerService;\n }): Promise<RoadmapDatabaseClient> {\n const { database, logger } = options;\n logger.info('Creating database for roadmap plugin');\n\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n logger.info('Running migrations for roadmap plugin');\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new RoadmapDatabaseClient(client, logger);\n }\n\n readonly features: FeaturesStore;\n readonly comments: CommentsStore;\n readonly votes: VotesStore;\n private readonly logger: LoggerService;\n\n constructor(knexInstance: Knex, logger: LoggerService) {\n this.features = new FeaturesStore(knexInstance);\n this.comments = new CommentsStore(knexInstance);\n this.votes = new VotesStore(knexInstance);\n this.logger = logger;\n }\n\n /** Logs and normalizes store errors: NotFound passes through, anything else becomes ConflictError. */\n private async run<T>(operation: string, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof NotFoundError) {\n throw error;\n }\n this.logger.error(`Error during ${operation}`, {\n error: String(error),\n });\n throw new ConflictError(`Failed to ${operation}`, error as Error);\n }\n }\n\n async addComment(comment: NewComment): Promise<Comment> {\n return this.run('add comment', () => this.comments.insert(comment));\n }\n\n async getCommentsByFeatureId(featureId: string): Promise<Comment[]> {\n return this.run(`get comments for feature ${featureId}`, () =>\n this.comments.getByFeatureId(featureId),\n );\n }\n\n async deleteCommentById(commentId: string): Promise<void> {\n return this.run(`delete comment ${commentId}`, () =>\n this.comments.delete(commentId),\n );\n }\n\n async addFeature(feature: NewFeature & { author: string }): Promise<Feature> {\n return this.run('add feature', () => this.features.insert(feature));\n }\n\n async getAllFeatures(): Promise<Feature[]> {\n return this.run('get all features', () => this.features.getAll());\n }\n\n async getFeatureById(id: string): Promise<Feature> {\n return this.run(`get feature with id ${id}`, () =>\n this.features.getById(id),\n );\n }\n\n async updateFeatureStatus(\n id: string,\n status: FeatureStatus,\n ): Promise<Feature> {\n return this.run(`update status for feature ${id}`, () =>\n this.features.updateStatus(id, status),\n );\n }\n\n async updateFeatureDetails(\n id: string,\n fields: { title?: string; description?: string },\n ): Promise<Feature> {\n return this.run(`update feature ${id}`, () =>\n this.features.updateDetails(id, fields),\n );\n }\n\n async deleteFeature(id: string): Promise<void> {\n return this.run(`delete feature ${id}`, () => this.features.delete(id));\n }\n\n async reorderFeaturesInStatus(\n status: FeatureStatus,\n orderedIds: string[],\n ): Promise<void> {\n return this.run('reorder features', () =>\n this.features.reorderInStatus(status, orderedIds),\n );\n }\n\n async toggleVote(\n featureId: string,\n voter: string,\n ): Promise<{ voteAdded: boolean; voteCount: number }> {\n return this.run(`toggle vote for feature ${featureId}`, () =>\n this.votes.toggle(featureId, voter),\n );\n }\n\n async getVoteCount(featureId: string): Promise<number> {\n const counts = await this.getVoteCounts([featureId]);\n return counts[featureId] || 0;\n }\n\n async getVoteCounts(featureIds: string[]): Promise<Record<string, number>> {\n return this.run('get vote counts', () => this.votes.getCounts(featureIds));\n }\n\n async hasVoted(featureId: string, voter: string): Promise<boolean> {\n return this.run(\n `check if user ${voter} has voted on feature ${featureId}`,\n () => this.votes.hasVoted(featureId, voter),\n );\n }\n\n async hasVotedBatch(\n featureIds: string[],\n voter: string,\n ): Promise<Record<string, boolean>> {\n return this.run(`check votes for user ${voter}`, () =>\n this.votes.hasVotedBatch(featureIds, voter),\n );\n }\n}\n"],"names":["resolvePackagePath","FeaturesStore","CommentsStore","VotesStore","NotFoundError","ConflictError"],"mappings":";;;;;;;;AAcA,MAAM,aAAA,GAAgBA,mCAAA;AAAA,EACpB,+CAAA;AAAA,EACA;AACF,CAAA;AASO,MAAM,qBAAA,CAA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M,KAAK,KAAA,CAAM,SAAA,CAAU,UAAU,CAAC,CAAA;AAAA,EAC3E;AAAA,EAEA,MAAM,QAAA,CAAS,SAAA,EAAmB,KAAA,EAAiC;AACjE,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,MACV,CAAA,cAAA,EAAiB,KAAK,CAAA,sBAAA,EAAyB,SAAS,CAAA,CAAA;AAAA,MACxD,MAAM,IAAA,CAAK,KAAA,CAAM,QAAA,CAAS,WAAW,KAAK;AAAA,KAC5C;AAAA,EACF;AAAA,EAEA,MAAM,aAAA,CACJ,UAAA,EACA,KAAA,EACkC;AAClC,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,MAAI,wBAAwB,KAAK,CAAA,CAAA;AAAA,MAAI,MAC/C,IAAA,CAAK,KAAA,CAAM,aAAA,CAAc,YAAY,KAAK;AAAA,KAC5C;AAAA,EACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"RoadmapDatabaseClient.cjs.js","sources":["../../src/database/RoadmapDatabaseClient.ts"],"sourcesContent":["import { Knex } from 'knex';\nimport {\n Feature,\n NewFeature,\n FeatureStatus,\n Comment,\n NewComment,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { RoadmapDatasource } from '../types';\nimport { LoggerService, DatabaseService } from '@backstage/backend-plugin-api';\nimport { NotFoundError } from '@backstage/errors';\nimport { resolvePackagePath } from '@backstage/backend-plugin-api';\nimport { FeaturesStore, CommentsStore, VotesStore } from './stores';\n\nconst migrationsDir = resolvePackagePath(\n '@rothenbergt/backstage-plugin-roadmap-backend',\n 'migrations',\n);\n\n/**\n * Knex-backed implementation of the RoadmapDatasource interface.\n *\n * Table access lives in the per-table stores (features/comments/votes).\n * This class aggregates them and wraps unexpected store failures in a\n * plain Error (surfaced as 500) while letting NotFoundError pass through.\n */\nexport class RoadmapDatabaseClient implements RoadmapDatasource {\n static async create(options: {\n database: DatabaseService;\n logger: LoggerService;\n }): Promise<RoadmapDatabaseClient> {\n const { database, logger } = options;\n logger.info('Creating database for roadmap plugin');\n\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n logger.info('Running migrations for roadmap plugin');\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new RoadmapDatabaseClient(client, logger);\n }\n\n readonly features: FeaturesStore;\n readonly comments: CommentsStore;\n readonly votes: VotesStore;\n private readonly logger: LoggerService;\n\n constructor(knexInstance: Knex, logger: LoggerService) {\n this.features = new FeaturesStore(knexInstance);\n this.comments = new CommentsStore(knexInstance);\n this.votes = new VotesStore(knexInstance);\n this.logger = logger;\n }\n\n /** Logs and normalizes store errors. NotFound passes through while anything else surfaces as an internal error. */\n private async run<T>(operation: string, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof NotFoundError) {\n throw error;\n }\n this.logger.error(`Error during ${operation}`, {\n error: String(error),\n });\n // An unexpected database failure is a server-side problem, so it\n // surfaces as a 500 instead of a misleading client error code\n throw new Error(`Failed to ${operation}`, { cause: error });\n }\n }\n\n async addComment(comment: NewComment): Promise<Comment> {\n return this.run('add comment', () => this.comments.insert(comment));\n }\n\n async getCommentsByFeatureId(featureId: string): Promise<Comment[]> {\n return this.run(`get comments for feature ${featureId}`, () =>\n this.comments.getByFeatureId(featureId),\n );\n }\n\n async deleteCommentById(commentId: string): Promise<void> {\n return this.run(`delete comment ${commentId}`, () =>\n this.comments.delete(commentId),\n );\n }\n\n async addFeature(feature: NewFeature & { author: string }): Promise<Feature> {\n return this.run('add feature', () => this.features.insert(feature));\n }\n\n async getAllFeatures(): Promise<Feature[]> {\n return this.run('get all features', () => this.features.getAll());\n }\n\n async getFeatureById(id: string): Promise<Feature> {\n return this.run(`get feature with id ${id}`, () =>\n this.features.getById(id),\n );\n }\n\n async updateFeatureStatus(\n id: string,\n status: FeatureStatus,\n ): Promise<Feature> {\n return this.run(`update status for feature ${id}`, () =>\n this.features.updateStatus(id, status),\n );\n }\n\n async updateFeatureDetails(\n id: string,\n fields: { title?: string; description?: string },\n ): Promise<Feature> {\n return this.run(`update feature ${id}`, () =>\n this.features.updateDetails(id, fields),\n );\n }\n\n async deleteFeature(id: string): Promise<void> {\n return this.run(`delete feature ${id}`, () => this.features.delete(id));\n }\n\n async reorderFeaturesInStatus(\n status: FeatureStatus,\n orderedIds: string[],\n ): Promise<void> {\n return this.run('reorder features', () =>\n this.features.reorderInStatus(status, orderedIds),\n );\n }\n\n async toggleVote(\n featureId: string,\n voter: string,\n ): Promise<{ voteAdded: boolean; voteCount: number }> {\n return this.run(`toggle vote for feature ${featureId}`, () =>\n this.votes.toggle(featureId, voter),\n );\n }\n\n async getVoteCount(featureId: string): Promise<number> {\n // Single-feature queries 404 on unknown ids in both datasources, while\n // batch queries stay lenient and simply omit unknown ids\n await this.requireFeatureExists(featureId);\n const counts = await this.getVoteCounts([featureId]);\n return counts[featureId] || 0;\n }\n\n async getVoteCounts(featureIds: string[]): Promise<Record<string, number>> {\n return this.run('get vote counts', () => this.votes.getCounts(featureIds));\n }\n\n async hasVoted(featureId: string, voter: string): Promise<boolean> {\n await this.requireFeatureExists(featureId);\n return this.run(\n `check if user ${voter} has voted on feature ${featureId}`,\n () => this.votes.hasVoted(featureId, voter),\n );\n }\n\n private async requireFeatureExists(featureId: string): Promise<void> {\n const exists = await this.run(`check feature ${featureId} exists`, () =>\n this.features.exists(featureId),\n );\n if (!exists) {\n throw new NotFoundError(`Feature with id ${featureId} not found`);\n }\n }\n\n async hasVotedBatch(\n featureIds: string[],\n voter: string,\n ): Promise<Record<string, boolean>> {\n return this.run(`check votes for user ${voter}`, () =>\n this.votes.hasVotedBatch(featureIds, voter),\n );\n }\n}\n"],"names":["resolvePackagePath","FeaturesStore","CommentsStore","VotesStore","NotFoundError"],"mappings":";;;;;;;;AAcA,MAAM,aAAA,GAAgBA,mCAAA;AAAA,EACpB,+CAAA;AAAA,EACA;AACF,CAAA;AASO,MAAM,qBAAA,CAAmD;AAAA,EAC9D,aAAa,OAAO,OAAA,EAGe;AACjC,IAAA,MA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AmB,MAAM,KAAK,KAAA,CAAM,SAAA,CAAU,UAAU,CAAC,CAAA;AAAA,EAC3E;AAAA,EAEA,MAAM,QAAA,CAAS,SAAA,EAAmB,KAAA,EAAiC;AACjE,IAAA,MAAM,IAAA,CAAK,qBAAqB,SAAS,CAAA;AACzC,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,MACV,CAAA,cAAA,EAAiB,KAAK,CAAA,sBAAA,EAAyB,SAAS,CAAA,CAAA;AAAA,MACxD,MAAM,IAAA,CAAK,KAAA,CAAM,QAAA,CAAS,WAAW,KAAK;AAAA,KAC5C;AAAA,EACF;AAAA,EAEA,MAAc,qBAAqB,SAAA,EAAkC;AACnE,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,GAAA;AAAA,MAAI,iBAAiB,SAAS,CAAA,OAAA,CAAA;AAAA,MAAW,MACjE,IAAA,CAAK,QAAA,CAAS,MAAA,CAAO,SAAS;AAAA,KAChC;AACA,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAM,IAAIA,oBAAA,CAAc,CAAA,gBAAA,EAAmB,SAAS,CAAA,UAAA,CAAY,CAAA;AAAA,IAClE;AAAA,EACF;AAAA,EAEA,MAAM,aAAA,CACJ,UAAA,EACA,KAAA,EACkC;AAClC,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,MAAI,wBAAwB,KAAK,CAAA,CAAA;AAAA,MAAI,MAC/C,IAAA,CAAK,KAAA,CAAM,aAAA,CAAc,YAAY,KAAK;AAAA,KAC5C;AAAA,EACF;AACF;;;;"}
|
|
@@ -39,14 +39,23 @@ class FeaturesStore {
|
|
|
39
39
|
return tables.mapFeatureRow(row);
|
|
40
40
|
}
|
|
41
41
|
async updateStatus(id, status) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
42
|
+
return this.knex.transaction(async (trx) => {
|
|
43
|
+
const current = await trx("features").where({ id }).first();
|
|
44
|
+
if (!current) {
|
|
45
|
+
throw new errors.NotFoundError(`Feature with id ${id} not found`);
|
|
46
|
+
}
|
|
47
|
+
const dbStatus = statusDbMapping.statusToDb(status);
|
|
48
|
+
const patch = {
|
|
49
|
+
status: dbStatus,
|
|
50
|
+
updated_at: this.knex.fn.now()
|
|
51
|
+
};
|
|
52
|
+
if (current.status !== dbStatus) {
|
|
53
|
+
const maxRow = await trx("features").where({ status: dbStatus }).max("board_position as maxp").first();
|
|
54
|
+
patch.board_position = Number(maxRow?.maxp ?? 0) + 1;
|
|
55
|
+
}
|
|
56
|
+
const [row] = await trx("features").where({ id }).update(patch).returning("*");
|
|
57
|
+
return tables.mapFeatureRow(row);
|
|
58
|
+
});
|
|
50
59
|
}
|
|
51
60
|
async updateDetails(id, fields) {
|
|
52
61
|
const patch = { updated_at: this.knex.fn.now() };
|
|
@@ -75,6 +84,13 @@ class FeaturesStore {
|
|
|
75
84
|
);
|
|
76
85
|
}
|
|
77
86
|
}
|
|
87
|
+
const omitted = await trx("features").where({ status: statusDbMapping.statusToDb(status) }).whereNotIn("id", orderedIds).orderBy([
|
|
88
|
+
{ column: "board_position", order: "asc" },
|
|
89
|
+
{ column: "created_at", order: "desc" }
|
|
90
|
+
]).select("id");
|
|
91
|
+
for (let i = 0; i < omitted.length; i += 1) {
|
|
92
|
+
await trx("features").where({ id: omitted[i].id }).update({ board_position: orderedIds.length + i });
|
|
93
|
+
}
|
|
78
94
|
});
|
|
79
95
|
}
|
|
80
96
|
async exists(id) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FeaturesStore.cjs.js","sources":["../../../src/database/stores/FeaturesStore.ts"],"sourcesContent":["import { Knex } from 'knex';\nimport {\n Feature,\n NewFeature,\n FeatureStatus,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { NotFoundError } from '@backstage/errors';\nimport { statusToDb } from '../statusDbMapping';\nimport { FeatureRow, mapFeatureRow } from '../tables';\n\n/**\n * All access to the `features` table. Returns API types only; the raw\n * snake_case rows never leave this store.\n */\nexport class FeaturesStore {\n constructor(private readonly knex: Knex) {}\n\n async insert(feature: NewFeature & { author: string }): Promise<Feature> {\n return this.knex.transaction(async trx => {\n const maxRow = await trx('features')\n .where({ status: statusToDb(FeatureStatus.Suggested) })\n .max('board_position as maxp')\n .first();\n const nextPosition =\n Number((maxRow as { maxp?: string | number })?.maxp ?? 0) + 1;\n\n const [row] = await trx<FeatureRow>('features')\n .insert({\n ...feature,\n status: statusToDb(FeatureStatus.Suggested),\n votes: 0,\n board_position: nextPosition,\n })\n .returning('*');\n return mapFeatureRow(row);\n });\n }\n\n async getAll(): Promise<Feature[]> {\n const rows = await this.knex<FeatureRow>('features')\n .orderBy([\n { column: 'status', order: 'asc' },\n { column: 'board_position', order: 'asc' },\n { column: 'created_at', order: 'desc' },\n ])\n .select('*');\n return rows.map(mapFeatureRow);\n }\n\n async getById(id: string): Promise<Feature> {\n const row = await this.knex<FeatureRow>('features').where({ id }).first();\n if (!row) {\n throw new NotFoundError(`Feature with id ${id} not found`);\n }\n return mapFeatureRow(row);\n }\n\n async updateStatus(id: string, status: FeatureStatus): Promise<Feature> {\n const
|
|
1
|
+
{"version":3,"file":"FeaturesStore.cjs.js","sources":["../../../src/database/stores/FeaturesStore.ts"],"sourcesContent":["import { Knex } from 'knex';\nimport {\n Feature,\n NewFeature,\n FeatureStatus,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { NotFoundError } from '@backstage/errors';\nimport { statusToDb } from '../statusDbMapping';\nimport { FeatureRow, mapFeatureRow } from '../tables';\n\n/**\n * All access to the `features` table. Returns API types only; the raw\n * snake_case rows never leave this store.\n */\nexport class FeaturesStore {\n constructor(private readonly knex: Knex) {}\n\n async insert(feature: NewFeature & { author: string }): Promise<Feature> {\n return this.knex.transaction(async trx => {\n const maxRow = await trx('features')\n .where({ status: statusToDb(FeatureStatus.Suggested) })\n .max('board_position as maxp')\n .first();\n const nextPosition =\n Number((maxRow as { maxp?: string | number })?.maxp ?? 0) + 1;\n\n const [row] = await trx<FeatureRow>('features')\n .insert({\n ...feature,\n status: statusToDb(FeatureStatus.Suggested),\n votes: 0,\n board_position: nextPosition,\n })\n .returning('*');\n return mapFeatureRow(row);\n });\n }\n\n async getAll(): Promise<Feature[]> {\n const rows = await this.knex<FeatureRow>('features')\n .orderBy([\n { column: 'status', order: 'asc' },\n { column: 'board_position', order: 'asc' },\n { column: 'created_at', order: 'desc' },\n ])\n .select('*');\n return rows.map(mapFeatureRow);\n }\n\n async getById(id: string): Promise<Feature> {\n const row = await this.knex<FeatureRow>('features').where({ id }).first();\n if (!row) {\n throw new NotFoundError(`Feature with id ${id} not found`);\n }\n return mapFeatureRow(row);\n }\n\n async updateStatus(id: string, status: FeatureStatus): Promise<Feature> {\n return this.knex.transaction(async trx => {\n const current = await trx<FeatureRow>('features').where({ id }).first();\n if (!current) {\n throw new NotFoundError(`Feature with id ${id} not found`);\n }\n const dbStatus = statusToDb(status);\n const patch: Record<string, unknown> = {\n status: dbStatus,\n updated_at: this.knex.fn.now(),\n };\n // Positions only mean something within a column, so a move lands the\n // feature at the end of its destination instead of keeping a position\n // that belonged to the previous column\n if (current.status !== dbStatus) {\n const maxRow = await trx('features')\n .where({ status: dbStatus })\n .max('board_position as maxp')\n .first();\n patch.board_position =\n Number((maxRow as { maxp?: string | number })?.maxp ?? 0) + 1;\n }\n const [row] = await trx<FeatureRow>('features')\n .where({ id })\n .update(patch)\n .returning('*');\n return mapFeatureRow(row);\n });\n }\n\n async updateDetails(\n id: string,\n fields: { title?: string; description?: string },\n ): Promise<Feature> {\n const patch: Record<string, unknown> = { updated_at: this.knex.fn.now() };\n if (fields.title !== undefined) patch.title = fields.title;\n if (fields.description !== undefined)\n patch.description = fields.description;\n const [row] = await this.knex<FeatureRow>('features')\n .where({ id })\n .update(patch)\n .returning('*');\n if (!row) {\n throw new NotFoundError(`Feature with id ${id} not found`);\n }\n return mapFeatureRow(row);\n }\n\n async delete(id: string): Promise<void> {\n const n = await this.knex('features').where({ id }).delete();\n if (!n) {\n throw new NotFoundError(`Feature with id ${id} not found`);\n }\n }\n\n async reorderInStatus(\n status: FeatureStatus,\n orderedIds: string[],\n ): Promise<void> {\n await this.knex.transaction(async trx => {\n for (let i = 0; i < orderedIds.length; i += 1) {\n const updated = await trx('features')\n .where({ id: orderedIds[i], status: statusToDb(status) })\n .update({ board_position: i });\n if (!updated) {\n throw new NotFoundError(\n `Feature ${orderedIds[i]} not found or not in status ${status}`,\n );\n }\n }\n\n // The client may only see a filtered view of the column (retention\n // hides older items), so features it omitted are re-positioned after\n // the submitted ones in their existing relative order to avoid\n // position collisions\n const omitted = await trx<FeatureRow>('features')\n .where({ status: statusToDb(status) })\n .whereNotIn('id', orderedIds)\n .orderBy([\n { column: 'board_position', order: 'asc' },\n { column: 'created_at', order: 'desc' },\n ])\n .select('id');\n for (let i = 0; i < omitted.length; i += 1) {\n await trx('features')\n .where({ id: omitted[i].id })\n .update({ board_position: orderedIds.length + i });\n }\n });\n }\n\n async exists(id: string): Promise<boolean> {\n const row = await this.knex('features').where({ id }).first();\n return Boolean(row);\n }\n}\n"],"names":["statusToDb","FeatureStatus","mapFeatureRow","NotFoundError"],"mappings":";;;;;;;AAcO,MAAM,aAAA,CAAc;AAAA,EACzB,YAA6B,IAAA,EAAY;AAAZ,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAa;AAAA,EAAb,IAAA;AAAA,EAE7B,MAAM,OAAO,OAAA,EAA4D;AACvE,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,WAAA,CAAY,OAAM,GAAA,KAAO;AACxC,MAAA,MAAM,SAAS,MAAM,GAAA,CAAI,UAAU,CAAA,CAChC,MAAM,EAAE,MAAA,EAAQA,0BAAA,CAAWC,0CAAA,CAAc,SAAS,CAAA,EAAG,EACrD,GAAA,CAAI,wBAAwB,EAC5B,KAAA,EAAM;AACT,MAAA,MAAM,YAAA,GACJ,MAAA,CAAQ,M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";
|
|
13
13
|
const AUTHOR_TAG_RE = /^<!-- author:(\S+) -->\n/;
|
|
14
|
+
const ISSUE_AUTHOR_TAG_RE = /^<!-- backstage-author:(\S+) -->\n/;
|
|
14
15
|
const VOTE_TAG_RE = /^<!-- vote:(\S+) -->$/;
|
|
15
16
|
function formatStatusAsGitLabLabel(status) {
|
|
16
17
|
return `${ROADMAP_SCOPE_LABEL}${status}`;
|
|
@@ -31,13 +32,18 @@ function toIsoUtc(isoDate) {
|
|
|
31
32
|
return Number.isNaN(parsed.getTime()) ? isoDate : parsed.toISOString();
|
|
32
33
|
}
|
|
33
34
|
function mapGitLabIssueToFeature(issue, voteCount) {
|
|
35
|
+
const rawDescription = issue.description ?? "";
|
|
36
|
+
const authorMatch = rawDescription.match(ISSUE_AUTHOR_TAG_RE);
|
|
34
37
|
return {
|
|
35
38
|
id: String(issue.id),
|
|
36
39
|
title: issue.title,
|
|
37
|
-
description:
|
|
40
|
+
description: authorMatch ? rawDescription.replace(ISSUE_AUTHOR_TAG_RE, "") : rawDescription,
|
|
38
41
|
status: extractStatusFromLabels(issue.labels ?? []),
|
|
39
42
|
votes: voteCount ?? issue.upvotes ?? 0,
|
|
40
|
-
|
|
43
|
+
// Issues created by this plugin carry the real Backstage author in a
|
|
44
|
+
// hidden tag because the GitLab issue author is just the API token owner.
|
|
45
|
+
// External issues fall back to the GitLab username.
|
|
46
|
+
author: authorMatch ? authorMatch[1] : issue.author?.username ?? "",
|
|
41
47
|
createdAt: toIsoUtc(issue.created_at),
|
|
42
48
|
updatedAt: toIsoUtc(issue.updated_at)
|
|
43
49
|
};
|
|
@@ -67,12 +73,16 @@ function parseUsernameFromEntityRef(userEntityRef) {
|
|
|
67
73
|
const entity = catalogModel.parseEntityRef(userEntityRef);
|
|
68
74
|
return entity.name;
|
|
69
75
|
}
|
|
70
|
-
function buildAuthorTaggedBody(
|
|
71
|
-
return `<!-- author:${
|
|
76
|
+
function buildAuthorTaggedBody(authorRef, text) {
|
|
77
|
+
return `<!-- author:${authorRef} -->
|
|
72
78
|
${text}`;
|
|
73
79
|
}
|
|
74
|
-
function buildVoteMarker(
|
|
75
|
-
return `<!-- vote:${
|
|
80
|
+
function buildVoteMarker(voterRef) {
|
|
81
|
+
return `<!-- vote:${voterRef} -->`;
|
|
82
|
+
}
|
|
83
|
+
function buildIssueAuthorTaggedDescription(authorRef, description) {
|
|
84
|
+
return `<!-- backstage-author:${authorRef} -->
|
|
85
|
+
${description}`;
|
|
76
86
|
}
|
|
77
87
|
function convertIssuesToFeatures(issues, voteCounts) {
|
|
78
88
|
return issues.map(
|
|
@@ -86,13 +96,15 @@ function filterUserComments(notes) {
|
|
|
86
96
|
return notes.filter(isUserComment);
|
|
87
97
|
}
|
|
88
98
|
function buildCommentBody(comment) {
|
|
89
|
-
|
|
90
|
-
return author ? buildAuthorTaggedBody(author, comment.text) : comment.text;
|
|
99
|
+
return comment.author ? buildAuthorTaggedBody(comment.author, comment.text) : comment.text;
|
|
91
100
|
}
|
|
92
101
|
function buildNewRoadmapIssuePayload(feature) {
|
|
93
102
|
return JSON.stringify({
|
|
94
103
|
title: feature.title,
|
|
95
|
-
description:
|
|
104
|
+
description: buildIssueAuthorTaggedDescription(
|
|
105
|
+
feature.author,
|
|
106
|
+
feature.description
|
|
107
|
+
),
|
|
96
108
|
labels: `${ROADMAP_LABEL},${formatStatusAsGitLabLabel(
|
|
97
109
|
backstagePluginRoadmapCommon.FeatureStatus.Suggested
|
|
98
110
|
)}`
|
|
@@ -115,6 +127,25 @@ function voteMapToJson(map) {
|
|
|
115
127
|
function jsonToVoteMap(json) {
|
|
116
128
|
return new Map(Object.entries(json));
|
|
117
129
|
}
|
|
130
|
+
function voterMarkerKeys(voterRef) {
|
|
131
|
+
const username = parseUsernameFromEntityRef(voterRef);
|
|
132
|
+
return username === voterRef ? [voterRef] : [voterRef, username];
|
|
133
|
+
}
|
|
134
|
+
function normalizeVoters(markers) {
|
|
135
|
+
const refKeyByName = /* @__PURE__ */ new Map();
|
|
136
|
+
for (const key of markers.keys()) {
|
|
137
|
+
if (key.includes("/")) {
|
|
138
|
+
const name = key.split("/").pop();
|
|
139
|
+
refKeyByName.set(name, refKeyByName.has(name) ? "" : key);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const logical = /* @__PURE__ */ new Map();
|
|
143
|
+
for (const [key, ids] of markers) {
|
|
144
|
+
const target = key.includes("/") ? key : refKeyByName.get(key) || key;
|
|
145
|
+
logical.set(target, [...logical.get(target) ?? [], ...ids]);
|
|
146
|
+
}
|
|
147
|
+
return logical;
|
|
148
|
+
}
|
|
118
149
|
class RoadmapGitlabClient {
|
|
119
150
|
baseUrl;
|
|
120
151
|
token;
|
|
@@ -253,11 +284,11 @@ class RoadmapGitlabClient {
|
|
|
253
284
|
)})`
|
|
254
285
|
);
|
|
255
286
|
if (res.status === 401)
|
|
256
|
-
throw new errors.
|
|
257
|
-
"GitLab API authentication failed
|
|
287
|
+
throw new errors.ServiceUnavailableError(
|
|
288
|
+
"GitLab API authentication failed because the configured token is missing or invalid"
|
|
258
289
|
);
|
|
259
290
|
if (res.status === 404) throw new errors.NotFoundError(text);
|
|
260
|
-
throw new errors.
|
|
291
|
+
throw new errors.ServiceUnavailableError(`GitLab API error: ${res.status}`);
|
|
261
292
|
}
|
|
262
293
|
if (res.status === 204 || res.headers.get("content-length") === "0") {
|
|
263
294
|
return { data: void 0, res };
|
|
@@ -309,7 +340,7 @@ class RoadmapGitlabClient {
|
|
|
309
340
|
}
|
|
310
341
|
async createRoadmapIssue(feature) {
|
|
311
342
|
if (this.isGroupMode && !this.defaultProjectId) {
|
|
312
|
-
throw new errors.
|
|
343
|
+
throw new errors.ServiceUnavailableError(
|
|
313
344
|
"Creating features in group mode requires defaultProjectId to be configured"
|
|
314
345
|
);
|
|
315
346
|
}
|
|
@@ -348,9 +379,13 @@ class RoadmapGitlabClient {
|
|
|
348
379
|
for (const note of notes) {
|
|
349
380
|
if (note.system) continue;
|
|
350
381
|
const match = (note.body ?? "").trim().match(VOTE_TAG_RE);
|
|
351
|
-
if (match)
|
|
382
|
+
if (match) {
|
|
383
|
+
const ids = votesByUser.get(match[1]) ?? [];
|
|
384
|
+
ids.push(note.id);
|
|
385
|
+
votesByUser.set(match[1], ids);
|
|
386
|
+
}
|
|
352
387
|
}
|
|
353
|
-
return votesByUser;
|
|
388
|
+
return normalizeVoters(votesByUser);
|
|
354
389
|
}
|
|
355
390
|
async deleteNote(featureId, noteId) {
|
|
356
391
|
const pid = await this.resolveProjectId(featureId);
|
|
@@ -373,13 +408,17 @@ class RoadmapGitlabClient {
|
|
|
373
408
|
await this.ensureIssueProjectCached(featureId);
|
|
374
409
|
await this.fetchIssueById(featureId);
|
|
375
410
|
}
|
|
376
|
-
async removeVote(featureId,
|
|
377
|
-
|
|
378
|
-
|
|
411
|
+
async removeVote(featureId, noteIds, votesByUser, voterKeys) {
|
|
412
|
+
for (const noteId of noteIds) {
|
|
413
|
+
await this.deleteNote(featureId, noteId);
|
|
414
|
+
}
|
|
415
|
+
for (const key of voterKeys) {
|
|
416
|
+
votesByUser.delete(key);
|
|
417
|
+
}
|
|
379
418
|
}
|
|
380
|
-
async addVote(featureId, votesByUser,
|
|
381
|
-
await this.createNote(featureId, buildVoteMarker(
|
|
382
|
-
votesByUser.set(
|
|
419
|
+
async addVote(featureId, votesByUser, voterRef) {
|
|
420
|
+
const note = await this.createNote(featureId, buildVoteMarker(voterRef));
|
|
421
|
+
votesByUser.set(voterRef, [note.id]);
|
|
383
422
|
}
|
|
384
423
|
async getOrFetchVotes(featureId) {
|
|
385
424
|
const cached = await this.getCachedVotes(featureId);
|
|
@@ -439,21 +478,27 @@ class RoadmapGitlabClient {
|
|
|
439
478
|
status
|
|
440
479
|
);
|
|
441
480
|
const updatedIssue = await this.updateIssueLabels(id, updatedLabels);
|
|
442
|
-
|
|
481
|
+
const voteCount = await this.getVoteCount(id);
|
|
482
|
+
return mapGitLabIssueToFeature(updatedIssue, voteCount);
|
|
443
483
|
}
|
|
444
484
|
async toggleVote(featureId, voter) {
|
|
445
485
|
await this.ensureIssueProjectCached(featureId);
|
|
446
486
|
await this.invalidateCachedVotes(featureId);
|
|
447
|
-
const
|
|
487
|
+
const voterKeys = voterMarkerKeys(voter);
|
|
448
488
|
const votesByUser = await this.collectVoteMarkersByUser(featureId);
|
|
449
|
-
const
|
|
450
|
-
|
|
451
|
-
|
|
489
|
+
const existingNoteIds = voterKeys.flatMap(
|
|
490
|
+
(key) => votesByUser.get(key) ?? []
|
|
491
|
+
);
|
|
492
|
+
if (existingNoteIds.length > 0) {
|
|
493
|
+
await this.removeVote(featureId, existingNoteIds, votesByUser, voterKeys);
|
|
452
494
|
} else {
|
|
453
|
-
await this.addVote(featureId, votesByUser,
|
|
495
|
+
await this.addVote(featureId, votesByUser, voter);
|
|
454
496
|
}
|
|
455
|
-
await this.
|
|
456
|
-
return {
|
|
497
|
+
await this.invalidateCachedVotes(featureId);
|
|
498
|
+
return {
|
|
499
|
+
voteAdded: existingNoteIds.length === 0,
|
|
500
|
+
voteCount: votesByUser.size
|
|
501
|
+
};
|
|
457
502
|
}
|
|
458
503
|
async getVoteCount(featureId) {
|
|
459
504
|
await this.ensureIssueProjectCached(featureId);
|
|
@@ -469,9 +514,8 @@ class RoadmapGitlabClient {
|
|
|
469
514
|
}
|
|
470
515
|
async hasVoted(featureId, voter) {
|
|
471
516
|
await this.ensureIssueProjectCached(featureId);
|
|
472
|
-
const username = parseUsernameFromEntityRef(voter);
|
|
473
517
|
const votes = await this.getOrFetchVotes(featureId);
|
|
474
|
-
return votes.has(
|
|
518
|
+
return voterMarkerKeys(voter).some((key) => votes.has(key));
|
|
475
519
|
}
|
|
476
520
|
async hasVotedBatch(featureIds, voter) {
|
|
477
521
|
const results = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RoadmapGitlabClient.cjs.js","sources":["../../src/gitlab/RoadmapGitlabClient.ts"],"sourcesContent":["import {\n NewComment,\n Comment,\n NewFeature,\n Feature,\n FeatureStatus,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { RoadmapDatasource } from '../types';\nimport {\n NotFoundError,\n ConflictError,\n NotAllowedError,\n} from '@backstage/errors';\nimport { CacheService, LoggerService } from '@backstage/backend-plugin-api';\nimport { GitlabConfig } from '../types';\nimport { parseEntityRef } from '@backstage/catalog-model';\n\nconst ROADMAP_LABEL = 'roadmap';\nconst ROADMAP_SCOPE_LABEL = `${ROADMAP_LABEL}::`;\nconst STATUS_LABELS = Object.values(FeatureStatus).map(\n status => `${ROADMAP_SCOPE_LABEL}${status}`,\n);\nconst PAGINATION = 'per_page=100';\n\nconst AUTHOR_TAG_RE = /^<!-- author:(\\S+) -->\\n/;\nconst VOTE_TAG_RE = /^<!-- vote:(\\S+) -->$/;\n\ninterface GitLabIssue {\n id: number;\n iid: number;\n project_id?: number;\n title: string;\n description?: string;\n labels?: string[];\n upvotes?: number;\n author?: { username: string };\n created_at: string;\n updated_at: string;\n}\n\ninterface GitLabNote {\n id: number;\n body?: string;\n system?: boolean;\n author?: { username: string };\n created_at: string;\n updated_at: string;\n}\n\nfunction formatStatusAsGitLabLabel(status: FeatureStatus): string {\n return `${ROADMAP_SCOPE_LABEL}${status}`;\n}\n\nfunction extractStatusFromLabels(labels: string[]): FeatureStatus {\n const match = labels.find(l => STATUS_LABELS.includes(l));\n if (!match) return FeatureStatus.Suggested;\n return match.replace(ROADMAP_SCOPE_LABEL, '') as FeatureStatus;\n}\n\nfunction replaceStatusLabels(\n labels: string[],\n newStatus: FeatureStatus,\n): string[] {\n const cleaned = labels.filter(l => !STATUS_LABELS.includes(l));\n if (!cleaned.includes(ROADMAP_LABEL)) cleaned.push(ROADMAP_LABEL);\n cleaned.push(formatStatusAsGitLabLabel(newStatus));\n return cleaned;\n}\n\n/** GitLab already returns ISO 8601; normalize the representation to UTC. */\nfunction toIsoUtc(isoDate: string): string {\n const parsed = new Date(isoDate);\n return Number.isNaN(parsed.getTime()) ? isoDate : parsed.toISOString();\n}\n\nfunction mapGitLabIssueToFeature(\n issue: GitLabIssue,\n voteCount?: number,\n): Feature {\n return {\n id: String(issue.id),\n title: issue.title,\n description: issue.description ?? '',\n status: extractStatusFromLabels(issue.labels ?? []),\n votes: voteCount ?? issue.upvotes ?? 0,\n author: issue.author?.username ?? '',\n createdAt: toIsoUtc(issue.created_at),\n updatedAt: toIsoUtc(issue.updated_at),\n };\n}\n\nfunction mapGitLabNoteToComment(note: GitLabNote, featureId: string): Comment {\n const body = note.body ?? '';\n const authorMatch = body.match(AUTHOR_TAG_RE);\n return {\n id: String(note.id),\n author: authorMatch ? authorMatch[1] : note.author?.username ?? '',\n featureId,\n text: authorMatch ? body.replace(AUTHOR_TAG_RE, '') : body,\n createdAt: toIsoUtc(note.created_at),\n updatedAt: toIsoUtc(note.updated_at),\n };\n}\n\nfunction isHiddenVoteMarker(body: string): boolean {\n return VOTE_TAG_RE.test(body?.trim());\n}\n\nfunction isUserComment(note: GitLabNote): boolean {\n return !note.system && !isHiddenVoteMarker(note.body ?? '');\n}\n\nfunction sanitizeLog(value: string): string {\n return value.replace(/[\\r\\n]/g, '');\n}\n\nfunction parseUsernameFromEntityRef(userEntityRef: string): string {\n const entity = parseEntityRef(userEntityRef);\n return entity.name;\n}\n\nfunction buildAuthorTaggedBody(username: string, text: string): string {\n return `<!-- author:${username} -->\\n${text}`;\n}\n\nfunction buildVoteMarker(username: string): string {\n return `<!-- vote:${username} -->`;\n}\n\nfunction convertIssuesToFeatures(\n issues: GitLabIssue[],\n voteCounts?: Record<string, number>,\n): Feature[] {\n return issues.map(issue =>\n mapGitLabIssueToFeature(issue, voteCounts?.[String(issue.id)]),\n );\n}\n\nfunction convertNotesToComments(\n notes: GitLabNote[],\n featureId: string,\n): Comment[] {\n return notes.map(n => mapGitLabNoteToComment(n, featureId));\n}\n\nfunction filterUserComments(notes: GitLabNote[]): GitLabNote[] {\n return notes.filter(isUserComment);\n}\n\nfunction buildCommentBody(comment: NewComment): string {\n const author = comment.author\n ? parseUsernameFromEntityRef(comment.author)\n : undefined;\n return author ? buildAuthorTaggedBody(author, comment.text) : comment.text;\n}\n\nfunction buildNewRoadmapIssuePayload(feature: NewFeature): string {\n return JSON.stringify({\n title: feature.title,\n description: feature.description,\n labels: `${ROADMAP_LABEL},${formatStatusAsGitLabLabel(\n FeatureStatus.Suggested,\n )}`,\n });\n}\n\nconst VOTE_CACHE_TTL_MS = 30_000; // 30 seconds\nconst PROJECT_MAP_CACHE_TTL_MS = 300_000; // 5 minutes\n\nfunction issueProjectCacheKey(issueId: string): string {\n return `roadmap:issue-project:${issueId}`;\n}\n\nfunction issueIidCacheKey(issueId: string): string {\n return `roadmap:issue-iid:${issueId}`;\n}\n\nfunction voteCacheKey(featureId: string): string {\n return `roadmap:votes:${featureId}`;\n}\n\nfunction voteMapToJson(map: Map<string, number>): Record<string, number> {\n return Object.fromEntries(map);\n}\n\nfunction jsonToVoteMap(json: Record<string, number>): Map<string, number> {\n return new Map(Object.entries(json));\n}\n\nexport class RoadmapGitlabClient implements RoadmapDatasource {\n private readonly baseUrl: string;\n private readonly token: string;\n private readonly projectId?: string;\n private readonly groupId?: string;\n private readonly defaultProjectId?: string;\n private readonly logger: LoggerService;\n private readonly cache: CacheService;\n\n private async getCachedVotes(\n featureId: string,\n ): Promise<Map<string, number> | undefined> {\n const cached = await this.cache.get<Record<string, number>>(\n voteCacheKey(featureId),\n );\n return cached ? jsonToVoteMap(cached) : undefined;\n }\n\n private async setCachedVotes(\n featureId: string,\n data: Map<string, number>,\n ): Promise<void> {\n await this.cache.set(voteCacheKey(featureId), voteMapToJson(data), {\n ttl: VOTE_CACHE_TTL_MS,\n });\n }\n\n private async invalidateCachedVotes(featureId: string): Promise<void> {\n await this.cache.delete(voteCacheKey(featureId));\n }\n\n static create(options: {\n gitlab: GitlabConfig;\n logger: LoggerService;\n cache: CacheService;\n }): RoadmapGitlabClient {\n const { gitlab, logger, cache } = options;\n return new RoadmapGitlabClient(\n gitlab.apiBaseUrl,\n gitlab.token,\n logger,\n cache,\n gitlab.projectId,\n gitlab.groupId,\n gitlab.defaultProjectId,\n );\n }\n\n private constructor(\n baseUrl: string,\n token: string,\n logger: LoggerService,\n cache: CacheService,\n projectId?: string,\n groupId?: string,\n defaultProjectId?: string,\n ) {\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\n this.token = token;\n this.projectId = projectId ? encodeURIComponent(projectId) : undefined;\n this.groupId = groupId ? encodeURIComponent(groupId) : undefined;\n this.defaultProjectId = defaultProjectId\n ? encodeURIComponent(defaultProjectId)\n : undefined;\n this.logger = logger;\n this.cache = cache;\n }\n\n private get isGroupMode(): boolean {\n return !!this.groupId;\n }\n\n private projectApiUrl(path: string, projectId?: string): string {\n const pid = projectId ?? this.projectId;\n if (!pid) {\n throw new Error('projectId is required for this operation');\n }\n return `${this.baseUrl}/projects/${pid}${path}`;\n }\n\n private groupApiUrl(path: string): string {\n return `${this.baseUrl}/groups/${this.groupId}${path}`;\n }\n\n /**\n * Resolves the encoded project ID for a given issue id.\n * In project mode, returns the configured projectId.\n * In group mode, looks up the cached mapping from group issue responses.\n */\n private async resolveProjectId(issueId: string): Promise<string> {\n if (!this.isGroupMode) return this.projectId!;\n const pid = await this.cache.get<string>(issueProjectCacheKey(issueId));\n if (!pid) {\n throw new NotFoundError(\n `No cached project mapping for issue ${issueId}. Fetch all features first.`,\n );\n }\n return pid;\n }\n\n /**\n * Resolves the project-scoped iid for a given global issue id.\n * Looks up the cached id→iid mapping.\n */\n private async resolveIid(issueId: string): Promise<string> {\n const iid = await this.cache.get<string>(issueIidCacheKey(issueId));\n if (!iid) {\n throw new NotFoundError(\n `No cached iid mapping for issue ${issueId}. Fetch all features first.`,\n );\n }\n return iid;\n }\n\n private async hasIssueProjectCached(issueId: string): Promise<boolean> {\n const iid = await this.cache.get<string>(issueIidCacheKey(issueId));\n if (!iid) return false;\n if (!this.isGroupMode) return true;\n const pid = await this.cache.get<string>(issueProjectCacheKey(issueId));\n return !!pid;\n }\n\n /** Caches the project_id and iid for issues returned from group-level queries. */\n private async cacheIssueMetadata(issues: GitLabIssue[]): Promise<void> {\n await Promise.all(\n issues.flatMap(issue => {\n const ops = [\n this.cache.set(\n issueIidCacheKey(String(issue.id)),\n String(issue.iid),\n { ttl: PROJECT_MAP_CACHE_TTL_MS },\n ),\n ];\n if (this.isGroupMode && issue.project_id) {\n ops.push(\n this.cache.set(\n issueProjectCacheKey(String(issue.id)),\n String(issue.project_id),\n { ttl: PROJECT_MAP_CACHE_TTL_MS },\n ),\n );\n }\n return ops;\n }),\n );\n }\n\n private authHeaders(): Record<string, string> {\n return {\n 'PRIVATE-TOKEN': this.token,\n 'Content-Type': 'application/json',\n };\n }\n\n private async ensureIssueProjectCached(featureId: string): Promise<void> {\n if (!(await this.hasIssueProjectCached(featureId))) {\n await this.fetchAllRoadmapIssues();\n }\n }\n\n private async callGitLabApi<T>(\n url: string,\n init?: { method?: string; body?: string },\n ): Promise<{ data: T; res: Response }> {\n const method = init?.method ?? 'GET';\n this.logger.debug(`GitLab API request: ${method} ${sanitizeLog(url)}`);\n const res = await fetch(url, { ...init, headers: this.authHeaders() });\n if (!res.ok) {\n const text = await res.text();\n this.logger.error(\n `GitLab API error: ${res.status} ${sanitizeLog(text)} (${sanitizeLog(\n url,\n )})`,\n );\n if (res.status === 401)\n throw new NotAllowedError(\n 'GitLab API authentication failed: token is missing or invalid',\n );\n if (res.status === 404) throw new NotFoundError(text);\n throw new ConflictError(`GitLab API error: ${res.status}`);\n }\n if (res.status === 204 || res.headers.get('content-length') === '0') {\n return { data: undefined as T, res };\n }\n const data = (await res.json()) as T;\n return { data, res };\n }\n\n private async fetchAllPages<T>(url: string): Promise<T[]> {\n const results: T[] = [];\n let nextUrl: string | undefined = url;\n while (nextUrl) {\n const { data, res } = await this.callGitLabApi<T[]>(nextUrl);\n results.push(...data);\n const nextPage = res.headers.get('x-next-page');\n if (nextPage) {\n const parsed: URL = new URL(nextUrl);\n parsed.searchParams.set('page', nextPage);\n nextUrl = parsed.toString();\n } else {\n nextUrl = undefined;\n }\n }\n return results;\n }\n\n private async fetchAllRoadmapIssues(): Promise<GitLabIssue[]> {\n const issues = await this.fetchAllPages<GitLabIssue>(\n this.roadmapIssuesUrl('desc'),\n );\n await this.cacheIssueMetadata(issues);\n return issues;\n }\n\n private async fetchIssueById(id: string): Promise<GitLabIssue> {\n const pid = await this.resolveProjectId(id);\n const iid = await this.resolveIid(id);\n const { data } = await this.callGitLabApi<GitLabIssue>(\n this.projectApiUrl(`/issues/${iid}`, pid),\n );\n if (this.isGroupMode && data.project_id) {\n await this.cache.set(\n issueProjectCacheKey(String(data.id)),\n String(data.project_id),\n { ttl: PROJECT_MAP_CACHE_TTL_MS },\n );\n }\n await this.cache.set(issueIidCacheKey(String(data.id)), String(data.iid), {\n ttl: PROJECT_MAP_CACHE_TTL_MS,\n });\n return data;\n }\n\n private async createRoadmapIssue(feature: NewFeature): Promise<GitLabIssue> {\n if (this.isGroupMode && !this.defaultProjectId) {\n throw new ConflictError(\n 'Creating features in group mode requires defaultProjectId to be configured',\n );\n }\n const pid = this.isGroupMode ? this.defaultProjectId : this.projectId;\n const { data } = await this.callGitLabApi<GitLabIssue>(\n this.projectApiUrl('/issues', pid),\n {\n method: 'POST',\n body: buildNewRoadmapIssuePayload(feature),\n },\n );\n return data;\n }\n\n private async updateIssueLabels(\n id: string,\n labels: string[],\n ): Promise<GitLabIssue> {\n const pid = await this.resolveProjectId(id);\n const iid = await this.resolveIid(id);\n const { data } = await this.callGitLabApi<GitLabIssue>(\n this.projectApiUrl(`/issues/${iid}`, pid),\n { method: 'PUT', body: JSON.stringify({ labels: labels.join(',') }) },\n );\n return data;\n }\n\n private async fetchIssueNotes(\n featureId: string,\n sort: 'asc' | 'desc' = 'desc',\n ): Promise<GitLabNote[]> {\n const pid = await this.resolveProjectId(featureId);\n const iid = await this.resolveIid(featureId);\n return this.fetchAllPages<GitLabNote>(\n this.projectApiUrl(\n `/issues/${iid}/notes?sort=${sort}&order_by=created_at&${PAGINATION}`,\n pid,\n ),\n );\n }\n\n private async collectVoteMarkersByUser(\n featureId: string,\n ): Promise<Map<string, number>> {\n const notes = await this.fetchIssueNotes(featureId, 'asc');\n const votesByUser = new Map<string, number>();\n for (const note of notes) {\n if (note.system) continue;\n const match = (note.body ?? '').trim().match(VOTE_TAG_RE);\n if (match) votesByUser.set(match[1], note.id);\n }\n return votesByUser;\n }\n\n private async deleteNote(featureId: string, noteId: number): Promise<void> {\n const pid = await this.resolveProjectId(featureId);\n const iid = await this.resolveIid(featureId);\n await this.callGitLabApi<void>(\n this.projectApiUrl(`/issues/${iid}/notes/${noteId}`, pid),\n { method: 'DELETE' },\n );\n }\n\n private async createNote(\n featureId: string,\n body: string,\n ): Promise<GitLabNote> {\n const pid = await this.resolveProjectId(featureId);\n const iid = await this.resolveIid(featureId);\n const { data } = await this.callGitLabApi<GitLabNote>(\n this.projectApiUrl(`/issues/${iid}/notes`, pid),\n { method: 'POST', body: JSON.stringify({ body }) },\n );\n return data;\n }\n\n private async ensureFeatureExists(featureId: string): Promise<void> {\n await this.ensureIssueProjectCached(featureId);\n await this.fetchIssueById(featureId);\n }\n\n private async removeVote(\n featureId: string,\n noteId: number,\n votesByUser: Map<string, number>,\n username: string,\n ): Promise<void> {\n await this.deleteNote(featureId, noteId);\n votesByUser.delete(username);\n }\n\n private async addVote(\n featureId: string,\n votesByUser: Map<string, number>,\n username: string,\n ): Promise<void> {\n await this.createNote(featureId, buildVoteMarker(username));\n votesByUser.set(username, 0);\n }\n\n private async getOrFetchVotes(\n featureId: string,\n ): Promise<Map<string, number>> {\n const cached = await this.getCachedVotes(featureId);\n if (cached) return cached;\n const votes = await this.collectVoteMarkersByUser(featureId);\n await this.setCachedVotes(featureId, votes);\n return votes;\n }\n\n private async collectAllVoteCounts(\n issues: GitLabIssue[],\n ): Promise<Record<string, number>> {\n const counts: Record<string, number> = {};\n await Promise.all(\n issues.map(async issue => {\n const id = String(issue.id);\n const votes = await this.getOrFetchVotes(id);\n counts[id] = votes.size;\n }),\n );\n return counts;\n }\n\n private roadmapIssuesUrl(sort: 'asc' | 'desc' = 'desc'): string {\n const query = `/issues?labels=${ROADMAP_LABEL}&${PAGINATION}&order_by=created_at&sort=${sort}`;\n return this.isGroupMode\n ? this.groupApiUrl(query)\n : this.projectApiUrl(query);\n }\n\n async addComment(comment: NewComment): Promise<Comment> {\n await this.ensureIssueProjectCached(comment.featureId);\n const body = buildCommentBody(comment);\n const gitlabNote = await this.createNote(comment.featureId, body);\n return mapGitLabNoteToComment(gitlabNote, comment.featureId);\n }\n\n async getCommentsByFeatureId(featureId: string): Promise<Comment[]> {\n await this.ensureFeatureExists(featureId);\n const allNotes = await this.fetchIssueNotes(featureId, 'desc');\n const commentNotes = filterUserComments(allNotes);\n return convertNotesToComments(commentNotes, featureId);\n }\n\n async addFeature(feature: NewFeature & { author: string }): Promise<Feature> {\n const gitlabIssue = await this.createRoadmapIssue(feature);\n return mapGitLabIssueToFeature(gitlabIssue);\n }\n\n async getAllFeatures(): Promise<Feature[]> {\n this.logger.info('Fetching all roadmap features from GitLab');\n const gitlabIssues = await this.fetchAllRoadmapIssues();\n const voteCounts = await this.collectAllVoteCounts(gitlabIssues);\n return convertIssuesToFeatures(gitlabIssues, voteCounts);\n }\n\n async getFeatureById(id: string): Promise<Feature> {\n await this.ensureIssueProjectCached(id);\n const gitlabIssue = await this.fetchIssueById(id);\n const voteCount = await this.getVoteCount(id);\n return mapGitLabIssueToFeature(gitlabIssue, voteCount);\n }\n\n async updateFeatureStatus(\n id: string,\n status: FeatureStatus,\n ): Promise<Feature> {\n await this.ensureIssueProjectCached(id);\n const existingIssue = await this.fetchIssueById(id);\n const updatedLabels = replaceStatusLabels(\n existingIssue.labels ?? [],\n status,\n );\n const updatedIssue = await this.updateIssueLabels(id, updatedLabels);\n return mapGitLabIssueToFeature(updatedIssue);\n }\n\n async toggleVote(\n featureId: string,\n voter: string,\n ): Promise<{ voteAdded: boolean; voteCount: number }> {\n await this.ensureIssueProjectCached(featureId);\n await this.invalidateCachedVotes(featureId);\n const username = parseUsernameFromEntityRef(voter);\n const votesByUser = await this.collectVoteMarkersByUser(featureId);\n const existingNoteId = votesByUser.get(username);\n\n if (existingNoteId) {\n await this.removeVote(featureId, existingNoteId, votesByUser, username);\n } else {\n await this.addVote(featureId, votesByUser, username);\n }\n\n await this.setCachedVotes(featureId, votesByUser);\n return { voteAdded: !existingNoteId, voteCount: votesByUser.size };\n }\n\n async getVoteCount(featureId: string): Promise<number> {\n await this.ensureIssueProjectCached(featureId);\n const votes = await this.getOrFetchVotes(featureId);\n return votes.size;\n }\n\n async getVoteCounts(featureIds: string[]): Promise<Record<string, number>> {\n const counts: Record<string, number> = {};\n for (const id of featureIds) {\n counts[id] = await this.getVoteCount(id);\n }\n return counts;\n }\n\n async hasVoted(featureId: string, voter: string): Promise<boolean> {\n await this.ensureIssueProjectCached(featureId);\n const username = parseUsernameFromEntityRef(voter);\n const votes = await this.getOrFetchVotes(featureId);\n return votes.has(username);\n }\n\n async hasVotedBatch(\n featureIds: string[],\n voter: string,\n ): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n for (const id of featureIds) {\n results[id] = await this.hasVoted(id, voter);\n }\n return results;\n }\n}\n"],"names":["FeatureStatus","parseEntityRef","NotFoundError","NotAllowedError","ConflictError"],"mappings":";;;;;;AAiBA,MAAM,aAAA,GAAgB,SAAA;AACtB,MAAM,mBAAA,GAAsB,GAAG,aAAa,CAAA,EAAA,CAAA;AAC5C,MAAM,aAAA,GAAgB,MAAA,CAAO,MAAA,CAAOA,0CAAa,CAAA,CAAE,GAAA;AAAA,EACjD,CAAA,MAAA,KAAU,CAAA,EAAG,mBAAmB,CAAA,EAAG,MAAM,CAAA;AAC3C,CAAA;AACA,MAAM,UAAA,GAAa,cAAA;AAEnB,MAAM,aAAA,GAAgB,0BAAA;AACtB,MAAM,WAAA,GAAc,uBAAA;AAwBpB,SAAS,0BAA0B,MAAA,EAA+B;AAChE,EAAA,OAAO,CAAA,E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AAA,CAAM,IAAA;AAAA,EACf;AAAA,EAEA,MAAM,cAAc,UAAA,EAAuD;AACzE,IAAA,MAAM,SAAiC,EAAC;AACxC,IAAA,KAAA,MAAW,MAAM,UAAA,EAAY;AAC3B,MAAA,MAAA,CAAO,EAAE,CAAA,GAAI,MAAM,IAAA,CAAK,aAAa,EAAE,CAAA;AAAA,IACzC;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EAEA,MAAM,QAAA,CAAS,SAAA,EAAmB,KAAA,EAAiC;AACjE,IAAA,MAAM,IAAA,CAAK,yBAAyB,SAAS,CAAA;AAC7C,IAAA,MAAM,QAAA,GAAW,2BAA2B,KAAK,CAAA;AACjD,IAAA,MAAM,KAAA,GAAQ,MAAM,IAAA,CAAK,eAAA,CAAgB,SAAS,CAAA;AAClD,IAAA,OAAO,KAAA,CAAM,IAAI,QAAQ,CAAA;AAAA,EAC3B;AAAA,EAEA,MAAM,aAAA,CACJ,UAAA,EACA,KAAA,EACkC;AAClC,IAAA,MAAM,UAAmC,EAAC;AAC1C,IAAA,KAAA,MAAW,MAAM,UAAA,EAAY;AAC3B,MAAA,OAAA,CAAQ,EAAE,CAAA,GAAI,MAAM,IAAA,CAAK,QAAA,CAAS,IAAI,KAAK,CAAA;AAAA,IAC7C;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"RoadmapGitlabClient.cjs.js","sources":["../../src/gitlab/RoadmapGitlabClient.ts"],"sourcesContent":["import {\n NewComment,\n Comment,\n NewFeature,\n Feature,\n FeatureStatus,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { RoadmapDatasource } from '../types';\nimport { NotFoundError, ServiceUnavailableError } from '@backstage/errors';\nimport { CacheService, LoggerService } from '@backstage/backend-plugin-api';\nimport { GitlabConfig } from '../types';\nimport { parseEntityRef } from '@backstage/catalog-model';\n\nconst ROADMAP_LABEL = 'roadmap';\nconst ROADMAP_SCOPE_LABEL = `${ROADMAP_LABEL}::`;\nconst STATUS_LABELS = Object.values(FeatureStatus).map(\n status => `${ROADMAP_SCOPE_LABEL}${status}`,\n);\nconst PAGINATION = 'per_page=100';\n\n// Markers persist the full Backstage entity ref (user:default/alice) so\n// namespaces are preserved. Legacy markers hold a bare username and are\n// still parsed for backward compatibility.\nconst AUTHOR_TAG_RE = /^<!-- author:(\\S+) -->\\n/;\nconst ISSUE_AUTHOR_TAG_RE = /^<!-- backstage-author:(\\S+) -->\\n/;\nconst VOTE_TAG_RE = /^<!-- vote:(\\S+) -->$/;\n\ninterface GitLabIssue {\n id: number;\n iid: number;\n project_id?: number;\n title: string;\n description?: string;\n labels?: string[];\n upvotes?: number;\n author?: { username: string };\n created_at: string;\n updated_at: string;\n}\n\ninterface GitLabNote {\n id: number;\n body?: string;\n system?: boolean;\n author?: { username: string };\n created_at: string;\n updated_at: string;\n}\n\nfunction formatStatusAsGitLabLabel(status: FeatureStatus): string {\n return `${ROADMAP_SCOPE_LABEL}${status}`;\n}\n\nfunction extractStatusFromLabels(labels: string[]): FeatureStatus {\n const match = labels.find(l => STATUS_LABELS.includes(l));\n if (!match) return FeatureStatus.Suggested;\n return match.replace(ROADMAP_SCOPE_LABEL, '') as FeatureStatus;\n}\n\nfunction replaceStatusLabels(\n labels: string[],\n newStatus: FeatureStatus,\n): string[] {\n const cleaned = labels.filter(l => !STATUS_LABELS.includes(l));\n if (!cleaned.includes(ROADMAP_LABEL)) cleaned.push(ROADMAP_LABEL);\n cleaned.push(formatStatusAsGitLabLabel(newStatus));\n return cleaned;\n}\n\n/** GitLab already returns ISO 8601; normalize the representation to UTC. */\nfunction toIsoUtc(isoDate: string): string {\n const parsed = new Date(isoDate);\n return Number.isNaN(parsed.getTime()) ? isoDate : parsed.toISOString();\n}\n\nfunction mapGitLabIssueToFeature(\n issue: GitLabIssue,\n voteCount?: number,\n): Feature {\n const rawDescription = issue.description ?? '';\n const authorMatch = rawDescription.match(ISSUE_AUTHOR_TAG_RE);\n return {\n id: String(issue.id),\n title: issue.title,\n description: authorMatch\n ? rawDescription.replace(ISSUE_AUTHOR_TAG_RE, '')\n : rawDescription,\n status: extractStatusFromLabels(issue.labels ?? []),\n votes: voteCount ?? issue.upvotes ?? 0,\n // Issues created by this plugin carry the real Backstage author in a\n // hidden tag because the GitLab issue author is just the API token owner.\n // External issues fall back to the GitLab username.\n author: authorMatch ? authorMatch[1] : issue.author?.username ?? '',\n createdAt: toIsoUtc(issue.created_at),\n updatedAt: toIsoUtc(issue.updated_at),\n };\n}\n\nfunction mapGitLabNoteToComment(note: GitLabNote, featureId: string): Comment {\n const body = note.body ?? '';\n const authorMatch = body.match(AUTHOR_TAG_RE);\n return {\n id: String(note.id),\n author: authorMatch ? authorMatch[1] : note.author?.username ?? '',\n featureId,\n text: authorMatch ? body.replace(AUTHOR_TAG_RE, '') : body,\n createdAt: toIsoUtc(note.created_at),\n updatedAt: toIsoUtc(note.updated_at),\n };\n}\n\nfunction isHiddenVoteMarker(body: string): boolean {\n return VOTE_TAG_RE.test(body?.trim());\n}\n\nfunction isUserComment(note: GitLabNote): boolean {\n return !note.system && !isHiddenVoteMarker(note.body ?? '');\n}\n\nfunction sanitizeLog(value: string): string {\n return value.replace(/[\\r\\n]/g, '');\n}\n\nfunction parseUsernameFromEntityRef(userEntityRef: string): string {\n const entity = parseEntityRef(userEntityRef);\n return entity.name;\n}\n\nfunction buildAuthorTaggedBody(authorRef: string, text: string): string {\n return `<!-- author:${authorRef} -->\\n${text}`;\n}\n\nfunction buildVoteMarker(voterRef: string): string {\n return `<!-- vote:${voterRef} -->`;\n}\n\nfunction buildIssueAuthorTaggedDescription(\n authorRef: string,\n description: string,\n): string {\n return `<!-- backstage-author:${authorRef} -->\\n${description}`;\n}\n\nfunction convertIssuesToFeatures(\n issues: GitLabIssue[],\n voteCounts?: Record<string, number>,\n): Feature[] {\n return issues.map(issue =>\n mapGitLabIssueToFeature(issue, voteCounts?.[String(issue.id)]),\n );\n}\n\nfunction convertNotesToComments(\n notes: GitLabNote[],\n featureId: string,\n): Comment[] {\n return notes.map(n => mapGitLabNoteToComment(n, featureId));\n}\n\nfunction filterUserComments(notes: GitLabNote[]): GitLabNote[] {\n return notes.filter(isUserComment);\n}\n\nfunction buildCommentBody(comment: NewComment): string {\n return comment.author\n ? buildAuthorTaggedBody(comment.author, comment.text)\n : comment.text;\n}\n\nfunction buildNewRoadmapIssuePayload(\n feature: NewFeature & { author: string },\n): string {\n return JSON.stringify({\n title: feature.title,\n description: buildIssueAuthorTaggedDescription(\n feature.author,\n feature.description,\n ),\n labels: `${ROADMAP_LABEL},${formatStatusAsGitLabLabel(\n FeatureStatus.Suggested,\n )}`,\n });\n}\n\nconst VOTE_CACHE_TTL_MS = 30_000; // 30 seconds\nconst PROJECT_MAP_CACHE_TTL_MS = 300_000; // 5 minutes\n\nfunction issueProjectCacheKey(issueId: string): string {\n return `roadmap:issue-project:${issueId}`;\n}\n\nfunction issueIidCacheKey(issueId: string): string {\n return `roadmap:issue-iid:${issueId}`;\n}\n\nfunction voteCacheKey(featureId: string): string {\n return `roadmap:votes:${featureId}`;\n}\n\nfunction voteMapToJson(map: Map<string, number[]>): Record<string, number[]> {\n return Object.fromEntries(map);\n}\n\nfunction jsonToVoteMap(json: Record<string, number[]>): Map<string, number[]> {\n return new Map(Object.entries(json));\n}\n\n/** The keys a voter's markers may be stored under, newest format first. */\nfunction voterMarkerKeys(voterRef: string): string[] {\n const username = parseUsernameFromEntityRef(voterRef);\n return username === voterRef ? [voterRef] : [voterRef, username];\n}\n\n/**\n * Groups raw marker keys into logical voters. A legacy username-only marker\n * is folded into the canonical entity ref marker with the same name when\n * that mapping is unambiguous, so one person with markers in both formats\n * still counts as a single voter and unvotes cleanly.\n */\nfunction normalizeVoters(\n markers: Map<string, number[]>,\n): Map<string, number[]> {\n const refKeyByName = new Map<string, string>();\n for (const key of markers.keys()) {\n if (key.includes('/')) {\n const name = key.split('/').pop()!;\n // An empty value marks an ambiguous name that must not be folded\n refKeyByName.set(name, refKeyByName.has(name) ? '' : key);\n }\n }\n const logical = new Map<string, number[]>();\n for (const [key, ids] of markers) {\n const target = key.includes('/') ? key : refKeyByName.get(key) || key;\n logical.set(target, [...(logical.get(target) ?? []), ...ids]);\n }\n return logical;\n}\n\nexport class RoadmapGitlabClient implements RoadmapDatasource {\n private readonly baseUrl: string;\n private readonly token: string;\n private readonly projectId?: string;\n private readonly groupId?: string;\n private readonly defaultProjectId?: string;\n private readonly logger: LoggerService;\n private readonly cache: CacheService;\n\n private async getCachedVotes(\n featureId: string,\n ): Promise<Map<string, number[]> | undefined> {\n const cached = await this.cache.get<Record<string, number[]>>(\n voteCacheKey(featureId),\n );\n return cached ? jsonToVoteMap(cached) : undefined;\n }\n\n private async setCachedVotes(\n featureId: string,\n data: Map<string, number[]>,\n ): Promise<void> {\n await this.cache.set(voteCacheKey(featureId), voteMapToJson(data), {\n ttl: VOTE_CACHE_TTL_MS,\n });\n }\n\n private async invalidateCachedVotes(featureId: string): Promise<void> {\n await this.cache.delete(voteCacheKey(featureId));\n }\n\n static create(options: {\n gitlab: GitlabConfig;\n logger: LoggerService;\n cache: CacheService;\n }): RoadmapGitlabClient {\n const { gitlab, logger, cache } = options;\n return new RoadmapGitlabClient(\n gitlab.apiBaseUrl,\n gitlab.token,\n logger,\n cache,\n gitlab.projectId,\n gitlab.groupId,\n gitlab.defaultProjectId,\n );\n }\n\n private constructor(\n baseUrl: string,\n token: string,\n logger: LoggerService,\n cache: CacheService,\n projectId?: string,\n groupId?: string,\n defaultProjectId?: string,\n ) {\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\n this.token = token;\n this.projectId = projectId ? encodeURIComponent(projectId) : undefined;\n this.groupId = groupId ? encodeURIComponent(groupId) : undefined;\n this.defaultProjectId = defaultProjectId\n ? encodeURIComponent(defaultProjectId)\n : undefined;\n this.logger = logger;\n this.cache = cache;\n }\n\n private get isGroupMode(): boolean {\n return !!this.groupId;\n }\n\n private projectApiUrl(path: string, projectId?: string): string {\n const pid = projectId ?? this.projectId;\n if (!pid) {\n throw new Error('projectId is required for this operation');\n }\n return `${this.baseUrl}/projects/${pid}${path}`;\n }\n\n private groupApiUrl(path: string): string {\n return `${this.baseUrl}/groups/${this.groupId}${path}`;\n }\n\n /**\n * Resolves the encoded project ID for a given issue id.\n * In project mode, returns the configured projectId.\n * In group mode, looks up the cached mapping from group issue responses.\n */\n private async resolveProjectId(issueId: string): Promise<string> {\n if (!this.isGroupMode) return this.projectId!;\n const pid = await this.cache.get<string>(issueProjectCacheKey(issueId));\n if (!pid) {\n throw new NotFoundError(\n `No cached project mapping for issue ${issueId}. Fetch all features first.`,\n );\n }\n return pid;\n }\n\n /**\n * Resolves the project-scoped iid for a given global issue id.\n * Looks up the cached id→iid mapping.\n */\n private async resolveIid(issueId: string): Promise<string> {\n const iid = await this.cache.get<string>(issueIidCacheKey(issueId));\n if (!iid) {\n throw new NotFoundError(\n `No cached iid mapping for issue ${issueId}. Fetch all features first.`,\n );\n }\n return iid;\n }\n\n private async hasIssueProjectCached(issueId: string): Promise<boolean> {\n const iid = await this.cache.get<string>(issueIidCacheKey(issueId));\n if (!iid) return false;\n if (!this.isGroupMode) return true;\n const pid = await this.cache.get<string>(issueProjectCacheKey(issueId));\n return !!pid;\n }\n\n /** Caches the project_id and iid for issues returned from group-level queries. */\n private async cacheIssueMetadata(issues: GitLabIssue[]): Promise<void> {\n await Promise.all(\n issues.flatMap(issue => {\n const ops = [\n this.cache.set(\n issueIidCacheKey(String(issue.id)),\n String(issue.iid),\n { ttl: PROJECT_MAP_CACHE_TTL_MS },\n ),\n ];\n if (this.isGroupMode && issue.project_id) {\n ops.push(\n this.cache.set(\n issueProjectCacheKey(String(issue.id)),\n String(issue.project_id),\n { ttl: PROJECT_MAP_CACHE_TTL_MS },\n ),\n );\n }\n return ops;\n }),\n );\n }\n\n private authHeaders(): Record<string, string> {\n return {\n 'PRIVATE-TOKEN': this.token,\n 'Content-Type': 'application/json',\n };\n }\n\n private async ensureIssueProjectCached(featureId: string): Promise<void> {\n if (!(await this.hasIssueProjectCached(featureId))) {\n await this.fetchAllRoadmapIssues();\n }\n }\n\n private async callGitLabApi<T>(\n url: string,\n init?: { method?: string; body?: string },\n ): Promise<{ data: T; res: Response }> {\n const method = init?.method ?? 'GET';\n this.logger.debug(`GitLab API request: ${method} ${sanitizeLog(url)}`);\n const res = await fetch(url, { ...init, headers: this.authHeaders() });\n if (!res.ok) {\n const text = await res.text();\n this.logger.error(\n `GitLab API error: ${res.status} ${sanitizeLog(text)} (${sanitizeLog(\n url,\n )})`,\n );\n // Upstream failures are server-side problems, so they surface as 503\n // instead of blaming the caller with a 403 or 409\n if (res.status === 401)\n throw new ServiceUnavailableError(\n 'GitLab API authentication failed because the configured token is missing or invalid',\n );\n if (res.status === 404) throw new NotFoundError(text);\n throw new ServiceUnavailableError(`GitLab API error: ${res.status}`);\n }\n if (res.status === 204 || res.headers.get('content-length') === '0') {\n return { data: undefined as T, res };\n }\n const data = (await res.json()) as T;\n return { data, res };\n }\n\n private async fetchAllPages<T>(url: string): Promise<T[]> {\n const results: T[] = [];\n let nextUrl: string | undefined = url;\n while (nextUrl) {\n const { data, res } = await this.callGitLabApi<T[]>(nextUrl);\n results.push(...data);\n const nextPage = res.headers.get('x-next-page');\n if (nextPage) {\n const parsed: URL = new URL(nextUrl);\n parsed.searchParams.set('page', nextPage);\n nextUrl = parsed.toString();\n } else {\n nextUrl = undefined;\n }\n }\n return results;\n }\n\n private async fetchAllRoadmapIssues(): Promise<GitLabIssue[]> {\n const issues = await this.fetchAllPages<GitLabIssue>(\n this.roadmapIssuesUrl('desc'),\n );\n await this.cacheIssueMetadata(issues);\n return issues;\n }\n\n private async fetchIssueById(id: string): Promise<GitLabIssue> {\n const pid = await this.resolveProjectId(id);\n const iid = await this.resolveIid(id);\n const { data } = await this.callGitLabApi<GitLabIssue>(\n this.projectApiUrl(`/issues/${iid}`, pid),\n );\n if (this.isGroupMode && data.project_id) {\n await this.cache.set(\n issueProjectCacheKey(String(data.id)),\n String(data.project_id),\n { ttl: PROJECT_MAP_CACHE_TTL_MS },\n );\n }\n await this.cache.set(issueIidCacheKey(String(data.id)), String(data.iid), {\n ttl: PROJECT_MAP_CACHE_TTL_MS,\n });\n return data;\n }\n\n private async createRoadmapIssue(\n feature: NewFeature & { author: string },\n ): Promise<GitLabIssue> {\n if (this.isGroupMode && !this.defaultProjectId) {\n throw new ServiceUnavailableError(\n 'Creating features in group mode requires defaultProjectId to be configured',\n );\n }\n const pid = this.isGroupMode ? this.defaultProjectId : this.projectId;\n const { data } = await this.callGitLabApi<GitLabIssue>(\n this.projectApiUrl('/issues', pid),\n {\n method: 'POST',\n body: buildNewRoadmapIssuePayload(feature),\n },\n );\n return data;\n }\n\n private async updateIssueLabels(\n id: string,\n labels: string[],\n ): Promise<GitLabIssue> {\n const pid = await this.resolveProjectId(id);\n const iid = await this.resolveIid(id);\n const { data } = await this.callGitLabApi<GitLabIssue>(\n this.projectApiUrl(`/issues/${iid}`, pid),\n { method: 'PUT', body: JSON.stringify({ labels: labels.join(',') }) },\n );\n return data;\n }\n\n private async fetchIssueNotes(\n featureId: string,\n sort: 'asc' | 'desc' = 'desc',\n ): Promise<GitLabNote[]> {\n const pid = await this.resolveProjectId(featureId);\n const iid = await this.resolveIid(featureId);\n return this.fetchAllPages<GitLabNote>(\n this.projectApiUrl(\n `/issues/${iid}/notes?sort=${sort}&order_by=created_at&${PAGINATION}`,\n pid,\n ),\n );\n }\n\n private async collectVoteMarkersByUser(\n featureId: string,\n ): Promise<Map<string, number[]>> {\n const notes = await this.fetchIssueNotes(featureId, 'asc');\n // Every marker note is tracked (not just the latest) so an unvote can\n // clean up duplicates left behind by concurrent toggles\n const votesByUser = new Map<string, number[]>();\n for (const note of notes) {\n if (note.system) continue;\n const match = (note.body ?? '').trim().match(VOTE_TAG_RE);\n if (match) {\n const ids = votesByUser.get(match[1]) ?? [];\n ids.push(note.id);\n votesByUser.set(match[1], ids);\n }\n }\n // Collapse aliases once here so count, hasVoted, and toggle all see the\n // same logical voters\n return normalizeVoters(votesByUser);\n }\n\n private async deleteNote(featureId: string, noteId: number): Promise<void> {\n const pid = await this.resolveProjectId(featureId);\n const iid = await this.resolveIid(featureId);\n await this.callGitLabApi<void>(\n this.projectApiUrl(`/issues/${iid}/notes/${noteId}`, pid),\n { method: 'DELETE' },\n );\n }\n\n private async createNote(\n featureId: string,\n body: string,\n ): Promise<GitLabNote> {\n const pid = await this.resolveProjectId(featureId);\n const iid = await this.resolveIid(featureId);\n const { data } = await this.callGitLabApi<GitLabNote>(\n this.projectApiUrl(`/issues/${iid}/notes`, pid),\n { method: 'POST', body: JSON.stringify({ body }) },\n );\n return data;\n }\n\n private async ensureFeatureExists(featureId: string): Promise<void> {\n await this.ensureIssueProjectCached(featureId);\n await this.fetchIssueById(featureId);\n }\n\n private async removeVote(\n featureId: string,\n noteIds: number[],\n votesByUser: Map<string, number[]>,\n voterKeys: string[],\n ): Promise<void> {\n // Delete every marker the voter has, including duplicates from\n // concurrent toggles and legacy username-only markers\n for (const noteId of noteIds) {\n await this.deleteNote(featureId, noteId);\n }\n for (const key of voterKeys) {\n votesByUser.delete(key);\n }\n }\n\n private async addVote(\n featureId: string,\n votesByUser: Map<string, number[]>,\n voterRef: string,\n ): Promise<void> {\n const note = await this.createNote(featureId, buildVoteMarker(voterRef));\n votesByUser.set(voterRef, [note.id]);\n }\n\n private async getOrFetchVotes(\n featureId: string,\n ): Promise<Map<string, number[]>> {\n const cached = await this.getCachedVotes(featureId);\n if (cached) return cached;\n const votes = await this.collectVoteMarkersByUser(featureId);\n await this.setCachedVotes(featureId, votes);\n return votes;\n }\n\n private async collectAllVoteCounts(\n issues: GitLabIssue[],\n ): Promise<Record<string, number>> {\n const counts: Record<string, number> = {};\n await Promise.all(\n issues.map(async issue => {\n const id = String(issue.id);\n const votes = await this.getOrFetchVotes(id);\n counts[id] = votes.size;\n }),\n );\n return counts;\n }\n\n private roadmapIssuesUrl(sort: 'asc' | 'desc' = 'desc'): string {\n const query = `/issues?labels=${ROADMAP_LABEL}&${PAGINATION}&order_by=created_at&sort=${sort}`;\n return this.isGroupMode\n ? this.groupApiUrl(query)\n : this.projectApiUrl(query);\n }\n\n async addComment(comment: NewComment): Promise<Comment> {\n await this.ensureIssueProjectCached(comment.featureId);\n const body = buildCommentBody(comment);\n const gitlabNote = await this.createNote(comment.featureId, body);\n return mapGitLabNoteToComment(gitlabNote, comment.featureId);\n }\n\n async getCommentsByFeatureId(featureId: string): Promise<Comment[]> {\n await this.ensureFeatureExists(featureId);\n const allNotes = await this.fetchIssueNotes(featureId, 'desc');\n const commentNotes = filterUserComments(allNotes);\n return convertNotesToComments(commentNotes, featureId);\n }\n\n async addFeature(feature: NewFeature & { author: string }): Promise<Feature> {\n const gitlabIssue = await this.createRoadmapIssue(feature);\n return mapGitLabIssueToFeature(gitlabIssue);\n }\n\n async getAllFeatures(): Promise<Feature[]> {\n this.logger.info('Fetching all roadmap features from GitLab');\n const gitlabIssues = await this.fetchAllRoadmapIssues();\n const voteCounts = await this.collectAllVoteCounts(gitlabIssues);\n return convertIssuesToFeatures(gitlabIssues, voteCounts);\n }\n\n async getFeatureById(id: string): Promise<Feature> {\n await this.ensureIssueProjectCached(id);\n const gitlabIssue = await this.fetchIssueById(id);\n const voteCount = await this.getVoteCount(id);\n return mapGitLabIssueToFeature(gitlabIssue, voteCount);\n }\n\n async updateFeatureStatus(\n id: string,\n status: FeatureStatus,\n ): Promise<Feature> {\n await this.ensureIssueProjectCached(id);\n const existingIssue = await this.fetchIssueById(id);\n const updatedLabels = replaceStatusLabels(\n existingIssue.labels ?? [],\n status,\n );\n const updatedIssue = await this.updateIssueLabels(id, updatedLabels);\n // Label updates don't touch votes, so without this the mapping would\n // fall back to GitLab's native upvotes and misreport the marker count.\n const voteCount = await this.getVoteCount(id);\n return mapGitLabIssueToFeature(updatedIssue, voteCount);\n }\n\n async toggleVote(\n featureId: string,\n voter: string,\n ): Promise<{ voteAdded: boolean; voteCount: number }> {\n await this.ensureIssueProjectCached(featureId);\n await this.invalidateCachedVotes(featureId);\n const voterKeys = voterMarkerKeys(voter);\n const votesByUser = await this.collectVoteMarkersByUser(featureId);\n const existingNoteIds = voterKeys.flatMap(\n key => votesByUser.get(key) ?? [],\n );\n\n if (existingNoteIds.length > 0) {\n await this.removeVote(featureId, existingNoteIds, votesByUser, voterKeys);\n } else {\n await this.addVote(featureId, votesByUser, voter);\n }\n\n // Don't cache the locally modified map because a concurrent toggle may\n // have added notes we never saw, and the snapshot would then serve a\n // wrong count for the cache TTL. Invalidate and let the next read refetch.\n // The returned count is still this request's local view, which is a\n // deliberate trade-off since an exact answer would cost another full\n // notes fetch and the next board load self-corrects anyway.\n await this.invalidateCachedVotes(featureId);\n return {\n voteAdded: existingNoteIds.length === 0,\n voteCount: votesByUser.size,\n };\n }\n\n async getVoteCount(featureId: string): Promise<number> {\n await this.ensureIssueProjectCached(featureId);\n const votes = await this.getOrFetchVotes(featureId);\n return votes.size;\n }\n\n async getVoteCounts(featureIds: string[]): Promise<Record<string, number>> {\n const counts: Record<string, number> = {};\n for (const id of featureIds) {\n counts[id] = await this.getVoteCount(id);\n }\n return counts;\n }\n\n async hasVoted(featureId: string, voter: string): Promise<boolean> {\n await this.ensureIssueProjectCached(featureId);\n const votes = await this.getOrFetchVotes(featureId);\n return voterMarkerKeys(voter).some(key => votes.has(key));\n }\n\n async hasVotedBatch(\n featureIds: string[],\n voter: string,\n ): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n for (const id of featureIds) {\n results[id] = await this.hasVoted(id, voter);\n }\n return results;\n }\n}\n"],"names":["FeatureStatus","parseEntityRef","NotFoundError","ServiceUnavailableError"],"mappings":";;;;;;AAaA,MAAM,aAAA,GAAgB,SAAA;AACtB,MAAM,mBAAA,GAAsB,GAAG,aAAa,CAAA,EAAA,CAAA;AAC5C,MAAM,aAAA,GAAgB,MAAA,CAAO,MAAA,CAAOA,0CAAa,CAAA,CAAE,GAAA;AAAA,EACjD,CAAA,MAAA,K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AA,CAAgB,SAAS,CAAA;AAClD,IAAA,OAAO,eAAA,CAAgB,KAAK,CAAA,CAAE,IAAA,CAAK,SAAO,KAAA,CAAM,GAAA,CAAI,GAAG,CAAC,CAAA;AAAA,EAC1D;AAAA,EAEA,MAAM,aAAA,CACJ,UAAA,EACA,KAAA,EACkC;AAClC,IAAA,MAAM,UAAmC,EAAC;AAC1C,IAAA,KAAA,MAAW,MAAM,UAAA,EAAY;AAC3B,MAAA,OAAA,CAAQ,EAAE,CAAA,GAAI,MAAM,IAAA,CAAK,QAAA,CAAS,IAAI,KAAK,CAAA;AAAA,IAC7C;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -43,7 +43,7 @@ interface RoadmapDatasource {
|
|
|
43
43
|
* @param comment - The comment to add
|
|
44
44
|
* @returns The created comment
|
|
45
45
|
* @throws NotFoundError - When the referenced feature does not exist
|
|
46
|
-
* @throws
|
|
46
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
47
47
|
*/
|
|
48
48
|
addComment(comment: NewComment): Promise<Comment>;
|
|
49
49
|
/**
|
|
@@ -52,7 +52,7 @@ interface RoadmapDatasource {
|
|
|
52
52
|
* @param featureId - The ID of the feature
|
|
53
53
|
* @returns Array of comments
|
|
54
54
|
* @throws NotFoundError - When the feature does not exist
|
|
55
|
-
* @throws
|
|
55
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
56
56
|
*/
|
|
57
57
|
getCommentsByFeatureId(featureId: string): Promise<Comment[]>;
|
|
58
58
|
/**
|
|
@@ -60,7 +60,7 @@ interface RoadmapDatasource {
|
|
|
60
60
|
*
|
|
61
61
|
* @param feature - The feature to add
|
|
62
62
|
* @returns The created feature
|
|
63
|
-
* @throws
|
|
63
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
64
64
|
*/
|
|
65
65
|
addFeature(feature: NewFeature & {
|
|
66
66
|
author: string;
|
|
@@ -69,7 +69,7 @@ interface RoadmapDatasource {
|
|
|
69
69
|
* Get all features
|
|
70
70
|
*
|
|
71
71
|
* @returns Array of all features
|
|
72
|
-
* @throws
|
|
72
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
73
73
|
*/
|
|
74
74
|
getAllFeatures(): Promise<Feature[]>;
|
|
75
75
|
/**
|
|
@@ -78,7 +78,7 @@ interface RoadmapDatasource {
|
|
|
78
78
|
* @param id - The ID of the feature
|
|
79
79
|
* @returns The feature
|
|
80
80
|
* @throws NotFoundError - When the feature does not exist
|
|
81
|
-
* @throws
|
|
81
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
82
82
|
*/
|
|
83
83
|
getFeatureById(id: string): Promise<Feature>;
|
|
84
84
|
/**
|
|
@@ -88,7 +88,7 @@ interface RoadmapDatasource {
|
|
|
88
88
|
* @param status - The new status
|
|
89
89
|
* @returns The updated feature
|
|
90
90
|
* @throws NotFoundError - When the feature does not exist
|
|
91
|
-
* @throws
|
|
91
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
92
92
|
*/
|
|
93
93
|
updateFeatureStatus(id: string, status: FeatureStatus): Promise<Feature>;
|
|
94
94
|
/**
|
|
@@ -98,7 +98,7 @@ interface RoadmapDatasource {
|
|
|
98
98
|
* @param voter - The user voting
|
|
99
99
|
* @returns Object with voteAdded (true if added, false if removed) and updated voteCount
|
|
100
100
|
* @throws NotFoundError - When the feature does not exist
|
|
101
|
-
* @throws
|
|
101
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
102
102
|
*/
|
|
103
103
|
toggleVote(featureId: string, voter: string): Promise<{
|
|
104
104
|
voteAdded: boolean;
|
|
@@ -110,7 +110,7 @@ interface RoadmapDatasource {
|
|
|
110
110
|
* @param featureId - The ID of the feature
|
|
111
111
|
* @returns The number of votes
|
|
112
112
|
* @throws NotFoundError - When the feature does not exist
|
|
113
|
-
* @throws
|
|
113
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
114
114
|
*/
|
|
115
115
|
getVoteCount(featureId: string): Promise<number>;
|
|
116
116
|
/**
|
|
@@ -118,7 +118,7 @@ interface RoadmapDatasource {
|
|
|
118
118
|
*
|
|
119
119
|
* @param featureIds - Array of feature IDs
|
|
120
120
|
* @returns Object mapping feature IDs to vote counts
|
|
121
|
-
* @throws
|
|
121
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
122
122
|
*/
|
|
123
123
|
getVoteCounts(featureIds: string[]): Promise<Record<string, number>>;
|
|
124
124
|
/**
|
|
@@ -127,7 +127,7 @@ interface RoadmapDatasource {
|
|
|
127
127
|
* @param featureId - The ID of the feature
|
|
128
128
|
* @param voter - The user
|
|
129
129
|
* @returns Boolean indicating if the user has voted
|
|
130
|
-
* @throws
|
|
130
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
131
131
|
*/
|
|
132
132
|
hasVoted(featureId: string, voter: string): Promise<boolean>;
|
|
133
133
|
/**
|
|
@@ -136,7 +136,7 @@ interface RoadmapDatasource {
|
|
|
136
136
|
* @param featureIds - Array of feature IDs
|
|
137
137
|
* @param voter - The user
|
|
138
138
|
* @returns Object mapping feature IDs to boolean (has voted)
|
|
139
|
-
* @throws
|
|
139
|
+
* @throws Error - When the datasource operation fails unexpectedly
|
|
140
140
|
*/
|
|
141
141
|
hasVotedBatch(featureIds: string[], voter: string): Promise<Record<string, boolean>>;
|
|
142
142
|
}
|
|
@@ -66,7 +66,7 @@ function commentsRouter(options) {
|
|
|
66
66
|
router.delete("/:commentId", async (req, res, next) => {
|
|
67
67
|
try {
|
|
68
68
|
if (datasource !== "database") {
|
|
69
|
-
throw new errors.
|
|
69
|
+
throw new errors.NotImplementedError(
|
|
70
70
|
"This operation is not supported for the GitLab roadmap datasource"
|
|
71
71
|
);
|
|
72
72
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commentsRouter.cjs.js","sources":["../../src/routes/commentsRouter.ts"],"sourcesContent":["import express from 'express';\nimport Router from 'express-promise-router';\nimport { RouterOptions } from './router';\nimport { CommentService } from '../services/CommentService';\nimport { PermissionService } from '../services/PermissionService';\nimport { RoadmapNotificationService } from '../services/RoadmapNotificationService';\nimport { RoadmapEventPublisher } from '../services/RoadmapEventPublisher';\nimport { getAdminUsers } from '../config';\nimport {
|
|
1
|
+
{"version":3,"file":"commentsRouter.cjs.js","sources":["../../src/routes/commentsRouter.ts"],"sourcesContent":["import express from 'express';\nimport Router from 'express-promise-router';\nimport { RouterOptions } from './router';\nimport { CommentService } from '../services/CommentService';\nimport { PermissionService } from '../services/PermissionService';\nimport { RoadmapNotificationService } from '../services/RoadmapNotificationService';\nimport { RoadmapEventPublisher } from '../services/RoadmapEventPublisher';\nimport { getAdminUsers } from '../config';\nimport {\n InputError,\n NotAllowedError,\n NotImplementedError,\n} from '@backstage/errors';\n\n/**\n * Router for comment-related endpoints\n */\nexport function commentsRouter(options: RouterOptions): express.Router {\n const { logger, db, datasource } = options;\n const router = Router();\n\n // Initialize services\n const commentService = new CommentService(db, logger, datasource);\n const permissionService = new PermissionService(options);\n const roadmapNotifications = options.notifications\n ? new RoadmapNotificationService(\n options.notifications,\n logger,\n getAdminUsers(options.config),\n )\n : undefined;\n const eventPublisher = new RoadmapEventPublisher(\n logger,\n options.events,\n options.signals,\n );\n\n // Add a comment to a feature\n router.post('/', async (req, res, next) => {\n try {\n const username = await permissionService.getUsername(req);\n const { featureId, text } = req.body;\n\n const comment = await commentService.addComment({\n featureId,\n text,\n author: username,\n });\n\n if (roadmapNotifications) {\n // Fire-and-forget: neither the feature lookup nor the send may fail\n // the comment request.\n db.getFeatureById(comment.featureId)\n .then(feature =>\n roadmapNotifications.notifyCommentAdded(feature, username),\n )\n .catch(error => {\n logger.warn(\n `Failed to send comment notification for feature ${featureId}: ${error}`,\n );\n });\n }\n\n eventPublisher.commentAdded(comment, username);\n res.status(201).json(comment);\n } catch (error) {\n next(error);\n }\n });\n\n // Get comments for a specific feature\n router.get('/', async (req, res, next) => {\n try {\n const { featureId } = req.query;\n if (!featureId || typeof featureId !== 'string') {\n throw new InputError('featureId is required and must be a string');\n }\n\n const comments = await commentService.getCommentsByFeatureId(featureId);\n res.status(200).json(comments);\n } catch (error) {\n next(error);\n }\n });\n\n router.delete('/:commentId', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotImplementedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n if (!isAdmin) {\n throw new NotAllowedError('User is not a Roadmap admin');\n }\n const { commentId } = req.params;\n await commentService.deleteComment(commentId);\n eventPublisher.commentDeleted(commentId, username);\n res.status(204).send();\n } catch (error) {\n next(error);\n }\n });\n\n return router;\n}\n"],"names":["Router","CommentService","PermissionService","RoadmapNotificationService","getAdminUsers","RoadmapEventPublisher","InputError","NotImplementedError","NotAllowedError"],"mappings":";;;;;;;;;;;;;;AAiBO,SAAS,eAAe,OAAA,EAAwC;AACrE,EAAA,MAAM,EAAE,MAAA,EAAQ,EAAA,EAAI,UAAA,EAAW,GAAI,OAAA;AACnC,EAAA,MAAM,SAASA,uBAAA,EAAO;AAGtB,EAAA,MAAM,cAAA,GAAiB,IAAIC,6BAAA,CAAe,EAAA,EAAI,QAAQ,UAAU,CAAA;AAChE,EAAA,MAAM,iBAAA,GAAoB,IAAIC,mCAAA,CAAkB,OAAO,CAAA;AACvD,EAAA,MAAM,oBAAA,GAAuB,OAAA,CAAQ,aAAA,GACjC,IAAIC,qDAAA;AAAA,IACF,OAAA,CAAQ,aAAA;AAAA,IACR,MAAA;AAAA,IACAC,oBAAA,CAAc,QAAQ,MAAM;AAAA,GAC9B,GACA,MAAA;AACJ,EAAA,MAAM,iBAAiB,IAAIC,2CAAA;AAAA,IACzB,MAAA;AAAA,IACA,OAAA,CAAQ,MAAA;AAAA,IACR,OAAA,CAAQ;AAAA,GACV;AAGA,EAAA,MAAA,CAAO,IAAA,CAAK,GAAA,EAAK,OAAO,GAAA,EAAK,KAAK,IAAA,KAAS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cAAA,CAAe,sBAAA,CAAuB,SAAS,CAAA;AACtE,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,QAAQ,CAAA;AAAA,IAC/B,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAED,EAAA,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,OAAO,GAAA,EAAK,KAAK,IAAA,KAAS;AACrD,IAAA,IAAI;AACF,MAAA,IAAI,eAAe,UAAA,EAAY;AAC7B,QAAA,MAAM,IAAIC,0BAAA;AAAA,UACR;AAAA,SACF;AAAA,MACF;AACA,MAAA,MAAM,QAAA,GAAW,MAAM,iBAAA,CAAkB,WAAA,CAAY,GAAG,CAAA;AACxD,MAAA,MAAM,OAAA,GAAU,MAAM,iBAAA,CAAkB,cAAA,CAAe,KAAK,QAAQ,CAAA;AACpE,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA,MAAM,IAAIC,uBAAgB,6BAA6B,CAAA;AAAA,MACzD;AACA,MAAA,MAAM,EAAE,SAAA,EAAU,GAAI,GAAA,CAAI,MAAA;AAC1B,MAAA,MAAM,cAAA,CAAe,cAAc,SAAS,CAAA;AAC5C,MAAA,cAAA,CAAe,cAAA,CAAe,WAAW,QAAQ,CAAA;AACjD,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,EAAK;AAAA,IACvB,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
@@ -82,7 +82,7 @@ function featuresRouter(options) {
|
|
|
82
82
|
router.put("/reorder", async (req, res, next) => {
|
|
83
83
|
try {
|
|
84
84
|
if (datasource !== "database") {
|
|
85
|
-
throw new errors.
|
|
85
|
+
throw new errors.NotImplementedError(
|
|
86
86
|
"This operation is not supported for the GitLab roadmap datasource"
|
|
87
87
|
);
|
|
88
88
|
}
|
|
@@ -142,7 +142,7 @@ function featuresRouter(options) {
|
|
|
142
142
|
router.put("/:id", async (req, res, next) => {
|
|
143
143
|
try {
|
|
144
144
|
if (datasource !== "database") {
|
|
145
|
-
throw new errors.
|
|
145
|
+
throw new errors.NotImplementedError(
|
|
146
146
|
"This operation is not supported for the GitLab roadmap datasource"
|
|
147
147
|
);
|
|
148
148
|
}
|
|
@@ -153,6 +153,12 @@ function featuresRouter(options) {
|
|
|
153
153
|
"At least one of title or description is required"
|
|
154
154
|
);
|
|
155
155
|
}
|
|
156
|
+
if (title !== void 0 && typeof title !== "string") {
|
|
157
|
+
throw new errors.InputError("title must be a string");
|
|
158
|
+
}
|
|
159
|
+
if (description !== void 0 && typeof description !== "string") {
|
|
160
|
+
throw new errors.InputError("description must be a string");
|
|
161
|
+
}
|
|
156
162
|
const username = await permissionService.getUsername(req);
|
|
157
163
|
const isAdmin = await permissionService.isRoadmapAdmin(req, username);
|
|
158
164
|
if (!isAdmin) {
|
|
@@ -171,7 +177,7 @@ function featuresRouter(options) {
|
|
|
171
177
|
router.delete("/:id", async (req, res, next) => {
|
|
172
178
|
try {
|
|
173
179
|
if (datasource !== "database") {
|
|
174
|
-
throw new errors.
|
|
180
|
+
throw new errors.NotImplementedError(
|
|
175
181
|
"This operation is not supported for the GitLab roadmap datasource"
|
|
176
182
|
);
|
|
177
183
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"featuresRouter.cjs.js","sources":["../../src/routes/featuresRouter.ts"],"sourcesContent":["import express from 'express';\nimport Router from 'express-promise-router';\nimport { RouterOptions } from './router';\nimport { FeatureStatus } from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { FeatureService } from '../services/FeatureService';\nimport { PermissionService } from '../services/PermissionService';\nimport { RoadmapNotificationService } from '../services/RoadmapNotificationService';\nimport { RoadmapEventPublisher } from '../services/RoadmapEventPublisher';\nimport { getAdminUsers } from '../config';\n\nimport { NotAllowedError, InputError } from '@backstage/errors';\n/**\n * Router for feature-related endpoints\n */\nexport function featuresRouter(options: RouterOptions): express.Router {\n const { logger, db, boardColumns, datasource } = options;\n const router = Router();\n\n // Initialize services\n const featureService = new FeatureService(\n db,\n logger,\n boardColumns,\n datasource,\n );\n const permissionService = new PermissionService(options);\n const roadmapNotifications = options.notifications\n ? new RoadmapNotificationService(\n options.notifications,\n logger,\n getAdminUsers(options.config),\n )\n : undefined;\n const eventPublisher = new RoadmapEventPublisher(\n logger,\n options.events,\n options.signals,\n );\n\n router.get('/board-config', async (_req, res, next) => {\n try {\n res.status(200).json(options.boardConfigResponse);\n } catch (error) {\n next(error);\n }\n });\n\n // Create new feature\n router.post('/', async (req, res, next) => {\n try {\n const username = await permissionService.getUsername(req);\n const canCreate = await permissionService.canCreateFeature(req, username);\n if (!canCreate) {\n throw new NotAllowedError(\n 'User does not have permission to create features',\n );\n }\n const { title, description } = req.body;\n\n if (!title || typeof title !== 'string') {\n throw new InputError('Title is required');\n }\n if (!description || typeof description !== 'string') {\n throw new InputError('Description is required');\n }\n\n const feature = await featureService.addFeature(\n { title, description },\n username,\n );\n roadmapNotifications?.notifyFeatureCreated(feature, username);\n eventPublisher.featureCreated(feature, username);\n res.status(201).json(feature);\n } catch (error) {\n next(error);\n }\n });\n\n // Get all features. The search collator module reads this endpoint with a\n // service token, so it must stay accessible to service principals.\n router.get('/', async (req, res, next) => {\n try {\n const raw = req.query.includeBeyondRetention;\n const includeBeyondRetention =\n datasource === 'database' &&\n typeof raw === 'string' &&\n (raw === 'true' || raw === '1');\n const features = await featureService.listFeaturesForBoard(\n includeBeyondRetention,\n );\n res.status(200).json(features);\n } catch (error) {\n next(error);\n }\n });\n\n router.put('/reorder', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotAllowedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n if (!isAdmin) {\n throw new NotAllowedError('User is not a Roadmap admin');\n }\n const { status, orderedIds } = req.body as {\n status?: string;\n orderedIds?: string[];\n };\n if (\n !status ||\n !Object.values(FeatureStatus).includes(status as FeatureStatus)\n ) {\n throw new InputError('Invalid status');\n }\n if (\n !Array.isArray(orderedIds) ||\n !orderedIds.every(id => typeof id === 'string')\n ) {\n throw new InputError('orderedIds must be an array of string ids');\n }\n await featureService.reorderFeatures(status as FeatureStatus, orderedIds);\n eventPublisher.boardReordered(status as FeatureStatus, username);\n res.status(204).send();\n } catch (error) {\n next(error);\n }\n });\n\n // Update feature status (admin only) — after literal paths, before PUT /:id\n router.put('/:id/status', async (req, res, next) => {\n try {\n const { id } = req.params;\n const { status } = req.body;\n\n if (!status || !Object.values(FeatureStatus).includes(status)) {\n throw new InputError(\n `Invalid status. Must be one of: ${Object.values(FeatureStatus).join(\n ', ',\n )}`,\n );\n }\n\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n\n if (!isAdmin) {\n throw new NotAllowedError('User is not a Roadmap admin');\n }\n\n const before = await featureService.getFeatureById(id);\n const updatedFeature = await featureService.updateFeatureStatus(\n id,\n status,\n );\n if (before.status !== updatedFeature.status) {\n roadmapNotifications?.notifyStatusChanged(\n updatedFeature,\n before.status,\n username,\n );\n eventPublisher.statusChanged(updatedFeature, before.status, username);\n }\n res.status(200).json(updatedFeature);\n } catch (error) {\n next(error);\n }\n });\n\n router.put('/:id', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotAllowedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const { id } = req.params;\n const { title, description } = req.body as {\n title?: string;\n description?: string;\n };\n if (title === undefined && description === undefined) {\n throw new InputError(\n 'At least one of title or description is required',\n );\n }\n\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n\n if (!isAdmin) {\n await featureService.assertAuthorSuggestedOrNotFound(id, username);\n }\n const updated = await featureService.updateFeatureDetails(id, {\n title,\n description,\n });\n eventPublisher.featureUpdated(updated, username);\n res.status(200).json(updated);\n } catch (error) {\n next(error);\n }\n });\n\n router.delete('/:id', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotAllowedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const { id } = req.params;\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n\n if (!isAdmin) {\n await featureService.assertAuthorSuggestedOrNotFound(id, username);\n }\n await featureService.deleteFeature(id);\n eventPublisher.featureDeleted(id, username);\n res.status(204).send();\n } catch (error) {\n next(error);\n }\n });\n\n // Get feature by ID (must be after static paths like /reorder)\n router.get('/:id', async (req, res, next) => {\n try {\n const { id } = req.params;\n const feature = await featureService.getFeatureById(id);\n res.status(200).json(feature);\n } catch (error) {\n next(error);\n }\n });\n\n return router;\n}\n"],"names":["Router","FeatureService","PermissionService","RoadmapNotificationService","getAdminUsers","RoadmapEventPublisher","NotAllowedError","InputError","FeatureStatus"],"mappings":";;;;;;;;;;;;;;;AAcO,SAAS,eAAe,OAAA,EAAwC;AACrE,EAAA,MAAM,EAAE,MAAA,EAAQ,EAAA,EAAI,YAAA,EAAc,YAAW,GAAI,OAAA;AACjD,EAAA,MAAM,SAASA,uBAAA,EAAO;AAGtB,EAAA,MAAM,iBAAiB,IAAIC,6BAAA;AAAA,IACzB,EAAA;AAAA,IACA,MAAA;AAAA,IACA,YAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,MAAM,iBAAA,GAAoB,IAAIC,mCAAA,CAAkB,OAAO,CAAA;AACvD,EAAA,MAAM,oBAAA,GAAuB,OAAA,CAAQ,aAAA,GACjC,IAAIC,qDAAA;AAAA,IACF,OAAA,CAAQ,aAAA;AAAA,IACR,MAAA;AAAA,IACAC,oBAAA,CAAc,QAAQ,MAAM;AAAA,GAC9B,GACA,MAAA;AACJ,EAAA,MAAM,iBAAiB,IAAIC,2CAAA;AAAA,I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,QAAQ,CAAA;AAAA,MACnE;AACA,MAAA,MAAM,cAAA,CAAe,cAAc,EAAE,CAAA;AACrC,MAAA,cAAA,CAAe,cAAA,CAAe,IAAI,QAAQ,CAAA;AAC1C,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,EAAK;AAAA,IACvB,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAGD,EAAA,MAAA,CAAO,GAAA,CAAI,MAAA,EAAQ,OAAO,GAAA,EAAK,KAAK,IAAA,KAAS;AAC3C,IAAA,IAAI;AACF,MAAA,MAAM,EAAE,EAAA,EAAG,GAAI,GAAA,CAAI,MAAA;AACnB,MAAA,MAAM,OAAA,GAAU,MAAM,cAAA,CAAe,cAAA,CAAe,EAAE,CAAA;AACtD,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,OAAO,CAAA;AAAA,IAC9B,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"featuresRouter.cjs.js","sources":["../../src/routes/featuresRouter.ts"],"sourcesContent":["import express from 'express';\nimport Router from 'express-promise-router';\nimport { RouterOptions } from './router';\nimport { FeatureStatus } from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { FeatureService } from '../services/FeatureService';\nimport { PermissionService } from '../services/PermissionService';\nimport { RoadmapNotificationService } from '../services/RoadmapNotificationService';\nimport { RoadmapEventPublisher } from '../services/RoadmapEventPublisher';\nimport { getAdminUsers } from '../config';\n\nimport {\n NotAllowedError,\n NotImplementedError,\n InputError,\n} from '@backstage/errors';\n/**\n * Router for feature-related endpoints\n */\nexport function featuresRouter(options: RouterOptions): express.Router {\n const { logger, db, boardColumns, datasource } = options;\n const router = Router();\n\n // Initialize services\n const featureService = new FeatureService(\n db,\n logger,\n boardColumns,\n datasource,\n );\n const permissionService = new PermissionService(options);\n const roadmapNotifications = options.notifications\n ? new RoadmapNotificationService(\n options.notifications,\n logger,\n getAdminUsers(options.config),\n )\n : undefined;\n const eventPublisher = new RoadmapEventPublisher(\n logger,\n options.events,\n options.signals,\n );\n\n router.get('/board-config', async (_req, res, next) => {\n try {\n res.status(200).json(options.boardConfigResponse);\n } catch (error) {\n next(error);\n }\n });\n\n // Create new feature\n router.post('/', async (req, res, next) => {\n try {\n const username = await permissionService.getUsername(req);\n const canCreate = await permissionService.canCreateFeature(req, username);\n if (!canCreate) {\n throw new NotAllowedError(\n 'User does not have permission to create features',\n );\n }\n const { title, description } = req.body;\n\n if (!title || typeof title !== 'string') {\n throw new InputError('Title is required');\n }\n if (!description || typeof description !== 'string') {\n throw new InputError('Description is required');\n }\n\n const feature = await featureService.addFeature(\n { title, description },\n username,\n );\n roadmapNotifications?.notifyFeatureCreated(feature, username);\n eventPublisher.featureCreated(feature, username);\n res.status(201).json(feature);\n } catch (error) {\n next(error);\n }\n });\n\n // Get all features. The search collator module reads this endpoint with a\n // service token, so it must stay accessible to service principals.\n router.get('/', async (req, res, next) => {\n try {\n const raw = req.query.includeBeyondRetention;\n const includeBeyondRetention =\n datasource === 'database' &&\n typeof raw === 'string' &&\n (raw === 'true' || raw === '1');\n const features = await featureService.listFeaturesForBoard(\n includeBeyondRetention,\n );\n res.status(200).json(features);\n } catch (error) {\n next(error);\n }\n });\n\n router.put('/reorder', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotImplementedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n if (!isAdmin) {\n throw new NotAllowedError('User is not a Roadmap admin');\n }\n const { status, orderedIds } = req.body as {\n status?: string;\n orderedIds?: string[];\n };\n if (\n !status ||\n !Object.values(FeatureStatus).includes(status as FeatureStatus)\n ) {\n throw new InputError('Invalid status');\n }\n if (\n !Array.isArray(orderedIds) ||\n !orderedIds.every(id => typeof id === 'string')\n ) {\n throw new InputError('orderedIds must be an array of string ids');\n }\n await featureService.reorderFeatures(status as FeatureStatus, orderedIds);\n eventPublisher.boardReordered(status as FeatureStatus, username);\n res.status(204).send();\n } catch (error) {\n next(error);\n }\n });\n\n // Update feature status (admin only) — after literal paths, before PUT /:id\n router.put('/:id/status', async (req, res, next) => {\n try {\n const { id } = req.params;\n const { status } = req.body;\n\n if (!status || !Object.values(FeatureStatus).includes(status)) {\n throw new InputError(\n `Invalid status. Must be one of: ${Object.values(FeatureStatus).join(\n ', ',\n )}`,\n );\n }\n\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n\n if (!isAdmin) {\n throw new NotAllowedError('User is not a Roadmap admin');\n }\n\n const before = await featureService.getFeatureById(id);\n const updatedFeature = await featureService.updateFeatureStatus(\n id,\n status,\n );\n if (before.status !== updatedFeature.status) {\n roadmapNotifications?.notifyStatusChanged(\n updatedFeature,\n before.status,\n username,\n );\n eventPublisher.statusChanged(updatedFeature, before.status, username);\n }\n res.status(200).json(updatedFeature);\n } catch (error) {\n next(error);\n }\n });\n\n router.put('/:id', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotImplementedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const { id } = req.params;\n const { title, description } = req.body as {\n title?: unknown;\n description?: unknown;\n };\n if (title === undefined && description === undefined) {\n throw new InputError(\n 'At least one of title or description is required',\n );\n }\n if (title !== undefined && typeof title !== 'string') {\n throw new InputError('title must be a string');\n }\n if (description !== undefined && typeof description !== 'string') {\n throw new InputError('description must be a string');\n }\n\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n\n if (!isAdmin) {\n await featureService.assertAuthorSuggestedOrNotFound(id, username);\n }\n const updated = await featureService.updateFeatureDetails(id, {\n title,\n description,\n });\n eventPublisher.featureUpdated(updated, username);\n res.status(200).json(updated);\n } catch (error) {\n next(error);\n }\n });\n\n router.delete('/:id', async (req, res, next) => {\n try {\n if (datasource !== 'database') {\n throw new NotImplementedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n const { id } = req.params;\n const username = await permissionService.getUsername(req);\n const isAdmin = await permissionService.isRoadmapAdmin(req, username);\n\n if (!isAdmin) {\n await featureService.assertAuthorSuggestedOrNotFound(id, username);\n }\n await featureService.deleteFeature(id);\n eventPublisher.featureDeleted(id, username);\n res.status(204).send();\n } catch (error) {\n next(error);\n }\n });\n\n // Get feature by ID (must be after static paths like /reorder)\n router.get('/:id', async (req, res, next) => {\n try {\n const { id } = req.params;\n const feature = await featureService.getFeatureById(id);\n res.status(200).json(feature);\n } catch (error) {\n next(error);\n }\n });\n\n return router;\n}\n"],"names":["Router","FeatureService","PermissionService","RoadmapNotificationService","getAdminUsers","RoadmapEventPublisher","NotAllowedError","InputError","NotImplementedError","FeatureStatus"],"mappings":";;;;;;;;;;;;;;;AAkBO,SAAS,eAAe,OAAA,EAAwC;AACrE,EAAA,MAAM,EAAE,MAAA,EAAQ,EAAA,EAAI,YAAA,EAAc,YAAW,GAAI,OAAA;AACjD,EAAA,MAAM,SAASA,uBAAA,EAAO;AAGtB,EAAA,MAAM,iBAAiB,IAAIC,6BAAA;AAAA,IACzB,EAAA;AAAA,IACA,MAAA;AAAA,IACA,YAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,MAAM,iBAAA,GAAoB,IAAIC,mCAAA,CAAkB,OAAO,CAAA;AACvD,EAAA,MAAM,oBAAA,GAAuB,OAAA,CAAQ,aAAA,GACjC,IAAIC,qDAAA;AAAA,IACF,OAAA,CAAQ,aAAA;AAAA,IACR,MAAA;AAAA,IACAC,oBAAA,CAAc,QAAQ,MAAM;AAAA,GAC9B,GACA,MAAA;AACJ,EAAA,MAAM,iBAAiB,IAAIC,2CAAA;AAAA,IACzB,MAAA;AAAA,IACA,OAAA,CAAQ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nB,MAAA,MAAM,QAAA,GAAW,MAAM,iBAAA,CAAkB,WAAA,CAAY,GAAG,CAAA;AACxD,MAAA,MAAM,OAAA,GAAU,MAAM,iBAAA,CAAkB,cAAA,CAAe,KAAK,QAAQ,CAAA;AAEpE,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA,MAAM,cAAA,CAAe,+BAAA,CAAgC,EAAA,EAAI,QAAQ,CAAA;AAAA,MACnE;AACA,MAAA,MAAM,cAAA,CAAe,cAAc,EAAE,CAAA;AACrC,MAAA,cAAA,CAAe,cAAA,CAAe,IAAI,QAAQ,CAAA;AAC1C,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,EAAK;AAAA,IACvB,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAGD,EAAA,MAAA,CAAO,GAAA,CAAI,MAAA,EAAQ,OAAO,GAAA,EAAK,KAAK,IAAA,KAAS;AAC3C,IAAA,IAAI;AACF,MAAA,MAAM,EAAE,EAAA,EAAG,GAAI,GAAA,CAAI,MAAA;AACnB,MAAA,MAAM,OAAA,GAAU,MAAM,cAAA,CAAe,cAAA,CAAe,EAAE,CAAA;AACtD,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,OAAO,CAAA;AAAA,IAC9B,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
@@ -10,6 +10,19 @@ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'defau
|
|
|
10
10
|
|
|
11
11
|
var Router__default = /*#__PURE__*/_interopDefaultCompat(Router);
|
|
12
12
|
|
|
13
|
+
const MAX_BATCH_IDS = 250;
|
|
14
|
+
function parseBatchIds(idsParam) {
|
|
15
|
+
if (!idsParam || typeof idsParam !== "string") {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
const ids = [...new Set(idsParam.split(",").filter(Boolean))];
|
|
19
|
+
if (ids.length > MAX_BATCH_IDS) {
|
|
20
|
+
throw new errors.InputError(
|
|
21
|
+
`Too many ids: at most ${MAX_BATCH_IDS} are allowed per request`
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
return ids;
|
|
25
|
+
}
|
|
13
26
|
function votesRouter(options) {
|
|
14
27
|
const { logger, db } = options;
|
|
15
28
|
const router = Router__default.default();
|
|
@@ -22,12 +35,7 @@ function votesRouter(options) {
|
|
|
22
35
|
);
|
|
23
36
|
router.get("/counts", async (req, res, next) => {
|
|
24
37
|
try {
|
|
25
|
-
const
|
|
26
|
-
if (!idsParam || typeof idsParam !== "string" || idsParam === "") {
|
|
27
|
-
res.json({});
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
30
|
-
const featureIds = idsParam.split(",").filter(Boolean);
|
|
38
|
+
const featureIds = parseBatchIds(req.query.ids);
|
|
31
39
|
if (featureIds.length === 0) {
|
|
32
40
|
res.json({});
|
|
33
41
|
return;
|
|
@@ -40,12 +48,7 @@ function votesRouter(options) {
|
|
|
40
48
|
});
|
|
41
49
|
router.get("/user/batch", async (req, res, next) => {
|
|
42
50
|
try {
|
|
43
|
-
const
|
|
44
|
-
if (!idsParam || typeof idsParam !== "string" || idsParam === "") {
|
|
45
|
-
res.json({});
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
const featureIds = idsParam.split(",").filter(Boolean);
|
|
51
|
+
const featureIds = parseBatchIds(req.query.ids);
|
|
49
52
|
if (featureIds.length === 0) {
|
|
50
53
|
res.json({});
|
|
51
54
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"votesRouter.cjs.js","sources":["../../src/routes/votesRouter.ts"],"sourcesContent":["import express from 'express';\nimport Router from 'express-promise-router';\nimport { RouterOptions } from './router';\nimport { VoteService } from '../services/VoteService';\nimport { PermissionService } from '../services/PermissionService';\nimport { RoadmapEventPublisher } from '../services/RoadmapEventPublisher';\nimport { InputError } from '@backstage/errors';\n\n/**\n * Router for vote-related endpoints\n */\nexport function votesRouter(options: RouterOptions): express.Router {\n const { logger, db } = options;\n const router = Router();\n\n // Initialize services\n const voteService = new VoteService(db, logger);\n const permissionService = new PermissionService(options);\n const eventPublisher = new RoadmapEventPublisher(\n logger,\n options.events,\n options.signals,\n );\n\n // Get vote counts for multiple features\n router.get('/counts', async (req, res, next) => {\n try {\n const
|
|
1
|
+
{"version":3,"file":"votesRouter.cjs.js","sources":["../../src/routes/votesRouter.ts"],"sourcesContent":["import express from 'express';\nimport Router from 'express-promise-router';\nimport { RouterOptions } from './router';\nimport { VoteService } from '../services/VoteService';\nimport { PermissionService } from '../services/PermissionService';\nimport { RoadmapEventPublisher } from '../services/RoadmapEventPublisher';\nimport { InputError } from '@backstage/errors';\n\n/**\n * Upper bound on ids per batch request. The board fetches votes for the\n * features it renders, so this is generous for real clients while keeping a\n * single request from fanning out into unbounded database/GitLab work.\n */\nconst MAX_BATCH_IDS = 250;\n\nfunction parseBatchIds(idsParam: unknown): string[] {\n if (!idsParam || typeof idsParam !== 'string') {\n return [];\n }\n const ids = [...new Set(idsParam.split(',').filter(Boolean))];\n if (ids.length > MAX_BATCH_IDS) {\n throw new InputError(\n `Too many ids: at most ${MAX_BATCH_IDS} are allowed per request`,\n );\n }\n return ids;\n}\n\n/**\n * Router for vote-related endpoints\n */\nexport function votesRouter(options: RouterOptions): express.Router {\n const { logger, db } = options;\n const router = Router();\n\n // Initialize services\n const voteService = new VoteService(db, logger);\n const permissionService = new PermissionService(options);\n const eventPublisher = new RoadmapEventPublisher(\n logger,\n options.events,\n options.signals,\n );\n\n // Get vote counts for multiple features\n router.get('/counts', async (req, res, next) => {\n try {\n const featureIds = parseBatchIds(req.query.ids);\n\n if (featureIds.length === 0) {\n res.json({});\n return;\n }\n\n const voteCounts = await voteService.getVoteCounts(featureIds);\n res.json(voteCounts);\n } catch (error) {\n next(error);\n }\n });\n\n // Check if user has voted on multiple features (batch)\n router.get('/user/batch', async (req, res, next) => {\n try {\n const featureIds = parseBatchIds(req.query.ids);\n\n if (featureIds.length === 0) {\n res.json({});\n return;\n }\n\n const username = await permissionService.getUsername(req);\n const hasVotedMap = await voteService.hasVotedBatch(featureIds, username);\n\n res.json(hasVotedMap);\n } catch (error) {\n next(error);\n }\n });\n\n // --- Parameterized routes below ---\n\n // Toggle vote for a feature\n router.post('/:featureId', async (req, res, next) => {\n try {\n const featureId = req.params.featureId;\n\n if (!featureId) {\n throw new InputError('Feature ID is required');\n }\n\n const username = await permissionService.getUsername(req);\n const result = await voteService.toggleVote(featureId, username);\n eventPublisher.voteToggled(\n featureId,\n result.voteAdded,\n result.voteCount,\n username,\n );\n\n res.status(200).json(result);\n } catch (error) {\n next(error);\n }\n });\n\n // Get vote count for a feature\n router.get('/:featureId/count', async (req, res, next) => {\n try {\n const featureId = req.params.featureId;\n\n if (!featureId) {\n throw new InputError('Feature ID is required');\n }\n\n const count = await voteService.getVoteCount(featureId);\n res.json(count);\n } catch (error) {\n next(error);\n }\n });\n\n // Check if a user has voted on a feature\n router.get('/:featureId/user', async (req, res, next) => {\n try {\n const featureId = req.params.featureId;\n\n if (!featureId) {\n throw new InputError('Feature ID is required');\n }\n\n const username = await permissionService.getUsername(req);\n const hasVoted = await voteService.hasVoted(featureId, username);\n\n res.json(hasVoted);\n } catch (error) {\n next(error);\n }\n });\n\n return router;\n}\n"],"names":["InputError","Router","VoteService","PermissionService","RoadmapEventPublisher"],"mappings":";;;;;;;;;;;;AAaA,MAAM,aAAA,GAAgB,GAAA;AAEtB,SAAS,cAAc,QAAA,EAA6B;AAClD,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,MAAM,GAAA,GAAM,CAAC,GAAG,IAAI,GAAA,CAAI,QAAA,CAAS,KAAA,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A,MAAA,CAAO,GAAA,CAAI,mBAAA,EAAqB,OAAO,GAAA,EAAK,KAAK,IAAA,KAAS;AACxD,IAAA,IAAI;AACF,MAAA,MAAM,SAAA,GAAY,IAAI,MAAA,CAAO,SAAA;AAE7B,MAAA,IAAI,CAAC,SAAA,EAAW;AACd,QAAA,MAAM,IAAIA,kBAAW,wBAAwB,CAAA;AAAA,MAC/C;AAEA,MAAA,MAAM,KAAA,GAAQ,MAAM,WAAA,CAAY,YAAA,CAAa,SAAS,CAAA;AACtD,MAAA,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IAChB,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAGD,EAAA,MAAA,CAAO,GAAA,CAAI,kBAAA,EAAoB,OAAO,GAAA,EAAK,KAAK,IAAA,KAAS;AACvD,IAAA,IAAI;AACF,MAAA,MAAM,SAAA,GAAY,IAAI,MAAA,CAAO,SAAA;AAE7B,MAAA,IAAI,CAAC,SAAA,EAAW;AACd,QAAA,MAAM,IAAIA,kBAAW,wBAAwB,CAAA;AAAA,MAC/C;AAEA,MAAA,MAAM,QAAA,GAAW,MAAM,iBAAA,CAAkB,WAAA,CAAY,GAAG,CAAA;AACxD,MAAA,MAAM,QAAA,GAAW,MAAM,WAAA,CAAY,QAAA,CAAS,WAAW,QAAQ,CAAA;AAE/D,MAAA,GAAA,CAAI,KAAK,QAAQ,CAAA;AAAA,IACnB,SAAS,KAAA,EAAO;AACd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
@@ -16,10 +16,10 @@ class CommentService {
|
|
|
16
16
|
* Validates a comment before adding it
|
|
17
17
|
*/
|
|
18
18
|
validateNewComment(comment) {
|
|
19
|
-
if (!comment.featureId) {
|
|
20
|
-
throw new errors.InputError("Feature ID is required");
|
|
19
|
+
if (!comment.featureId || typeof comment.featureId !== "string") {
|
|
20
|
+
throw new errors.InputError("Feature ID is required and must be a string");
|
|
21
21
|
}
|
|
22
|
-
if (
|
|
22
|
+
if (typeof comment.text !== "string" || comment.text.trim() === "") {
|
|
23
23
|
throw new errors.InputError("Comment text is required and cannot be empty");
|
|
24
24
|
}
|
|
25
25
|
if (comment.text.length > 1e3) {
|
|
@@ -40,7 +40,7 @@ class CommentService {
|
|
|
40
40
|
/** Database only; GitLab roadmap does not support deleting notes via this plugin. */
|
|
41
41
|
async deleteComment(commentId) {
|
|
42
42
|
if (this.datasource !== "database" || !(this.db instanceof RoadmapDatabaseClient.RoadmapDatabaseClient)) {
|
|
43
|
-
throw new errors.
|
|
43
|
+
throw new errors.NotImplementedError(
|
|
44
44
|
"This operation is not supported for the GitLab roadmap datasource"
|
|
45
45
|
);
|
|
46
46
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CommentService.cjs.js","sources":["../../src/services/CommentService.ts"],"sourcesContent":["import { LoggerService } from '@backstage/backend-plugin-api';\nimport { RoadmapDatasource } from '../types';\nimport { DatasourceType } from '../types';\nimport { CommentServiceInterface } from './types';\nimport {\n Comment,\n NewComment,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { InputError,
|
|
1
|
+
{"version":3,"file":"CommentService.cjs.js","sources":["../../src/services/CommentService.ts"],"sourcesContent":["import { LoggerService } from '@backstage/backend-plugin-api';\nimport { RoadmapDatasource } from '../types';\nimport { DatasourceType } from '../types';\nimport { CommentServiceInterface } from './types';\nimport {\n Comment,\n NewComment,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { InputError, NotImplementedError } from '@backstage/errors';\nimport { RoadmapDatabaseClient } from '../database/RoadmapDatabaseClient';\n\n/**\n * Implementation of the Comment Service\n */\nexport class CommentService implements CommentServiceInterface {\n constructor(\n private readonly db: RoadmapDatasource,\n private readonly logger: LoggerService,\n private readonly datasource: DatasourceType,\n ) {}\n\n /**\n * Validates a comment before adding it\n */\n private validateNewComment(comment: NewComment): void {\n if (!comment.featureId || typeof comment.featureId !== 'string') {\n throw new InputError('Feature ID is required and must be a string');\n }\n\n if (typeof comment.text !== 'string' || comment.text.trim() === '') {\n throw new InputError('Comment text is required and cannot be empty');\n }\n\n if (comment.text.length > 1000) {\n throw new InputError(\n 'Comment text cannot be longer than 1000 characters',\n );\n }\n }\n\n async addComment(comment: NewComment): Promise<Comment> {\n this.logger.info(`Adding comment to feature ${comment.featureId}`);\n this.validateNewComment(comment);\n return this.db.addComment(comment);\n }\n\n async getCommentsByFeatureId(featureId: string): Promise<Comment[]> {\n this.logger.info(`Fetching comments for feature ${featureId}`);\n return this.db.getCommentsByFeatureId(featureId);\n }\n\n /** Database only; GitLab roadmap does not support deleting notes via this plugin. */\n async deleteComment(commentId: string): Promise<void> {\n if (\n this.datasource !== 'database' ||\n !(this.db instanceof RoadmapDatabaseClient)\n ) {\n throw new NotImplementedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n this.logger.info(`Deleting comment ${commentId}`);\n await this.db.deleteCommentById(commentId);\n }\n}\n"],"names":["InputError","RoadmapDatabaseClient","NotImplementedError"],"mappings":";;;;;AAcO,MAAM,cAAA,CAAkD;AAAA,EAC7D,WAAA,CACmB,EAAA,EACA,MAAA,EACA,UAAA,EACjB;AAHiB,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAChB;AAAA,EAHgB,EAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA,EAMX,mBAAmB,OAAA,EAA2B;AACpD,IAAA,IAAI,CAAC,OAAA,CAAQ,SAAA,IAAa,OAAO,OAAA,CAAQ,cAAc,QAAA,EAAU;AAC/D,MAAA,MAAM,IAAIA,kBAAW,6CAA6C,CAAA;AAAA,IACpE;AAEA,IAAA,IAAI,OAAO,QAA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|
requireDatabase() {
|
|
21
21
|
if (this.datasource !== "database" || !(this.db instanceof RoadmapDatabaseClient.RoadmapDatabaseClient)) {
|
|
22
|
-
throw new errors.
|
|
22
|
+
throw new errors.NotImplementedError(
|
|
23
23
|
"This operation is not supported for the GitLab roadmap datasource"
|
|
24
24
|
);
|
|
25
25
|
}
|
|
@@ -89,15 +89,15 @@ class FeatureService {
|
|
|
89
89
|
async updateFeatureDetails(id, fields) {
|
|
90
90
|
const client = this.requireDatabase();
|
|
91
91
|
if (fields.title !== void 0) {
|
|
92
|
-
if (!fields.title.trim()) {
|
|
93
|
-
throw new errors.InputError("Title
|
|
92
|
+
if (typeof fields.title !== "string" || !fields.title.trim()) {
|
|
93
|
+
throw new errors.InputError("Title must be a non-empty string");
|
|
94
94
|
}
|
|
95
95
|
if (fields.title.length > 100) {
|
|
96
96
|
throw new errors.InputError("Title cannot be longer than 100 characters");
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
|
-
if (fields.description !== void 0 && !fields.description.trim()) {
|
|
100
|
-
throw new errors.InputError("Description
|
|
99
|
+
if (fields.description !== void 0 && (typeof fields.description !== "string" || !fields.description.trim())) {
|
|
100
|
+
throw new errors.InputError("Description must be a non-empty string");
|
|
101
101
|
}
|
|
102
102
|
return client.updateFeatureDetails(id, fields);
|
|
103
103
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FeatureService.cjs.js","sources":["../../src/services/FeatureService.ts"],"sourcesContent":["import { LoggerService } from '@backstage/backend-plugin-api';\nimport { RoadmapDatasource } from '../types';\nimport { DatasourceType } from '../types';\nimport { FeatureServiceInterface } from './types';\nimport {\n Feature,\n NewFeature,\n FeatureStatus,\n RoadmapBoardColumnResolved,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { InputError, NotAllowedError } from '@backstage/errors';\nimport { filterFeaturesForBoardList } from './featureBoardFilter';\nimport { RoadmapDatabaseClient } from '../database/RoadmapDatabaseClient';\n\n/**\n * Feature business logic: validation, board list filtering (visibility + retention),\n * and database-only writes. GitLab mutations that are not supported stay in the router.\n */\nexport class FeatureService implements FeatureServiceInterface {\n constructor(\n private readonly db: RoadmapDatasource,\n private readonly logger: LoggerService,\n private readonly boardColumns: RoadmapBoardColumnResolved[],\n private readonly datasource: DatasourceType,\n ) {}\n\n /** Ensures we are on the Knex-backed datasource before DB-only operations. */\n private requireDatabase(): RoadmapDatabaseClient {\n if (\n this.datasource !== 'database' ||\n !(this.db instanceof RoadmapDatabaseClient)\n ) {\n throw new NotAllowedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n return this.db;\n }\n\n /** Rules for creating a suggestion from the API. */\n private validateNewFeature(feature: NewFeature): void {\n if (!feature.title || feature.title.trim() === '') {\n throw new InputError('Title is required and cannot be empty');\n }\n\n if (!feature.description || feature.description.trim() === '') {\n throw new InputError('Description is required and cannot be empty');\n }\n\n if (feature.title.length > 100) {\n throw new InputError('Title cannot be longer than 100 characters');\n }\n }\n\n /** Ensures status values match the shared enum (used by status changes and reorder). */\n private validateStatus(status: FeatureStatus): void {\n const validStatuses = Object.values(FeatureStatus);\n if (!validStatuses.includes(status)) {\n throw new InputError(\n `Invalid status: ${status}. Must be one of: ${validStatuses.join(\n ', ',\n )}`,\n );\n }\n }\n\n /**\n * Primary list for the board: applies column visibility and, for the database\n * datasource, per-column retention unless `includeBeyondRetention` is true.\n */\n async listFeaturesForBoard(\n includeBeyondRetention: boolean,\n ): Promise<Feature[]> {\n this.logger.info('Fetching roadmap features for board list');\n const raw = await this.db.getAllFeatures();\n return filterFeaturesForBoardList(raw, this.boardColumns, {\n includeBeyondRetention,\n datasource: this.datasource,\n });\n }\n\n /** Same as the board list with default retention filtering (backward compatible name). */\n async getAllFeatures(): Promise<Feature[]> {\n return this.listFeaturesForBoard(false);\n }\n\n async getFeatureById(id: string): Promise<Feature> {\n this.logger.info(`Fetching feature with id ${id}`);\n return this.db.getFeatureById(id);\n }\n\n /** Creates a new feature in Suggested status with the given author ref. */\n async addFeature(feature: NewFeature, author: string): Promise<Feature> {\n this.logger.info(`Adding new feature: ${feature.title} by ${author}`);\n this.validateNewFeature(feature);\n return this.db.addFeature({ ...feature, author });\n }\n\n /**\n * Admin workflow: change status. Supported for both database and GitLab\n * (GitLab implementation updates labels on the issue).\n */\n async updateFeatureStatus(\n id: string,\n status: FeatureStatus,\n ): Promise<Feature> {\n this.logger.info(`Updating feature ${id} status to ${status}`);\n this.validateStatus(status);\n return this.db.updateFeatureStatus(id, status);\n }\n\n /**\n * Database only. Router decides admin vs author-on-Suggested; this layer only validates fields.\n */\n async updateFeatureDetails(\n id: string,\n fields: { title?: string; description?: string },\n ): Promise<Feature> {\n const client = this.requireDatabase();\n if (fields.title !== undefined) {\n if (!fields.title.trim()) {\n throw new InputError('Title cannot be empty');\n }\n if (fields.title.length > 100) {\n throw new InputError('Title cannot be longer than 100 characters');\n }\n }\n if (fields.description !== undefined && !fields.description.trim()) {\n throw new InputError('Description cannot be empty');\n }\n return client.updateFeatureDetails(id, fields);\n }\n\n /** Database only: hard-delete feature row (and FK-cascaded comments/votes). */\n async deleteFeature(id: string): Promise<void> {\n const client = this.requireDatabase();\n await client.deleteFeature(id);\n }\n\n /**\n * Database only: persist admin drag-and-drop order within a single status column.\n */\n async reorderFeatures(\n status: FeatureStatus,\n orderedIds: string[],\n ): Promise<void> {\n this.validateStatus(status);\n const client = this.requireDatabase();\n await client.reorderFeaturesInStatus(status, orderedIds);\n }\n\n /**\n * Non-admin edit/delete path: loads the feature and ensures it is Suggested\n * and owned by `username`; otherwise throws NotAllowed. Missing ids surface as NotFound from the datasource.\n */\n async assertAuthorSuggestedOrNotFound(\n id: string,\n username: string,\n ): Promise<Feature> {\n const feature = await this.db.getFeatureById(id);\n if (feature.status !== FeatureStatus.Suggested) {\n throw new NotAllowedError(\n 'Only suggested features can be edited by the author',\n );\n }\n if (feature.author !== username) {\n throw new NotAllowedError(\n 'You can only edit your own suggested features',\n );\n }\n return feature;\n }\n}\n"],"names":["Ro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CAAA;AAC1B,IAAA,MAAM,MAAA,GAAS,KAAK,eAAA,EAAgB;AACpC,IAAA,MAAM,MAAA,CAAO,uBAAA,CAAwB,MAAA,EAAQ,UAAU,CAAA;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,+BAAA,CACJ,EAAA,EACA,QAAA,EACkB;AAClB,IAAA,MAAM,OAAA,GAAU,MAAM,IAAA,CAAK,EAAA,CAAG,eAAe,EAAE,CAAA;AAC/C,IAAA,IAAI,OAAA,CAAQ,MAAA,KAAWC,0CAAA,CAAc,SAAA,EAAW;AAC9C,MAAA,MAAM,IAAIF,sBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,WAAW,QAAA,EAAU;AAC/B,MAAA,MAAM,IAAIA,sBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"FeatureService.cjs.js","sources":["../../src/services/FeatureService.ts"],"sourcesContent":["import { LoggerService } from '@backstage/backend-plugin-api';\nimport { RoadmapDatasource } from '../types';\nimport { DatasourceType } from '../types';\nimport { FeatureServiceInterface } from './types';\nimport {\n Feature,\n NewFeature,\n FeatureStatus,\n RoadmapBoardColumnResolved,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport {\n InputError,\n NotAllowedError,\n NotImplementedError,\n} from '@backstage/errors';\nimport { filterFeaturesForBoardList } from './featureBoardFilter';\nimport { RoadmapDatabaseClient } from '../database/RoadmapDatabaseClient';\n\n/**\n * Feature business logic: validation, board list filtering (visibility + retention),\n * and database-only writes. GitLab mutations that are not supported stay in the router.\n */\nexport class FeatureService implements FeatureServiceInterface {\n constructor(\n private readonly db: RoadmapDatasource,\n private readonly logger: LoggerService,\n private readonly boardColumns: RoadmapBoardColumnResolved[],\n private readonly datasource: DatasourceType,\n ) {}\n\n /** Ensures we are on the Knex-backed datasource before DB-only operations. */\n private requireDatabase(): RoadmapDatabaseClient {\n if (\n this.datasource !== 'database' ||\n !(this.db instanceof RoadmapDatabaseClient)\n ) {\n throw new NotImplementedError(\n 'This operation is not supported for the GitLab roadmap datasource',\n );\n }\n return this.db;\n }\n\n /** Rules for creating a suggestion from the API. */\n private validateNewFeature(feature: NewFeature): void {\n if (!feature.title || feature.title.trim() === '') {\n throw new InputError('Title is required and cannot be empty');\n }\n\n if (!feature.description || feature.description.trim() === '') {\n throw new InputError('Description is required and cannot be empty');\n }\n\n if (feature.title.length > 100) {\n throw new InputError('Title cannot be longer than 100 characters');\n }\n }\n\n /** Ensures status values match the shared enum (used by status changes and reorder). */\n private validateStatus(status: FeatureStatus): void {\n const validStatuses = Object.values(FeatureStatus);\n if (!validStatuses.includes(status)) {\n throw new InputError(\n `Invalid status: ${status}. Must be one of: ${validStatuses.join(\n ', ',\n )}`,\n );\n }\n }\n\n /**\n * Primary list for the board: applies column visibility and, for the database\n * datasource, per-column retention unless `includeBeyondRetention` is true.\n */\n async listFeaturesForBoard(\n includeBeyondRetention: boolean,\n ): Promise<Feature[]> {\n this.logger.info('Fetching roadmap features for board list');\n const raw = await this.db.getAllFeatures();\n return filterFeaturesForBoardList(raw, this.boardColumns, {\n includeBeyondRetention,\n datasource: this.datasource,\n });\n }\n\n /** Same as the board list with default retention filtering (backward compatible name). */\n async getAllFeatures(): Promise<Feature[]> {\n return this.listFeaturesForBoard(false);\n }\n\n async getFeatureById(id: string): Promise<Feature> {\n this.logger.info(`Fetching feature with id ${id}`);\n return this.db.getFeatureById(id);\n }\n\n /** Creates a new feature in Suggested status with the given author ref. */\n async addFeature(feature: NewFeature, author: string): Promise<Feature> {\n this.logger.info(`Adding new feature: ${feature.title} by ${author}`);\n this.validateNewFeature(feature);\n return this.db.addFeature({ ...feature, author });\n }\n\n /**\n * Admin workflow: change status. Supported for both database and GitLab\n * (GitLab implementation updates labels on the issue).\n */\n async updateFeatureStatus(\n id: string,\n status: FeatureStatus,\n ): Promise<Feature> {\n this.logger.info(`Updating feature ${id} status to ${status}`);\n this.validateStatus(status);\n return this.db.updateFeatureStatus(id, status);\n }\n\n /**\n * Database only. Router decides admin vs author-on-Suggested; this layer only validates fields.\n */\n async updateFeatureDetails(\n id: string,\n fields: { title?: string; description?: string },\n ): Promise<Feature> {\n const client = this.requireDatabase();\n if (fields.title !== undefined) {\n if (typeof fields.title !== 'string' || !fields.title.trim()) {\n throw new InputError('Title must be a non-empty string');\n }\n if (fields.title.length > 100) {\n throw new InputError('Title cannot be longer than 100 characters');\n }\n }\n if (\n fields.description !== undefined &&\n (typeof fields.description !== 'string' || !fields.description.trim())\n ) {\n throw new InputError('Description must be a non-empty string');\n }\n return client.updateFeatureDetails(id, fields);\n }\n\n /** Database only: hard-delete feature row (and FK-cascaded comments/votes). */\n async deleteFeature(id: string): Promise<void> {\n const client = this.requireDatabase();\n await client.deleteFeature(id);\n }\n\n /**\n * Database only: persist admin drag-and-drop order within a single status column.\n */\n async reorderFeatures(\n status: FeatureStatus,\n orderedIds: string[],\n ): Promise<void> {\n this.validateStatus(status);\n const client = this.requireDatabase();\n await client.reorderFeaturesInStatus(status, orderedIds);\n }\n\n /**\n * Non-admin edit/delete path: loads the feature and ensures it is Suggested\n * and owned by `username`; otherwise throws NotAllowed. Missing ids surface as NotFound from the datasource.\n */\n async assertAuthorSuggestedOrNotFound(\n id: string,\n username: string,\n ): Promise<Feature> {\n const feature = await this.db.getFeatureById(id);\n if (feature.status !== FeatureStatus.Suggested) {\n throw new NotAllowedError(\n 'Only suggested features can be edited by the author',\n );\n }\n if (feature.author !== username) {\n throw new NotAllowedError(\n 'You can only edit your own suggested features',\n );\n }\n return feature;\n }\n}\n"],"names":["RoadmapDatabaseClient","NotImplementedError","InputError","FeatureStatus","filterFeaturesForBoardList","NotAllowedError"],"mappings":";;;;;;;AAsBO,MAAM,cAAA,CAAkD;AAAA,EAC7D,WAAA,CACmB,EAAA,EACA,MAAA,EACA,YAAA,EACA,UAAA,EACjB;AAJ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A,CAAO,uBAAA,CAAwB,MAAA,EAAQ,UAAU,CAAA;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,+BAAA,CACJ,EAAA,EACA,QAAA,EACkB;AAClB,IAAA,MAAM,OAAA,GAAU,MAAM,IAAA,CAAK,EAAA,CAAG,eAAe,EAAE,CAAA;AAC/C,IAAA,IAAI,OAAA,CAAQ,MAAA,KAAWC,0CAAA,CAAc,SAAA,EAAW;AAC9C,MAAA,MAAM,IAAIE,sBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,WAAW,QAAA,EAAU;AAC/B,MAAA,MAAM,IAAIA,sBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;"}
|
|
@@ -58,6 +58,9 @@ class PermissionService {
|
|
|
58
58
|
return this.checkPermission(req, username, backstagePluginRoadmapCommon.roadmapAdminPermission);
|
|
59
59
|
}
|
|
60
60
|
async canCreateFeature(req, username) {
|
|
61
|
+
if (!this.options.permissions) {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
61
64
|
return this.checkPermission(req, username, backstagePluginRoadmapCommon.roadmapCreatePermission);
|
|
62
65
|
}
|
|
63
66
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PermissionService.cjs.js","sources":["../../src/services/PermissionService.ts"],"sourcesContent":["import { Request } from 'express';\nimport { PermissionServiceInterface } from './types';\nimport { RouterOptions } from '../routes/router';\nimport {\n roadmapAdminPermission,\n roadmapCreatePermission,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { BasicPermission } from '@backstage/plugin-permission-common';\nimport { NotFoundError, NotAllowedError } from '@backstage/errors';\nimport { getAdminUsers } from '../config';\nimport {\n AuthorizeResult,\n DefinitivePolicyDecision,\n} from '@backstage/plugin-permission-common';\n\n/**\n * Implementation of the Permission Service\n */\nexport class PermissionService implements PermissionServiceInterface {\n private readonly options: RouterOptions;\n\n constructor(options: RouterOptions) {\n this.options = options;\n }\n\n async getUsername(req: Request): Promise<string> {\n const { httpAuth, userInfo, logger } = this.options;\n const credentials = await httpAuth.credentials(req);\n if (!credentials) {\n logger.warn('Unauthorized access attempt');\n throw new NotAllowedError('Unauthorized access');\n }\n const user = await userInfo.getUserInfo(credentials);\n const username = user?.userEntityRef?.toString();\n if (!username) {\n logger.warn('User not found');\n throw new NotFoundError('User not found');\n }\n return username;\n }\n\n async checkPermission(\n req: Request,\n username: string,\n permission: BasicPermission,\n ): Promise<boolean> {\n const { config, logger, permissions, httpAuth } = this.options;\n const adminUsers = getAdminUsers(config);\n\n // Admin users early exit\n if (adminUsers.includes(username)) {\n return true;\n }\n\n // Check if permissions service is available\n if (!permissions) {\n return false;\n }\n\n // Authenticate request credentials\n const credentials = await httpAuth.credentials(req);\n if (!credentials) {\n logger.warn(`Unauthorized access attempt by user ${username}`);\n throw new NotAllowedError('Unauthorized access');\n }\n\n let decision: DefinitivePolicyDecision = { result: AuthorizeResult.DENY };\n\n try {\n // Authorize user with permission service\n decision = (\n await permissions.authorize([{ permission }], {\n credentials,\n })\n )[0];\n\n const isAllowed = decision.result === AuthorizeResult.ALLOW;\n logger.info(\n `Permission ${permission.name} ${\n isAllowed ? 'granted' : 'denied'\n } to user ${username}`,\n );\n\n return isAllowed;\n } catch (error) {\n logger.error(`Error while authorizing user ${username}`);\n throw new NotAllowedError('Permission check failed');\n }\n }\n\n async isRoadmapAdmin(req: Request, username: string): Promise<boolean> {\n return this.checkPermission(req, username, roadmapAdminPermission);\n }\n\n async canCreateFeature(req: Request, username: string): Promise<boolean> {\n return this.checkPermission(req, username, roadmapCreatePermission);\n }\n}\n"],"names":["NotAllowedError","NotFoundError","config","getAdminUsers","AuthorizeResult","roadmapAdminPermission","roadmapCreatePermission"],"mappings":";;;;;;;AAkBO,MAAM,iBAAA,CAAwD;AAAA,EAClD,OAAA;AAAA,EAEjB,YAAY,OAAA,EAAw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AA,EAAuC,QAAQ,CAAA,CAAE,CAAA;AAC7D,MAAA,MAAM,IAAIF,uBAAgB,qBAAqB,CAAA;AAAA,IACjD;AAEA,IAAA,IAAI,QAAA,GAAqC,EAAE,MAAA,EAAQI,sCAAA,CAAgB,IAAA,EAAK;AAExE,IAAA,IAAI;AAEF,MAAA,QAAA,GAAA,CACE,MAAM,WAAA,CAAY,SAAA,CAAU,CAAC,EAAE,UAAA,EAAY,CAAA,EAAG;AAAA,QAC5C;AAAA,OACD,GACD,CAAC,CAAA;AAEH,MAAA,MAAM,SAAA,GAAY,QAAA,CAAS,MAAA,KAAWA,sCAAA,CAAgB,KAAA;AACtD,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,CAAA,WAAA,EAAc,WAAW,IAAI,CAAA,CAAA,EAC3B,YAAY,SAAA,GAAY,QAC1B,YAAY,QAAQ,CAAA;AAAA,OACtB;AAEA,MAAA,OAAO,SAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,MAAA,CAAO,KAAA,CAAM,CAAA,6BAAA,EAAgC,QAAQ,CAAA,CAAE,CAAA;AACvD,MAAA,MAAM,IAAIJ,uBAAgB,yBAAyB,CAAA;AAAA,IACrD;AAAA,EACF;AAAA,EAEA,MAAM,cAAA,CAAe,GAAA,EAAc,QAAA,EAAoC;AACrE,IAAA,OAAO,IAAA,CAAK,eAAA,CAAgB,GAAA,EAAK,QAAA,EAAUK,mDAAsB,CAAA;AAAA,EACnE;AAAA,EAEA,MAAM,gBAAA,CAAiB,GAAA,EAAc,QAAA,EAAoC;
|
|
1
|
+
{"version":3,"file":"PermissionService.cjs.js","sources":["../../src/services/PermissionService.ts"],"sourcesContent":["import { Request } from 'express';\nimport { PermissionServiceInterface } from './types';\nimport { RouterOptions } from '../routes/router';\nimport {\n roadmapAdminPermission,\n roadmapCreatePermission,\n} from '@rothenbergt/backstage-plugin-roadmap-common';\nimport { BasicPermission } from '@backstage/plugin-permission-common';\nimport { NotFoundError, NotAllowedError } from '@backstage/errors';\nimport { getAdminUsers } from '../config';\nimport {\n AuthorizeResult,\n DefinitivePolicyDecision,\n} from '@backstage/plugin-permission-common';\n\n/**\n * Implementation of the Permission Service\n */\nexport class PermissionService implements PermissionServiceInterface {\n private readonly options: RouterOptions;\n\n constructor(options: RouterOptions) {\n this.options = options;\n }\n\n async getUsername(req: Request): Promise<string> {\n const { httpAuth, userInfo, logger } = this.options;\n const credentials = await httpAuth.credentials(req);\n if (!credentials) {\n logger.warn('Unauthorized access attempt');\n throw new NotAllowedError('Unauthorized access');\n }\n const user = await userInfo.getUserInfo(credentials);\n const username = user?.userEntityRef?.toString();\n if (!username) {\n logger.warn('User not found');\n throw new NotFoundError('User not found');\n }\n return username;\n }\n\n async checkPermission(\n req: Request,\n username: string,\n permission: BasicPermission,\n ): Promise<boolean> {\n const { config, logger, permissions, httpAuth } = this.options;\n const adminUsers = getAdminUsers(config);\n\n // Admin users early exit\n if (adminUsers.includes(username)) {\n return true;\n }\n\n // Check if permissions service is available\n if (!permissions) {\n return false;\n }\n\n // Authenticate request credentials\n const credentials = await httpAuth.credentials(req);\n if (!credentials) {\n logger.warn(`Unauthorized access attempt by user ${username}`);\n throw new NotAllowedError('Unauthorized access');\n }\n\n let decision: DefinitivePolicyDecision = { result: AuthorizeResult.DENY };\n\n try {\n // Authorize user with permission service\n decision = (\n await permissions.authorize([{ permission }], {\n credentials,\n })\n )[0];\n\n const isAllowed = decision.result === AuthorizeResult.ALLOW;\n logger.info(\n `Permission ${permission.name} ${\n isAllowed ? 'granted' : 'denied'\n } to user ${username}`,\n );\n\n return isAllowed;\n } catch (error) {\n logger.error(`Error while authorizing user ${username}`);\n throw new NotAllowedError('Permission check failed');\n }\n }\n\n async isRoadmapAdmin(req: Request, username: string): Promise<boolean> {\n return this.checkPermission(req, username, roadmapAdminPermission);\n }\n\n async canCreateFeature(req: Request, username: string): Promise<boolean> {\n // Without the permission framework, any authenticated user can suggest\n // features, while the adminUsers list only gates admin actions.\n if (!this.options.permissions) {\n return true;\n }\n return this.checkPermission(req, username, roadmapCreatePermission);\n }\n}\n"],"names":["NotAllowedError","NotFoundError","config","getAdminUsers","AuthorizeResult","roadmapAdminPermission","roadmapCreatePermission"],"mappings":";;;;;;;AAkBO,MAAM,iBAAA,CAAwD;AAAA,EAClD,OAAA;AAAA,EAEjB,YAAY,OAAA,EAAwB;AAClC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA,EAEA,MAAM,YAAY,GAAA,EAA+B;AAC/C,IAAA,MAAM,EAAE,QAAA,EAAU,QAAA,EAAU,MAAA,KAAW,IAAA,CAAK,OAAA;AAC5C,IAAA,MAAM,WAAA,GAAc,MAAM,QAAA,CAAS,WAAA,CAAY,GAAG,CAAA;AAClD,IAAA,IAAI,CAAC,WAAA,EAAa;AAChB,MAAA,MAAA,CAAO,KAAK,6BAA6B,CAAA;AACzC,MAAA,MAAM,IAAIA,uBAAgB,qBAAqB,CAAA;AAAA,IACjD;AACA,IAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,WAAA,CAAY,WAAW,CAAA;AACnD,IAAA,MAAM,QAAA,GAAW,IAAA,EAAM,aAAA,EAAe,QAAA,EAAS;AAC/C,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAA,CAAO,KAAK,gBAAgB,CAAA;AAC5B,MAAA,MAAM,IAAIC,qBAAc,gBAAgB,CAAA;AAAA,IAC1C;AACA,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,MAAM,eAAA,CACJ,GAAA,EACA,QAAA,EACA,UAAA,EACkB;AAClB,IAAA,MAAM,UAAEC,QAAA,EAAQ,MAAA,EAAQ,WAAA,EAAa,QAAA,KAAa,IAAA,CAAK,OAAA;AACvD,IAAA,MAAM,UAAA,GAAaC,qBAAcD,QAAM,CAAA;AAGvC,IAAA,IAAI,UAAA,CAAW,QAAA,CAAS,QAAQ,CAAA,EAAG;AACjC,MAAA,OAAO,IAAA;AAAA,IACT;AAGA,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,WAAA,EAAa;AAC7B,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,IAAA,CAAK,eAAA,CAAgB,GAAA,EAAK,QAAA,EAAUC,oDAAuB,CAAA;AAAA,EACpE;AACF;;;;"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rothenbergt/backstage-plugin-roadmap-backend",
|
|
3
3
|
"description": "Backstage Roadmap plugin backend",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.1",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"@backstage/plugin-auth-backend": "^0.29.1",
|
|
53
53
|
"@backstage/plugin-auth-backend-module-guest-provider": "^0.2.20",
|
|
54
54
|
"@backstage/plugin-catalog-backend": "^3.8.0",
|
|
55
|
+
"@backstage/plugin-catalog-node": "^2.2.2",
|
|
55
56
|
"@backstage/plugin-notifications-backend": "^0.6.6",
|
|
56
57
|
"@backstage/plugin-permission-backend": "^0.7.2",
|
|
57
58
|
"@backstage/plugin-permission-backend-module-allow-all-policy": "^0.2.10",
|