@abayramli/backstage-plugin-scaffolder-backend-module-template-pulse 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # Template Pulse database history
2
+
3
+ Let Template Pulse read run history directly from Scaffolder's database.
4
+
5
+ ```sh
6
+ yarn workspace backend add @abayramli/backstage-plugin-scaffolder-backend-module-template-pulse@0.1.0
7
+ ```
8
+
9
+ Register it alongside your Scaffolder backend:
10
+
11
+ ```ts
12
+ backend.add(import('@abayramli/backstage-plugin-scaffolder-backend-module-template-pulse'));
13
+ ```
14
+
15
+ Set `templatePulse.historySource: database` and configure permissions using the [installation guide](https://github.com/alibayramli/template-pulse#add-to-backstage).
16
+
17
+ - Uses Scaffolder's existing database connection to read its standard SQL tables without changing them. Tested with SQLite and PostgreSQL.
18
+ - Checks the database structure after Scaffolder starts and finishes its migrations.
19
+ - Supports the built-in `IS_TASK_OWNER` permission rule. For custom task stores or permission rules, set `templatePulse.historySource: service`.
20
+ - After upgrading Scaffolder, check that its database structure still works with this module.
2
21
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+
3
+ function orderExecutionDetails(query, sort) {
4
+ const column = {
5
+ templateName: "template_name",
6
+ userRef: "user_ref",
7
+ status: "status",
8
+ createdAt: "created_at",
9
+ durationMs: "duration_ms"
10
+ }[sort.sortBy ?? "createdAt"];
11
+ const direction = sort.sortDirection === "ascending" ? "asc" : "desc";
12
+ if (column === "duration_ms" || column === "user_ref")
13
+ query.orderByRaw("?? IS NULL ASC", [column]);
14
+ if (["template_name", "user_ref", "status"].includes(column))
15
+ query.orderByRaw(`LOWER(??) ${direction}`, [column]);
16
+ else query.orderBy(column, direction);
17
+ query.orderBy("id", "desc");
18
+ return query;
19
+ }
20
+ function executionProjection(db, cohort, postgres) {
21
+ const eventStatus = postgres ? "(e.body::jsonb #>> '{status}')" : "json_extract(e.body, '$.status')";
22
+ const finishedAt = db("task_events as e").max("e.created_at").whereRaw("?? = ??", ["e.task_id", "t.id"]).whereIn("e.event_type", ["completion", "cancelled"]).andWhere(
23
+ (builder) => builder.whereRaw(`${eventStatus} IS NULL`).orWhereRaw(`${eventStatus} = t.status`)
24
+ );
25
+ const metadata = cohort.clone().select(finishedAt.as("finished_at"));
26
+ const elapsed = postgres ? "EXTRACT(EPOCH FROM (finished_at - created_at)) * 1000" : "ROUND((julianday(finished_at) - julianday(created_at)) * 86400000)";
27
+ return db.from(metadata.as("metadata")).select(
28
+ "id",
29
+ "status",
30
+ "created_at",
31
+ "template_ref",
32
+ "template_name",
33
+ "user_ref"
34
+ ).select(
35
+ db.raw(`CASE WHEN status IN ('completed', 'failed', 'cancelled')
36
+ AND finished_at >= created_at THEN ${elapsed} END AS duration_ms`)
37
+ );
38
+ }
39
+ function filterExecutionDetails(query, filters) {
40
+ if (filters.status) query.where("status", filters.status);
41
+ for (const term of filters.query?.toLowerCase().split(/\s+/).filter(Boolean) ?? []) {
42
+ const pattern = `%${term.replace(/[!%_]/g, (value) => `!${value}`)}%`;
43
+ query.andWhere((builder) => {
44
+ for (const column of [
45
+ "id",
46
+ "template_ref",
47
+ "template_name",
48
+ "user_ref"
49
+ ]) {
50
+ builder.orWhereRaw(
51
+ "LOWER(COALESCE(CAST(?? AS TEXT), '')) LIKE ? ESCAPE '!'",
52
+ [column, pattern]
53
+ );
54
+ }
55
+ });
56
+ }
57
+ return query;
58
+ }
59
+ function metricsQuery(db, executions, group) {
60
+ const groupColumn = group === "template" ? "template_ref" : "COALESCE(user_ref, 'unknown')";
61
+ const partition = group ? `PARTITION BY ${groupColumn}` : "";
62
+ const successful = "status = 'completed' AND duration_ms IS NOT NULL";
63
+ const ranked = db.from(executions.clone().as("executions")).select("*").select(
64
+ db.raw(`ROW_NUMBER() OVER (${partition} ORDER BY
65
+ CASE WHEN ${successful} THEN 0 ELSE 1 END, duration_ms, id) AS duration_rank`),
66
+ db.raw(
67
+ `SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) OVER (${partition}) AS timed_count`
68
+ ),
69
+ db.raw(
70
+ `ROW_NUMBER() OVER (${partition} ORDER BY created_at DESC, id DESC) AS latest_rank`
71
+ )
72
+ );
73
+ const result = db.from(ranked.as("ranked")).select(
74
+ db.raw("COUNT(*) AS total"),
75
+ db.raw(
76
+ "SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed"
77
+ ),
78
+ db.raw("SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed"),
79
+ db.raw(
80
+ "SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled"
81
+ ),
82
+ db.raw(
83
+ "SUM(CASE WHEN status IN ('open', 'processing') THEN 1 ELSE 0 END) AS active"
84
+ ),
85
+ db.raw("COUNT(DISTINCT NULLIF(user_ref, '')) AS users"),
86
+ db.raw("COUNT(DISTINCT NULLIF(template_ref, 'unknown')) AS templates"),
87
+ db.raw(`SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) AS timed_completed`),
88
+ db.raw(`AVG(CASE WHEN ${successful} THEN duration_ms END) AS average_ms`),
89
+ db.raw(`MAX(CASE WHEN ${successful}
90
+ AND duration_rank = CAST((timed_count * 95 + 99) / 100 AS INTEGER)
91
+ THEN duration_ms END) AS p95_ms`)
92
+ );
93
+ if (group) {
94
+ result.select(
95
+ db.raw(`${groupColumn} AS id`),
96
+ db.raw("MAX(created_at) AS last_run")
97
+ ).select(
98
+ db.raw("MAX(CASE WHEN latest_rank = 1 THEN template_name END) AS name")
99
+ ).groupByRaw(groupColumn);
100
+ }
101
+ return result;
102
+ }
103
+ function mapMetrics(row) {
104
+ const count = (key) => Number(row[key] ?? 0);
105
+ const completed = count("completed");
106
+ const failed = count("failed");
107
+ return {
108
+ total: count("total"),
109
+ completed,
110
+ failed,
111
+ cancelled: count("cancelled"),
112
+ active: count("active"),
113
+ users: count("users"),
114
+ templates: count("templates"),
115
+ timedCompleted: count("timed_completed"),
116
+ successRate: completed + failed ? 100 * completed / (completed + failed) : void 0,
117
+ averageMs: row.average_ms === null || row.average_ms === void 0 ? void 0 : Number(row.average_ms),
118
+ p95Ms: row.p95_ms === null || row.p95_ms === void 0 ? void 0 : Number(row.p95_ms)
119
+ };
120
+ }
121
+
122
+ exports.executionProjection = executionProjection;
123
+ exports.filterExecutionDetails = filterExecutionDetails;
124
+ exports.mapMetrics = mapMetrics;
125
+ exports.metricsQuery = metricsQuery;
126
+ exports.orderExecutionDetails = orderExecutionDetails;
127
+ //# sourceMappingURL=historySql.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"historySql.cjs.js","sources":["../src/historySql.ts"],"sourcesContent":["import type { Knex } from 'knex';\nimport type {\n ExecutionMetrics,\n ExecutionQuery,\n} from '@abayramli/backstage-plugin-template-pulse-common';\n\n/** Order public metadata before LIMIT/OFFSET, with missing values last in either direction. */\nexport function orderExecutionDetails<T extends Knex.QueryBuilder>(\n query: T,\n sort: Pick<ExecutionQuery, 'sortBy' | 'sortDirection'>,\n) {\n const column = {\n templateName: 'template_name',\n userRef: 'user_ref',\n status: 'status',\n createdAt: 'created_at',\n durationMs: 'duration_ms',\n }[sort.sortBy ?? 'createdAt'];\n const direction = sort.sortDirection === 'ascending' ? 'asc' : 'desc';\n if (column === 'duration_ms' || column === 'user_ref')\n query.orderByRaw('?? IS NULL ASC', [column]);\n if (['template_name', 'user_ref', 'status'].includes(column))\n query.orderByRaw(`LOWER(??) ${direction}`, [column]);\n else query.orderBy(column, direction);\n query.orderBy('id', 'desc');\n return query;\n}\n\n/** Project only execution metadata and timing; task specs and event bodies stay in SQL. */\nexport function executionProjection(\n db: Knex,\n cohort: Knex.QueryBuilder,\n postgres: boolean,\n) {\n const eventStatus = postgres\n ? \"(e.body::jsonb #>> '{status}')\"\n : \"json_extract(e.body, '$.status')\";\n const finishedAt = db('task_events as e')\n .max('e.created_at')\n .whereRaw('?? = ??', ['e.task_id', 't.id'])\n .whereIn('e.event_type', ['completion', 'cancelled'])\n .andWhere(builder =>\n builder\n .whereRaw(`${eventStatus} IS NULL`)\n .orWhereRaw(`${eventStatus} = t.status`),\n );\n const metadata = cohort.clone().select(finishedAt.as('finished_at'));\n const elapsed = postgres\n ? 'EXTRACT(EPOCH FROM (finished_at - created_at)) * 1000'\n : 'ROUND((julianday(finished_at) - julianday(created_at)) * 86400000)';\n return db\n .from(metadata.as('metadata'))\n .select(\n 'id',\n 'status',\n 'created_at',\n 'template_ref',\n 'template_name',\n 'user_ref',\n )\n .select(\n db.raw(`CASE WHEN status IN ('completed', 'failed', 'cancelled')\n AND finished_at >= created_at THEN ${elapsed} END AS duration_ms`),\n );\n}\n\n/** Search is literal, parameterized and limited to the same public metadata as service history. */\nexport function filterExecutionDetails(\n query: Knex.QueryBuilder,\n filters: { status?: string; query?: string },\n) {\n if (filters.status) query.where('status', filters.status);\n for (const term of filters.query\n ?.toLowerCase()\n .split(/\\s+/)\n .filter(Boolean) ?? []) {\n const pattern = `%${term.replace(/[!%_]/g, value => `!${value}`)}%`;\n query.andWhere(builder => {\n for (const column of [\n 'id',\n 'template_ref',\n 'template_name',\n 'user_ref',\n ]) {\n // CAST also supports Scaffolder's PostgreSQL UUID task IDs.\n builder.orWhereRaw(\n \"LOWER(COALESCE(CAST(?? AS TEXT), '')) LIKE ? ESCAPE '!'\",\n [column, pattern],\n );\n }\n });\n }\n return query;\n}\n\n/** Compute complete metrics and nearest-rank P95 in the database, independent of detail pagination. */\nexport function metricsQuery(\n db: Knex,\n executions: Knex.QueryBuilder,\n group?: 'template' | 'user',\n) {\n const groupColumn =\n group === 'template' ? 'template_ref' : \"COALESCE(user_ref, 'unknown')\";\n const partition = group ? `PARTITION BY ${groupColumn}` : '';\n const successful = \"status = 'completed' AND duration_ms IS NOT NULL\";\n const ranked = db\n .from(executions.clone().as('executions'))\n .select('*')\n .select(\n db.raw(`ROW_NUMBER() OVER (${partition} ORDER BY\n CASE WHEN ${successful} THEN 0 ELSE 1 END, duration_ms, id) AS duration_rank`),\n db.raw(\n `SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) OVER (${partition}) AS timed_count`,\n ),\n db.raw(\n `ROW_NUMBER() OVER (${partition} ORDER BY created_at DESC, id DESC) AS latest_rank`,\n ),\n );\n const result = db.from(ranked.as('ranked')).select(\n db.raw('COUNT(*) AS total'),\n db.raw(\n \"SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed\",\n ),\n db.raw(\"SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed\"),\n db.raw(\n \"SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled\",\n ),\n db.raw(\n \"SUM(CASE WHEN status IN ('open', 'processing') THEN 1 ELSE 0 END) AS active\",\n ),\n db.raw(\"COUNT(DISTINCT NULLIF(user_ref, '')) AS users\"),\n db.raw(\"COUNT(DISTINCT NULLIF(template_ref, 'unknown')) AS templates\"),\n db.raw(`SUM(CASE WHEN ${successful} THEN 1 ELSE 0 END) AS timed_completed`),\n db.raw(`AVG(CASE WHEN ${successful} THEN duration_ms END) AS average_ms`),\n db.raw(`MAX(CASE WHEN ${successful}\n AND duration_rank = CAST((timed_count * 95 + 99) / 100 AS INTEGER)\n THEN duration_ms END) AS p95_ms`),\n );\n if (group) {\n result\n .select(\n db.raw(`${groupColumn} AS id`),\n db.raw('MAX(created_at) AS last_run'),\n )\n .select(\n db.raw('MAX(CASE WHEN latest_rank = 1 THEN template_name END) AS name'),\n )\n .groupByRaw(groupColumn);\n }\n return result;\n}\n\nexport function mapMetrics(row: Record<string, unknown>): ExecutionMetrics {\n const count = (key: string) => Number(row[key] ?? 0);\n const completed = count('completed');\n const failed = count('failed');\n return {\n total: count('total'),\n completed,\n failed,\n cancelled: count('cancelled'),\n active: count('active'),\n users: count('users'),\n templates: count('templates'),\n timedCompleted: count('timed_completed'),\n successRate:\n completed + failed ? (100 * completed) / (completed + failed) : undefined,\n averageMs:\n row.average_ms === null || row.average_ms === undefined\n ? undefined\n : Number(row.average_ms),\n p95Ms:\n row.p95_ms === null || row.p95_ms === undefined\n ? undefined\n : Number(row.p95_ms),\n };\n}\n"],"names":[],"mappings":";;AAOO,SAAS,qBAAA,CACd,OACA,IAAA,EACA;AACA,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,YAAA,EAAc,eAAA;AAAA,IACd,OAAA,EAAS,UAAA;AAAA,IACT,MAAA,EAAQ,QAAA;AAAA,IACR,SAAA,EAAW,YAAA;AAAA,IACX,UAAA,EAAY;AAAA,GACd,CAAE,IAAA,CAAK,MAAA,IAAU,WAAW,CAAA;AAC5B,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,aAAA,KAAkB,WAAA,GAAc,KAAA,GAAQ,MAAA;AAC/D,EAAA,IAAI,MAAA,KAAW,iBAAiB,MAAA,KAAW,UAAA;AACzC,IAAA,KAAA,CAAM,UAAA,CAAW,gBAAA,EAAkB,CAAC,MAAM,CAAC,CAAA;AAC7C,EAAA,IAAI,CAAC,eAAA,EAAiB,UAAA,EAAY,QAAQ,CAAA,CAAE,SAAS,MAAM,CAAA;AACzD,IAAA,KAAA,CAAM,WAAW,CAAA,UAAA,EAAa,SAAS,CAAA,CAAA,EAAI,CAAC,MAAM,CAAC,CAAA;AAAA,OAChD,KAAA,CAAM,OAAA,CAAQ,MAAA,EAAQ,SAAS,CAAA;AACpC,EAAA,KAAA,CAAM,OAAA,CAAQ,MAAM,MAAM,CAAA;AAC1B,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,mBAAA,CACd,EAAA,EACA,MAAA,EACA,QAAA,EACA;AACA,EAAA,MAAM,WAAA,GAAc,WAChB,gCAAA,GACA,kCAAA;AACJ,EAAA,MAAM,UAAA,GA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AAAA,IACtB,KAAA,EAAO,MAAM,OAAO,CAAA;AAAA,IACpB,SAAA,EAAW,MAAM,WAAW,CAAA;AAAA,IAC5B,cAAA,EAAgB,MAAM,iBAAiB,CAAA;AAAA,IACvC,aACE,SAAA,GAAY,MAAA,GAAU,GAAA,GAAM,SAAA,IAAc,YAAY,MAAA,CAAA,GAAU,MAAA;AAAA,IAClE,SAAA,EACE,GAAA,CAAI,UAAA,KAAe,IAAA,IAAQ,GAAA,CAAI,eAAe,MAAA,GAC1C,MAAA,GACA,MAAA,CAAO,GAAA,CAAI,UAAU,CAAA;AAAA,IAC3B,KAAA,EACE,GAAA,CAAI,MAAA,KAAW,IAAA,IAAQ,GAAA,CAAI,WAAW,MAAA,GAClC,MAAA,GACA,MAAA,CAAO,GAAA,CAAI,MAAM;AAAA,GACzB;AACF;;;;;;"}
@@ -0,0 +1,307 @@
1
+ 'use strict';
2
+
3
+ var errors = require('@backstage/errors');
4
+ var pluginPermissionCommon = require('@backstage/plugin-permission-common');
5
+ var historySql = require('./historySql.cjs.js');
6
+
7
+ function applyConditions(query, criteria) {
8
+ if ("allOf" in criteria) {
9
+ if (!criteria.allOf.length) query.whereRaw("1 = 1");
10
+ for (const condition of criteria.allOf)
11
+ query.andWhere((builder) => applyConditions(builder, condition));
12
+ } else if ("anyOf" in criteria) {
13
+ if (!criteria.anyOf.length) query.whereRaw("1 = 0");
14
+ else
15
+ query.andWhere((builder) => {
16
+ for (const condition of criteria.anyOf)
17
+ builder.orWhere((branch) => applyConditions(branch, condition));
18
+ });
19
+ } else if ("not" in criteria) {
20
+ query.whereNot((builder) => applyConditions(builder, criteria.not));
21
+ } else {
22
+ const owners = criteria.params?.createdBy;
23
+ if (criteria.resourceType !== "scaffolder-task" || criteria.rule !== "IS_TASK_OWNER" || !Array.isArray(owners) || !owners.every((owner) => typeof owner === "string")) {
24
+ throw new errors.NotAllowedError(
25
+ "Database history does not support this task permission condition. Use the service history source for custom task rules."
26
+ );
27
+ }
28
+ query.whereIn("t.created_by", owners);
29
+ }
30
+ }
31
+ function isoDate(value) {
32
+ if (value instanceof Date) return value.toISOString();
33
+ return new Date(
34
+ value.includes("T") ? value : `${value.replace(" ", "T")}Z`
35
+ ).toISOString();
36
+ }
37
+ class DatabaseHistoryStore {
38
+ constructor(getClient, maxHistoryRows = 1e4) {
39
+ this.getClient = getClient;
40
+ this.maxHistoryRows = maxHistoryRows;
41
+ if (!Number.isInteger(maxHistoryRows) || maxHistoryRows < 1 || maxHistoryRows > 1e5) {
42
+ throw new Error(
43
+ "templatePulse.maxHistoryRows must be an integer between 1 and 100000."
44
+ );
45
+ }
46
+ }
47
+ getClient;
48
+ maxHistoryRows;
49
+ database;
50
+ /** Called after Scaffolder startup, when its own migrations have completed. */
51
+ async initialize() {
52
+ await this.getDatabase();
53
+ }
54
+ getDatabase() {
55
+ this.database ??= this.validateDatabase().catch((error) => {
56
+ this.database = void 0;
57
+ throw error;
58
+ });
59
+ return this.database;
60
+ }
61
+ async validateDatabase() {
62
+ const db = await this.getClient();
63
+ const client = db.client.config.client;
64
+ if (!["pg", "postgres", "postgresql", "better-sqlite3", "sqlite3"].includes(
65
+ client
66
+ )) {
67
+ throw new Error(
68
+ "Database history supports PostgreSQL and SQLite Scaffolder task stores."
69
+ );
70
+ }
71
+ const [taskColumns, eventColumns] = await Promise.all([
72
+ db("tasks").columnInfo(),
73
+ db("task_events").columnInfo()
74
+ ]);
75
+ if (!["id", "spec", "status", "created_at", "created_by"].every(
76
+ (key) => key in taskColumns
77
+ ) || !["task_id", "body", "event_type", "created_at"].every(
78
+ (key) => key in eventColumns
79
+ )) {
80
+ throw new Error(
81
+ "The Scaffolder task store schema is incompatible with database history. Check that Scaffolder migrations have completed and use service history for custom task stores."
82
+ );
83
+ }
84
+ return db;
85
+ }
86
+ async search(query, callerRef, decision, limit) {
87
+ if (query.teamRef && !query.teamMembers)
88
+ throw new errors.InputError(
89
+ "Team membership must be resolved before reading history"
90
+ );
91
+ if (decision.result === pluginPermissionCommon.AuthorizeResult.DENY)
92
+ throw new errors.NotAllowedError("Scaffolder task access denied");
93
+ if (decision.result === pluginPermissionCommon.AuthorizeResult.CONDITIONAL && (decision.pluginId !== "scaffolder" || decision.resourceType !== "scaffolder-task")) {
94
+ throw new errors.NotAllowedError(
95
+ "Unsupported Scaffolder task permission decision"
96
+ );
97
+ }
98
+ const db = await this.getDatabase();
99
+ const postgres = ["pg", "postgres", "postgresql"].includes(
100
+ db.client.config.client
101
+ );
102
+ return db.transaction(
103
+ (transaction) => this.searchDatabase(
104
+ transaction,
105
+ postgres,
106
+ query,
107
+ callerRef,
108
+ decision,
109
+ limit
110
+ ),
111
+ postgres ? { isolationLevel: "repeatable read", readOnly: true } : void 0
112
+ );
113
+ }
114
+ async searchDatabase(db, postgres, query, callerRef, decision, limit) {
115
+ const json = (column, path) => postgres ? `(${column}::jsonb #>> '{${path.join(",")}}')` : `json_extract(${column}, '$.${path.join(".")}')`;
116
+ const userRef = `COALESCE(t.created_by, ${json("t.spec", [
117
+ "user",
118
+ "ref"
119
+ ])})`;
120
+ const templateRef = `COALESCE(${json("t.spec", [
121
+ "templateInfo",
122
+ "entityRef"
123
+ ])}, 'unknown')`;
124
+ const templateName = `COALESCE(${json("t.spec", [
125
+ "templateInfo",
126
+ "entity",
127
+ "metadata",
128
+ "title"
129
+ ])}, ${json("t.spec", [
130
+ "templateInfo",
131
+ "entity",
132
+ "metadata",
133
+ "name"
134
+ ])}, ${json("t.spec", ["templateInfo", "entityRef"])}, 'Unknown template')`;
135
+ const base = db("tasks as t");
136
+ if (decision.result === pluginPermissionCommon.AuthorizeResult.CONDITIONAL)
137
+ applyConditions(base, decision.conditions);
138
+ if (query.scope === "mine") base.whereRaw(`${userRef} = ?`, [callerRef]);
139
+ else if (query.userRef) base.whereRaw(`${userRef} = ?`, [query.userRef]);
140
+ if (query.teamMembers) {
141
+ if (query.teamMembers.length)
142
+ base.whereRaw(
143
+ `${userRef} IN (${query.teamMembers.map(() => "?").join(", ")})`,
144
+ query.teamMembers
145
+ );
146
+ else base.whereRaw("1 = 0");
147
+ }
148
+ const metadata = (source) => source.clone().select(
149
+ "t.id",
150
+ "t.status",
151
+ "t.created_at",
152
+ db.raw(`${templateRef} AS template_ref`),
153
+ db.raw(`${templateName} AS template_name`),
154
+ db.raw(`${userRef} AS user_ref`)
155
+ );
156
+ const latestTemplates = db.from(metadata(base).as("authorized")).select(
157
+ "template_ref AS id",
158
+ "template_name AS name",
159
+ db.raw(
160
+ "ROW_NUMBER() OVER (PARTITION BY template_ref ORDER BY created_at DESC, id DESC) AS latest_rank"
161
+ )
162
+ );
163
+ const counts = await base.clone().count({ total: "t.id" }).first();
164
+ const templateChoices = await db.from(latestTemplates.as("template_choices")).select("id", "name").where("latest_rank", 1).limit(this.maxHistoryRows + 1);
165
+ const userChoices = await base.clone().distinct(db.raw(`${userRef} as ref`)).limit(this.maxHistoryRows + 1);
166
+ if (templateChoices.length > this.maxHistoryRows || userChoices.length > this.maxHistoryRows) {
167
+ throw new errors.InputError(
168
+ "Too many history filter choices. Select a user or ask your administrator to review templatePulse.maxHistoryRows."
169
+ );
170
+ }
171
+ const cohort = base.clone();
172
+ if (!query.allTime) {
173
+ cohort.where(
174
+ "t.created_at",
175
+ ">=",
176
+ postgres ? query.from : query.from.slice(0, 19).replace("T", " ")
177
+ ).where(
178
+ "t.created_at",
179
+ "<",
180
+ postgres ? query.to : query.to.slice(0, 19).replace("T", " ")
181
+ );
182
+ }
183
+ if (query.templateRef)
184
+ cohort.whereRaw(`${templateRef} = ?`, [query.templateRef]);
185
+ const executions = historySql.executionProjection(db, metadata(cohort), postgres);
186
+ const details = historySql.filterExecutionDetails(
187
+ db.from(metadata(cohort).as("cohort")),
188
+ query
189
+ );
190
+ const offset = query.offset ?? 0;
191
+ const sortableDetails = query.sortBy === "durationMs" ? historySql.filterExecutionDetails(db.from(executions.clone().as("cohort")), query) : details.clone();
192
+ const pageIds = historySql.orderExecutionDetails(sortableDetails.select("id"), query).limit(limit).offset(offset);
193
+ const summaryRow = await historySql.metricsQuery(db, executions).select(db.raw("MIN(created_at) AS oldest_at")).first();
194
+ const templateRows = await historySql.metricsQuery(db, executions, "template").limit(
195
+ this.maxHistoryRows + 1
196
+ );
197
+ const userRows = await historySql.metricsQuery(db, executions, "user").limit(
198
+ this.maxHistoryRows + 1
199
+ );
200
+ const matchingCount = await details.clone().count({ total: "*" }).first();
201
+ const rawRows = await historySql.orderExecutionDetails(
202
+ db.from(
203
+ historySql.executionProjection(
204
+ db,
205
+ metadata(base.clone().whereIn("t.id", pageIds)),
206
+ postgres
207
+ ).as("page")
208
+ ).select("*"),
209
+ query
210
+ );
211
+ const dailyRows = await db.from(metadata(cohort).as("cohort")).where(
212
+ "created_at",
213
+ ">=",
214
+ postgres ? query.from : query.from.slice(0, 19).replace("T", " ")
215
+ ).where(
216
+ "created_at",
217
+ "<",
218
+ postgres ? query.to : query.to.slice(0, 19).replace("T", " ")
219
+ ).select(
220
+ db.raw(
221
+ `${postgres ? "to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD')" : "substr(created_at, 1, 10)"} AS date`
222
+ )
223
+ ).select(db.raw("COUNT(*) AS total")).select(
224
+ db.raw(
225
+ "SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed"
226
+ )
227
+ ).select(
228
+ db.raw("SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed")
229
+ ).groupBy("date");
230
+ if (templateRows.length > this.maxHistoryRows || userRows.length > this.maxHistoryRows) {
231
+ throw new errors.InputError(
232
+ "Too many analytics groups. Narrow the template or user filters, or review templatePulse.maxHistoryRows."
233
+ );
234
+ }
235
+ const rows = rawRows.map((row) => {
236
+ const createdAt = isoDate(row.created_at);
237
+ return {
238
+ id: row.id,
239
+ status: row.status,
240
+ templateRef: row.template_ref,
241
+ templateName: row.template_name,
242
+ userRef: row.user_ref ?? void 0,
243
+ createdAt,
244
+ durationMs: row.duration_ms === null || row.duration_ms === void 0 ? void 0 : Number(row.duration_ms)
245
+ };
246
+ });
247
+ const rollups = (results, kind) => results.map((row) => {
248
+ const userName = row.id === "unknown" ? "Unknown user" : row.id;
249
+ return {
250
+ id: row.id,
251
+ name: kind === "template" ? row.name : userName,
252
+ lastRun: isoDate(row.last_run),
253
+ ...historySql.mapMetrics(row)
254
+ };
255
+ }).sort((a, b) => b.total - a.total || a.name.localeCompare(b.name));
256
+ const daily = new Map(dailyRows.map((row) => [row.date, row]));
257
+ const activity = [];
258
+ for (let day = Date.parse(query.from); day < Date.parse(query.to); day += 864e5) {
259
+ const date = new Date(day).toISOString().slice(0, 10);
260
+ const row = daily.get(date);
261
+ const total2 = Number(row?.total ?? 0);
262
+ const completed = Number(row?.completed ?? 0);
263
+ const failed = Number(row?.failed ?? 0);
264
+ activity.push({
265
+ date,
266
+ total: total2,
267
+ completed,
268
+ failed,
269
+ other: total2 - completed - failed
270
+ });
271
+ }
272
+ const summary = historySql.mapMetrics(summaryRow);
273
+ const total = Number(matchingCount?.total ?? 0);
274
+ return {
275
+ scope: query.scope,
276
+ items: rows,
277
+ summary,
278
+ templates: rollups(templateRows, "template"),
279
+ users: rollups(userRows, "user"),
280
+ activity,
281
+ page: { offset, limit, total, hasMore: offset + limit < total },
282
+ facets: {
283
+ templates: [
284
+ ...new Map(
285
+ templateChoices.map((row) => [
286
+ row.id,
287
+ { id: row.id, name: row.name }
288
+ ])
289
+ ).values()
290
+ ].sort((a, b) => a.name.localeCompare(b.name)),
291
+ users: userChoices.map((row) => row.ref).filter(Boolean).sort()
292
+ },
293
+ window: {
294
+ historySource: "database",
295
+ limit,
296
+ scanned: summary.total,
297
+ sourceTotal: Number(counts?.total ?? 0),
298
+ truncated: false,
299
+ oldestAt: summaryRow.oldest_at ? isoDate(summaryRow.oldest_at) : void 0,
300
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
301
+ }
302
+ };
303
+ }
304
+ }
305
+
306
+ exports.DatabaseHistoryStore = DatabaseHistoryStore;
307
+ //# sourceMappingURL=historyStore.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"historyStore.cjs.js","sources":["../src/historyStore.ts"],"sourcesContent":["import type { Knex } from 'knex';\nimport { InputError, NotAllowedError } from '@backstage/errors';\nimport {\n AuthorizeResult,\n type PermissionCondition,\n type PermissionCriteria,\n type QueryPermissionResponse,\n} from '@backstage/plugin-permission-common';\nimport type {\n DailyActivity,\n Execution,\n ExecutionAnalytics,\n ExecutionQuery,\n} from '@abayramli/backstage-plugin-template-pulse-common';\nimport {\n executionProjection,\n filterExecutionDetails,\n mapMetrics,\n metricsQuery,\n orderExecutionDetails,\n} from './historySql';\n\ntype HistoryQuery = ExecutionQuery & { teamMembers?: string[] };\n\nfunction applyConditions(\n query: Knex.QueryBuilder,\n criteria: PermissionCriteria<PermissionCondition>,\n) {\n if ('allOf' in criteria) {\n if (!criteria.allOf.length) query.whereRaw('1 = 1');\n for (const condition of criteria.allOf)\n query.andWhere(builder => applyConditions(builder, condition));\n } else if ('anyOf' in criteria) {\n if (!criteria.anyOf.length) query.whereRaw('1 = 0');\n else\n query.andWhere(builder => {\n for (const condition of criteria.anyOf)\n builder.orWhere(branch => applyConditions(branch, condition));\n });\n } else if ('not' in criteria) {\n query.whereNot(builder => applyConditions(builder, criteria.not));\n } else {\n const owners = criteria.params?.createdBy;\n if (\n criteria.resourceType !== 'scaffolder-task' ||\n criteria.rule !== 'IS_TASK_OWNER' ||\n !Array.isArray(owners) ||\n !owners.every(owner => typeof owner === 'string')\n ) {\n // Never drop a policy condition that this database adapter cannot enforce.\n throw new NotAllowedError(\n 'Database history does not support this task permission condition. Use the service history source for custom task rules.',\n );\n }\n query.whereIn('t.created_by', owners);\n }\n}\n\nfunction isoDate(value: Date | string) {\n if (value instanceof Date) return value.toISOString();\n return new Date(\n value.includes('T') ? value : `${value.replace(' ', 'T')}Z`,\n ).toISOString();\n}\n\n/** Read-only adapter for the standard Scaffolder SQL task store. */\nexport class DatabaseHistoryStore {\n private database?: Promise<Knex>;\n\n constructor(\n private readonly getClient: () => Promise<Knex>,\n private readonly maxHistoryRows = 10_000,\n ) {\n if (\n !Number.isInteger(maxHistoryRows) ||\n maxHistoryRows < 1 ||\n maxHistoryRows > 100_000\n ) {\n throw new Error(\n 'templatePulse.maxHistoryRows must be an integer between 1 and 100000.',\n );\n }\n }\n\n /** Called after Scaffolder startup, when its own migrations have completed. */\n async initialize(): Promise<void> {\n await this.getDatabase();\n }\n\n private getDatabase(): Promise<Knex> {\n this.database ??= this.validateDatabase().catch(error => {\n this.database = undefined;\n throw error;\n });\n return this.database;\n }\n\n private async validateDatabase(): Promise<Knex> {\n const db = await this.getClient();\n const client = db.client.config.client;\n if (\n !['pg', 'postgres', 'postgresql', 'better-sqlite3', 'sqlite3'].includes(\n client,\n )\n ) {\n throw new Error(\n 'Database history supports PostgreSQL and SQLite Scaffolder task stores.',\n );\n }\n // Scaffolder owns these tables and migrations, as well as the connection pool.\n const [taskColumns, eventColumns] = await Promise.all([\n db('tasks').columnInfo(),\n db('task_events').columnInfo(),\n ]);\n if (\n !['id', 'spec', 'status', 'created_at', 'created_by'].every(\n key => key in taskColumns,\n ) ||\n !['task_id', 'body', 'event_type', 'created_at'].every(\n key => key in eventColumns,\n )\n ) {\n throw new Error(\n 'The Scaffolder task store schema is incompatible with database history. Check that Scaffolder migrations have completed and use service history for custom task stores.',\n );\n }\n return db;\n }\n\n async search(\n query: HistoryQuery,\n callerRef: string,\n decision: QueryPermissionResponse,\n limit: number,\n ): Promise<ExecutionAnalytics> {\n if (query.teamRef && !query.teamMembers)\n throw new InputError(\n 'Team membership must be resolved before reading history',\n );\n if (decision.result === AuthorizeResult.DENY)\n throw new NotAllowedError('Scaffolder task access denied');\n if (\n decision.result === AuthorizeResult.CONDITIONAL &&\n (decision.pluginId !== 'scaffolder' ||\n decision.resourceType !== 'scaffolder-task')\n ) {\n throw new NotAllowedError(\n 'Unsupported Scaffolder task permission decision',\n );\n }\n const db = await this.getDatabase();\n const postgres = ['pg', 'postgres', 'postgresql'].includes(\n db.client.config.client,\n );\n // A single snapshot keeps counts, metrics and details consistent during active task updates.\n return db.transaction(\n transaction =>\n this.searchDatabase(\n transaction,\n postgres,\n query,\n callerRef,\n decision,\n limit,\n ),\n postgres\n ? { isolationLevel: 'repeatable read', readOnly: true }\n : undefined,\n );\n }\n\n private async searchDatabase(\n db: Knex,\n postgres: boolean,\n query: HistoryQuery,\n callerRef: string,\n decision: QueryPermissionResponse,\n limit: number,\n ): Promise<ExecutionAnalytics> {\n const json = (column: string, path: string[]) =>\n postgres\n ? `(${column}::jsonb #>> '{${path.join(',')}}')`\n : `json_extract(${column}, '$.${path.join('.')}')`;\n const userRef = `COALESCE(t.created_by, ${json('t.spec', [\n 'user',\n 'ref',\n ])})`;\n const templateRef = `COALESCE(${json('t.spec', [\n 'templateInfo',\n 'entityRef',\n ])}, 'unknown')`;\n const templateName = `COALESCE(${json('t.spec', [\n 'templateInfo',\n 'entity',\n 'metadata',\n 'title',\n ])}, ${json('t.spec', [\n 'templateInfo',\n 'entity',\n 'metadata',\n 'name',\n ])}, ${json('t.spec', ['templateInfo', 'entityRef'])}, 'Unknown template')`;\n const base = db('tasks as t');\n if (decision.result === AuthorizeResult.CONDITIONAL)\n applyConditions(base, decision.conditions);\n if (query.scope === 'mine') base.whereRaw(`${userRef} = ?`, [callerRef]);\n else if (query.userRef) base.whereRaw(`${userRef} = ?`, [query.userRef]);\n if (query.teamMembers) {\n if (query.teamMembers.length)\n base.whereRaw(\n `${userRef} IN (${query.teamMembers.map(() => '?').join(', ')})`,\n query.teamMembers,\n );\n else base.whereRaw('1 = 0');\n }\n\n // Membership intersects task permissions before any counts or facets.\n const metadata = (source: Knex.QueryBuilder) =>\n source\n .clone()\n .select(\n 't.id',\n 't.status',\n 't.created_at',\n db.raw(`${templateRef} AS template_ref`),\n db.raw(`${templateName} AS template_name`),\n db.raw(`${userRef} AS user_ref`),\n );\n const latestTemplates = db\n .from(metadata(base).as('authorized'))\n .select(\n 'template_ref AS id',\n 'template_name AS name',\n db.raw(\n 'ROW_NUMBER() OVER (PARTITION BY template_ref ORDER BY created_at DESC, id DESC) AS latest_rank',\n ),\n );\n\n // Facets cover authorized retained history, including templates outside the current date range.\n // A transaction has one connection; execute its statements sequentially.\n const counts = await base.clone().count({ total: 't.id' }).first();\n const templateChoices = await db\n .from(latestTemplates.as('template_choices'))\n .select('id', 'name')\n .where('latest_rank', 1)\n .limit(this.maxHistoryRows + 1);\n const userChoices = await base\n .clone()\n .distinct(db.raw(`${userRef} as ref`))\n .limit(this.maxHistoryRows + 1);\n if (\n templateChoices.length > this.maxHistoryRows ||\n userChoices.length > this.maxHistoryRows\n ) {\n throw new InputError(\n 'Too many history filter choices. Select a user or ask your administrator to review templatePulse.maxHistoryRows.',\n );\n }\n const cohort = base.clone();\n if (!query.allTime) {\n cohort\n .where(\n 't.created_at',\n '>=',\n postgres ? query.from : query.from.slice(0, 19).replace('T', ' '),\n )\n .where(\n 't.created_at',\n '<',\n postgres ? query.to : query.to.slice(0, 19).replace('T', ' '),\n );\n }\n if (query.templateRef)\n cohort.whereRaw(`${templateRef} = ?`, [query.templateRef]);\n const executions = executionProjection(db, metadata(cohort), postgres);\n const details = filterExecutionDetails(\n db.from(metadata(cohort).as('cohort')),\n query,\n );\n const offset = query.offset ?? 0;\n // Only elapsed sorting needs completion events for every matching execution.\n const sortableDetails =\n query.sortBy === 'durationMs'\n ? filterExecutionDetails(db.from(executions.clone().as('cohort')), query)\n : details.clone();\n const pageIds = orderExecutionDetails(sortableDetails.select('id'), query)\n .limit(limit)\n .offset(offset);\n // Search, status, COUNT, LIMIT and OFFSET execute in SQL; only one detail page leaves the DB.\n const summaryRow = await metricsQuery(db, executions)\n .select(db.raw('MIN(created_at) AS oldest_at'))\n .first();\n const templateRows = await metricsQuery(db, executions, 'template').limit(\n this.maxHistoryRows + 1,\n );\n const userRows = await metricsQuery(db, executions, 'user').limit(\n this.maxHistoryRows + 1,\n );\n const matchingCount = await details.clone().count({ total: '*' }).first();\n const rawRows = await orderExecutionDetails(\n db\n .from(\n executionProjection(\n db,\n metadata(base.clone().whereIn('t.id', pageIds)),\n postgres,\n ).as('page'),\n )\n .select('*'),\n query,\n );\n const dailyRows = await db\n .from(metadata(cohort).as('cohort'))\n .where(\n 'created_at',\n '>=',\n postgres ? query.from : query.from.slice(0, 19).replace('T', ' '),\n )\n .where(\n 'created_at',\n '<',\n postgres ? query.to : query.to.slice(0, 19).replace('T', ' '),\n )\n .select(\n db.raw(\n `${\n postgres\n ? \"to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD')\"\n : 'substr(created_at, 1, 10)'\n } AS date`,\n ),\n )\n .select(db.raw('COUNT(*) AS total'))\n .select(\n db.raw(\n \"SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed\",\n ),\n )\n .select(\n db.raw(\"SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed\"),\n )\n .groupBy('date');\n if (\n templateRows.length > this.maxHistoryRows ||\n userRows.length > this.maxHistoryRows\n ) {\n throw new InputError(\n 'Too many analytics groups. Narrow the template or user filters, or review templatePulse.maxHistoryRows.',\n );\n }\n const rows: Execution[] = rawRows.map(row => {\n const createdAt = isoDate(row.created_at);\n return {\n id: row.id,\n status: row.status,\n templateRef: row.template_ref,\n templateName: row.template_name,\n userRef: row.user_ref ?? undefined,\n createdAt,\n durationMs:\n row.duration_ms === null || row.duration_ms === undefined\n ? undefined\n : Number(row.duration_ms),\n };\n });\n const rollups = (results: typeof templateRows, kind: 'template' | 'user') =>\n results\n .map(row => {\n const userName =\n row.id === 'unknown' ? 'Unknown user' : (row.id as string);\n return {\n id: row.id as string,\n name: kind === 'template' ? (row.name as string) : userName,\n lastRun: isoDate(row.last_run),\n ...mapMetrics(row),\n };\n })\n .sort((a, b) => b.total - a.total || a.name.localeCompare(b.name));\n const daily = new Map(dailyRows.map(row => [row.date, row]));\n const activity: DailyActivity[] = [];\n for (\n let day = Date.parse(query.from);\n day < Date.parse(query.to);\n day += 86_400_000\n ) {\n const date = new Date(day).toISOString().slice(0, 10);\n const row = daily.get(date);\n const total = Number(row?.total ?? 0);\n const completed = Number(row?.completed ?? 0);\n const failed = Number(row?.failed ?? 0);\n activity.push({\n date,\n total,\n completed,\n failed,\n other: total - completed - failed,\n });\n }\n const summary = mapMetrics(summaryRow);\n const total = Number(matchingCount?.total ?? 0);\n return {\n scope: query.scope,\n items: rows,\n summary,\n templates: rollups(templateRows, 'template'),\n users: rollups(userRows, 'user'),\n activity,\n page: { offset, limit, total, hasMore: offset + limit < total },\n facets: {\n templates: [\n ...new Map(\n templateChoices.map(row => [\n row.id,\n { id: row.id as string, name: row.name as string },\n ]),\n ).values(),\n ].sort((a, b) => a.name.localeCompare(b.name)),\n users: userChoices\n .map(row => row.ref as string)\n .filter(Boolean)\n .sort(),\n },\n window: {\n historySource: 'database' as const,\n limit,\n scanned: summary.total,\n sourceTotal: Number(counts?.total ?? 0),\n truncated: false,\n oldestAt: summaryRow.oldest_at\n ? isoDate(summaryRow.oldest_at)\n : undefined,\n generatedAt: new Date().toISOString(),\n },\n };\n }\n}\n"],"names":["NotAllowedError","InputError","AuthorizeResult","executionProjection","filterExecutionDetails","orderExecutionDetails","metricsQuery","mapMetrics","total"],"mappings":";;;;;;AAwBA,SAAS,eAAA,CACP,OACA,QAAA,EACA;AACA,EAAA,IAAI,WAAW,QAAA,EAAU;AACvB,IAAA,IAAI,CAAC,QAAA,CAAS,KAAA,CAAM,MAAA,EAAQ,KAAA,CAAM,SAAS,OAAO,CAAA;AAClD,IAAA,KAAA,MAAW,aAAa,QAAA,CAAS,KAAA;AAC/B,MAAA,KAAA,CAAM,QAAA,CAAS,CAAA,OAAA,KAAW,eAAA,CAAgB,OAAA,EAAS,SAAS,CAAC,CAAA;AAAA,EACjE,CAAA,MAAA,IAAW,WAAW,QAAA,EAAU;AAC9B,IAAA,IAAI,CAAC,QAAA,CAAS,KAAA,CAAM,MAAA,EAAQ,KAAA,CAAM,SAAS,OAAO,C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,CAAQ,QAAA,EAAU,MAAM,CAAA;AAAA,MAC/B,QAAA;AAAA,MACA,IAAA,EAAM,EAAE,MAAA,EAAQ,KAAA,EAAO,OAAO,OAAA,EAAS,MAAA,GAAS,QAAQ,KAAA,EAAM;AAAA,MAC9D,MAAA,EAAQ;AAAA,QACN,SAAA,EAAW;AAAA,UACT,GAAG,IAAI,GAAA;AAAA,YACL,eAAA,CAAgB,IAAI,CAAA,GAAA,KAAO;AAAA,cACzB,GAAA,CAAI,EAAA;AAAA,cACJ,EAAE,EAAA,EAAI,GAAA,CAAI,EAAA,EAAc,IAAA,EAAM,IAAI,IAAA;AAAe,aAClD;AAAA,YACD,MAAA;AAAO,SACX,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,EAAE,IAAA,CAAK,aAAA,CAAc,CAAA,CAAE,IAAI,CAAC,CAAA;AAAA,QAC7C,KAAA,EAAO,WAAA,CACJ,GAAA,CAAI,CAAA,GAAA,KAAO,GAAA,CAAI,GAAa,CAAA,CAC5B,MAAA,CAAO,OAAO,CAAA,CACd,IAAA;AAAK,OACV;AAAA,MACA,MAAA,EAAQ;AAAA,QACN,aAAA,EAAe,UAAA;AAAA,QACf,KAAA;AAAA,QACA,SAAS,OAAA,CAAQ,KAAA;AAAA,QACjB,WAAA,EAAa,MAAA,CAAO,MAAA,EAAQ,KAAA,IAAS,CAAC,CAAA;AAAA,QACtC,SAAA,EAAW,KAAA;AAAA,QACX,UAAU,UAAA,CAAW,SAAA,GACjB,OAAA,CAAQ,UAAA,CAAW,SAAS,CAAA,GAC5B,MAAA;AAAA,QACJ,WAAA,EAAA,iBAAa,IAAI,IAAA,EAAK,EAAE,WAAA;AAAY;AACtC,KACF;AAAA,EACF;AACF;;"}
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var module$1 = require('./module.cjs.js');
6
+
7
+
8
+
9
+ exports.default = module$1.scaffolderModuleTemplatePulse;
10
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
@@ -0,0 +1,6 @@
1
+ import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
2
+
3
+ /** Retained execution analytics hosted inside the Scaffolder plugin. @public */
4
+ declare const scaffolderModuleTemplatePulse: _backstage_backend_plugin_api.BackendFeature;
5
+
6
+ export { scaffolderModuleTemplatePulse as default };
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ var backendPluginApi = require('@backstage/backend-plugin-api');
4
+ var backstagePluginTemplatePulseNode = require('@abayramli/backstage-plugin-template-pulse-node');
5
+ var historyStore = require('./historyStore.cjs.js');
6
+ var router = require('./router.cjs.js');
7
+
8
+ const scaffolderModuleTemplatePulse = backendPluginApi.createBackendModule({
9
+ pluginId: "scaffolder",
10
+ moduleId: "template-pulse",
11
+ register(env) {
12
+ env.registerInit({
13
+ deps: {
14
+ database: backendPluginApi.coreServices.database,
15
+ httpRouter: backendPluginApi.coreServices.httpRouter,
16
+ httpAuth: backendPluginApi.coreServices.httpAuth,
17
+ permissions: backendPluginApi.coreServices.permissions,
18
+ config: backendPluginApi.coreServices.rootConfig,
19
+ lifecycle: backendPluginApi.coreServices.lifecycle,
20
+ auth: backendPluginApi.coreServices.auth,
21
+ discovery: backendPluginApi.coreServices.discovery
22
+ },
23
+ async init({
24
+ database,
25
+ httpRouter,
26
+ config,
27
+ lifecycle,
28
+ auth,
29
+ discovery,
30
+ ...services
31
+ }) {
32
+ if (config.getOptionalBoolean("permission.enabled") !== true)
33
+ throw new Error(
34
+ "Template Pulse history requires permission.enabled: true and an administrator permission policy."
35
+ );
36
+ const historyStore$1 = new historyStore.DatabaseHistoryStore(
37
+ () => database.getClient(),
38
+ config.getOptionalNumber("templatePulse.maxHistoryRows") ?? 1e4
39
+ );
40
+ if (config.getOptionalString("templatePulse.historySource") === "database") {
41
+ lifecycle.addStartupHook(() => historyStore$1.initialize());
42
+ }
43
+ const teams = new backstagePluginTemplatePulseNode.TeamMembersClient({ auth, discovery });
44
+ httpRouter.use(router.createRouter({ ...services, historyStore: historyStore$1, teams }));
45
+ }
46
+ });
47
+ }
48
+ });
49
+
50
+ exports.scaffolderModuleTemplatePulse = scaffolderModuleTemplatePulse;
51
+ //# sourceMappingURL=module.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.cjs.js","sources":["../src/module.ts"],"sourcesContent":["import {\n coreServices,\n createBackendModule,\n} from '@backstage/backend-plugin-api';\nimport { TeamMembersClient } from '@abayramli/backstage-plugin-template-pulse-node';\nimport { DatabaseHistoryStore } from './historyStore';\nimport { createRouter } from './router';\n\n/** Retained execution analytics hosted inside the Scaffolder plugin. @public */\nexport const scaffolderModuleTemplatePulse = createBackendModule({\n pluginId: 'scaffolder',\n moduleId: 'template-pulse',\n register(env) {\n env.registerInit({\n deps: {\n database: coreServices.database,\n httpRouter: coreServices.httpRouter,\n httpAuth: coreServices.httpAuth,\n permissions: coreServices.permissions,\n config: coreServices.rootConfig,\n lifecycle: coreServices.lifecycle,\n auth: coreServices.auth,\n discovery: coreServices.discovery,\n },\n async init({\n database,\n httpRouter,\n config,\n lifecycle,\n auth,\n discovery,\n ...services\n }) {\n if (config.getOptionalBoolean('permission.enabled') !== true)\n throw new Error(\n 'Template Pulse history requires permission.enabled: true and an administrator permission policy.',\n );\n // Modules receive their target plugin's database. The database service\n // owns the pool and lifecycle; do not create or destroy a second pool.\n const historyStore = new DatabaseHistoryStore(\n () => database.getClient(),\n config.getOptionalNumber('templatePulse.maxHistoryRows') ?? 10_000,\n );\n if (\n config.getOptionalString('templatePulse.historySource') === 'database'\n ) {\n // Module init runs before the plugin. Validate only after Scaffolder\n // has initialized and migrated its database, never before its tables exist.\n lifecycle.addStartupHook(() => historyStore.initialize());\n }\n const teams = new TeamMembersClient({ auth, discovery });\n httpRouter.use(createRouter({ ...services, historyStore, teams }));\n },\n });\n },\n});\n"],"names":["createBackendModule","coreServices","historyStore","DatabaseHistoryStore","TeamMembersClient","createRouter"],"mappings":";;;;;;;AASO,MAAM,gCAAgCA,oCAAA,CAAoB;AAAA,EAC/D,QAAA,EAAU,YAAA;AAAA,EACV,QAAA,EAAU,gBAAA;AAAA,EACV,SAAS,GAAA,EAAK;AACZ,IAAA,GAAA,CAAI,YAAA,CAAa;AAAA,MACf,IAAA,EAAM;AAAA,QACJ,UAAUC,6BAAA,CAAa,QAAA;AAAA,QACvB,YAAYA,6BAAA,CAAa,UAAA;AAAA,QACzB,UAAUA,6BAAA,CAAa,QAAA;AAAA,QACvB,aAAaA,6BAAA,CAAa,WAAA;AAAA,QAC1B,QAAQA,6BAAA,CAAa,UAAA;AAAA,QACrB,WAAWA,6BAAA,CAAa,SAAA;AAAA,QACxB,MAAMA,6BAAA,CAAa,IAAA;AAAA,QACnB,WAAWA,6BAAA,CAAa;AAAA,OAC1B;AAAA,MACA,MAAM,IAAA,CAAK;AAAA,QACT,QAAA;AAAA,QACA,UAAA;AAAA,QACA,MAAA;AAAA,QACA,SAAA;AAAA,QACA,IAAA;AAAA,QACA,SAAA;AAAA,QACA,GAAG;AAAA,OACL,EAAG;AACD,QAAA,IAAI,MAAA,CAAO,kBAAA,CAAmB,oBAAoB,CAAA,KAAM,IAAA;AACtD,UAAA,MAAM,IAAI,KAAA;AAAA,YACR;AAAA,WACF;AAGF,QAAA,MAAMC,iBAAe,IAAIC,iCAAA;AAAA,UACvB,MAAM,SAAS,SAAA,EAAU;AAAA,UACzB,MAAA,CAAO,iBAAA,CAAkB,8BAA8B,CAAA,IAAK;AAAA,SAC9D;AACA,QAAA,IACE,MAAA,CAAO,iBAAA,CAAkB,6BAA6B,CAAA,KAAM,UAAA,EAC5D;AAGA,UAAA,SAAA,CAAU,cAAA,CAAe,MAAMD,cAAA,CAAa,UAAA,EAAY,CAAA;AAAA,QAC1D;AACA,QAAA,MAAM,QAAQ,IAAIE,kDAAA,CAAkB,EAAE,IAAA,EAAM,WAAW,CAAA;AACvD,QAAA,UAAA,CAAW,GAAA,CAAIC,oBAAa,EAAE,GAAG,wBAAUH,cAAA,EAAc,KAAA,EAAO,CAAC,CAAA;AAAA,MACnE;AAAA,KACD,CAAA;AAAA,EACH;AACF,CAAC;;"}
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ var errors = require('@backstage/errors');
4
+ var alpha = require('@backstage/plugin-scaffolder-common/alpha');
5
+ var pluginPermissionCommon = require('@backstage/plugin-permission-common');
6
+ var backstagePluginTemplatePulseNode = require('@abayramli/backstage-plugin-template-pulse-node');
7
+ var Router = require('express-promise-router');
8
+
9
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
10
+
11
+ var Router__default = /*#__PURE__*/_interopDefaultCompat(Router);
12
+
13
+ function createRouter(options) {
14
+ const { httpAuth, permissions, historyStore } = options;
15
+ const router = Router__default.default();
16
+ router.get("/modules/template-pulse/analytics", async (req, res) => {
17
+ const query = backstagePluginTemplatePulseNode.parseExecutionQuery(req.query);
18
+ const limit = req.query.limit ?? "200";
19
+ if (typeof limit !== "string" || !/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 1e3)
20
+ throw new errors.InputError("limit must be an integer between 1 and 1000");
21
+ const credentials = await httpAuth.credentials(req, { allow: ["user"] });
22
+ await backstagePluginTemplatePulseNode.authorizeExecutionQuery({ query, credentials, permissions });
23
+ const [decision] = await permissions.authorizeConditional(
24
+ [{ permission: alpha.taskReadPermission }],
25
+ { credentials }
26
+ );
27
+ if (!decision || decision.result === pluginPermissionCommon.AuthorizeResult.DENY)
28
+ throw new errors.NotAllowedError("Scaffolder task access denied");
29
+ const teamMembers = query.teamRef ? await options.teams.getMembers(query.teamRef, credentials) : void 0;
30
+ const analytics = await historyStore.search(
31
+ teamMembers ? { ...query, teamMembers } : query,
32
+ credentials.principal.userEntityRef,
33
+ decision,
34
+ Number(limit)
35
+ );
36
+ res.setHeader("Cache-Control", "no-store");
37
+ res.json(analytics);
38
+ });
39
+ return router;
40
+ }
41
+
42
+ exports.createRouter = createRouter;
43
+ //# sourceMappingURL=router.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.cjs.js","sources":["../src/router.ts"],"sourcesContent":["import type {\r\n HttpAuthService,\r\n PermissionsService,\r\n} from '@backstage/backend-plugin-api';\r\nimport { InputError, NotAllowedError } from '@backstage/errors';\r\nimport { taskReadPermission } from '@backstage/plugin-scaffolder-common/alpha';\r\nimport { AuthorizeResult } from '@backstage/plugin-permission-common';\r\nimport {\r\n authorizeExecutionQuery,\r\n parseExecutionQuery,\r\n type TeamMembersClient,\r\n} from '@abayramli/backstage-plugin-template-pulse-node';\r\nimport Router from 'express-promise-router';\r\nimport type { DatabaseHistoryStore } from './historyStore';\r\n\r\nexport function createRouter(options: {\r\n httpAuth: HttpAuthService;\r\n permissions: PermissionsService;\r\n historyStore: DatabaseHistoryStore;\r\n teams: Pick<TeamMembersClient, 'getMembers'>;\r\n}) {\r\n const { httpAuth, permissions, historyStore } = options;\r\n const router = Router();\r\n router.get('/modules/template-pulse/analytics', async (req, res) => {\r\n const query = parseExecutionQuery(req.query);\r\n const limit = req.query.limit ?? '200';\r\n if (\r\n typeof limit !== 'string' ||\r\n !/^\\d+$/.test(limit) ||\r\n Number(limit) < 1 ||\r\n Number(limit) > 1000\r\n )\r\n throw new InputError('limit must be an integer between 1 and 1000');\r\n const credentials = await httpAuth.credentials(req, { allow: ['user'] });\r\n // This endpoint also enforces analytics permissions when called directly.\r\n await authorizeExecutionQuery({ query, credentials, permissions });\r\n const [decision] = await permissions.authorizeConditional(\r\n [{ permission: taskReadPermission }],\r\n { credentials },\r\n );\r\n if (!decision || decision.result === AuthorizeResult.DENY)\r\n throw new NotAllowedError('Scaffolder task access denied');\r\n const teamMembers = query.teamRef\r\n ? await options.teams.getMembers(query.teamRef, credentials)\r\n : undefined;\r\n const analytics = await historyStore.search(\r\n teamMembers ? { ...query, teamMembers } : query,\r\n credentials.principal.userEntityRef,\r\n decision,\r\n Number(limit),\r\n );\r\n res.setHeader('Cache-Control', 'no-store');\r\n res.json(analytics);\r\n });\r\n return router;\r\n}\r\n"],"names":["Router","parseExecutionQuery","InputError","authorizeExecutionQuery","taskReadPermission","AuthorizeResult","NotAllowedError"],"mappings":";;;;;;;;;;;;AAeO,SAAS,aAAa,OAAA,EAK1B;AACD,EAAA,MAAM,EAAE,QAAA,EAAU,WAAA,EAAa,YAAA,EAAa,GAAI,OAAA;AAChD,EAAA,MAAM,SAASA,uBAAA,EAAO;AACtB,EAAA,MAAA,CAAO,GAAA,CAAI,mCAAA,EAAqC,OAAO,GAAA,EAAK,GAAA,KAAQ;AAClE,IAAA,MAAM,KAAA,GAAQC,oDAAA,CAAoB,GAAA,CAAI,KAAK,CAAA;AAC3C,IAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,KAAA,CAAM,KAAA,IAAS,KAAA;AACjC,IAAA,IACE,OAAO,KAAA,KAAU,QAAA,IACjB,CAAC,QAAQ,IAAA,CAAK,KAAK,CAAA,IACnB,MAAA,CAAO,KAAK,CAAA,GAAI,CAAA,IAChB,MAAA,CAAO,KAAK,CAAA,GAAI,GAAA;AAEhB,MAAA,MAAM,IAAIC,kBAAW,6CAA6C,CAAA;AACpE,IAAA,MAAM,WAAA,GAAc,MAAM,QAAA,CAAS,WAAA,CAAY,GAAA,EAAK,EAAE,KAAA,EAAO,CAAC,MAAM,CAAA,EAAG,CAAA;AAEvE,IAAA,MAAMC,wDAAA,CAAwB,EAAE,KAAA,EAAO,WAAA,EAAa,aAAa,CAAA;AACjE,IAAA,MAAM,CAAC,QAAQ,CAAA,GAAI,MAAM,WAAA,CAAY,oBAAA;AAAA,MACnC,CAAC,EAAE,UAAA,EAAYC,wBAAA,EAAoB,CAAA;AAAA,MACnC,EAAE,WAAA;AAAY,KAChB;AACA,IAAA,IAAI,CAAC,QAAA,IAAY,QAAA,CAAS,MAAA,KAAWC,sCAAA,CAAgB,IAAA;AACnD,MAAA,MAAM,IAAIC,uBAAgB,+BAA+B,CAAA;AAC3D,IAAA,MAAM,WAAA,GAAc,KAAA,CAAM,OAAA,GACtB,MAAM,OAAA,CAAQ,MAAM,UAAA,CAAW,KAAA,CAAM,OAAA,EAAS,WAAW,CAAA,GACzD,MAAA;AACJ,IAAA,MAAM,SAAA,GAAY,MAAM,YAAA,CAAa,MAAA;AAAA,MACnC,WAAA,GAAc,EAAE,GAAG,KAAA,EAAO,aAAY,GAAI,KAAA;AAAA,MAC1C,YAAY,SAAA,CAAU,aAAA;AAAA,MACtB,QAAA;AAAA,MACA,OAAO,KAAK;AAAA,KACd;AACA,IAAA,GAAA,CAAI,SAAA,CAAU,iBAAiB,UAAU,CAAA;AACzC,IAAA,GAAA,CAAI,KAAK,SAAS,CAAA;AAAA,EACpB,CAAC,CAAA;AACD,EAAA,OAAO,MAAA;AACT;;"}
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@abayramli/backstage-plugin-scaffolder-backend-module-template-pulse",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Read Scaffolder run history from its database, with access controlled by Backstage permissions.",
5
+ "license": "Apache-2.0",
6
+ "backstage": {
7
+ "role": "backend-plugin-module",
8
+ "pluginId": "scaffolder",
9
+ "pluginPackage": "@backstage/plugin-scaffolder-backend",
10
+ "features": {
11
+ ".": "@backstage/BackendFeature"
12
+ }
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "main": "./dist/index.cjs.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "backstage": "@backstage/BackendFeature",
22
+ "require": "./dist/index.cjs.js",
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.cjs.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "typesVersions": {
29
+ "*": {
30
+ "package.json": [
31
+ "package.json"
32
+ ]
33
+ }
34
+ },
35
+ "files": [
36
+ "dist"
37
+ ],
38
+ "scripts": {
39
+ "lint": "backstage-cli package lint",
40
+ "test": "backstage-cli package test",
41
+ "build": "backstage-cli package build",
42
+ "clean": "backstage-cli package clean",
43
+ "prepack": "backstage-cli package prepack",
44
+ "postpack": "backstage-cli package postpack"
45
+ },
46
+ "dependencies": {
47
+ "@abayramli/backstage-plugin-template-pulse-common": "^0.1.0",
48
+ "@abayramli/backstage-plugin-template-pulse-node": "^0.1.0",
49
+ "@backstage/backend-plugin-api": "^1.10.1",
50
+ "@backstage/errors": "^1.3.1",
51
+ "@backstage/plugin-permission-common": "^0.9.11",
52
+ "@backstage/plugin-scaffolder-common": "^2.3.0",
53
+ "express": "^4.22.0",
54
+ "express-promise-router": "^4.1.1",
55
+ "knex": "^3.3.0"
56
+ },
57
+ "devDependencies": {
58
+ "@backstage/cli": "^0.36.6",
59
+ "@types/express": "^4.17.21",
60
+ "@types/jest": "^30.0.0",
61
+ "better-sqlite3": "^12.0.0",
62
+ "jest": "~30.2.0",
63
+ "pg": "^8.16.0"
64
+ },
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "https://github.com/alibayramli/template-pulse.git",
68
+ "directory": "plugins/scaffolder-backend-module-template-pulse"
69
+ },
70
+ "homepage": "https://github.com/alibayramli/template-pulse#readme",
71
+ "bugs": "https://github.com/alibayramli/template-pulse/issues",
72
+ "keywords": [
73
+ "backstage",
74
+ "backstage-plugin",
75
+ "scaffolder",
76
+ "template-pulse",
77
+ "analytics"
78
+ ],
79
+ "engines": {
80
+ "node": "22 || 24"
81
+ }
6
82
  }