Release checklist¶
| Aspect | Details |
|---|---|
| Folder | examples/release-checklist |
| Identifier | com.example.releasechecklist |
| View | sidebar checklist |
| Endpoints | POST validate, POST assign-to-me |
| Placement | none; choose Release checklist in the Show Sidebar menu |
| Uses | fetchContext(), selection-changed events, your own endpoints with a JSON array in the body, the tracker and security services on the server |
Download com.example.releasechecklist · version 0.2.2
This is the most complete example in the guide: a view that follows the user, and server-side capability that the REST API does not offer in one call. It shows the typical shape of a rich application: the sidebar is the experience, the endpoints are the capability.
What it does¶
- The sidebar fetches the context and subscribes to selection changes, debounced by 200 ms.
- For the selected ids it calls the application's own
validateendpoint with{ "objectId": "test/TEST-514", "objectIds": "[\"test/TEST-514\", …]" }:objectIdis mandatory on every call, and the list is JSON-encoded into a string because Polarion accepts only string values in a POST body. validate.jsruns on the server: it loads each work item, applies five rules (empty description, no assignee, no links, no priority, open for more than 90 days) and returns findings per item plus a summary. Fifty selected items are still one request. The endpoints accept at most 100 ids per call, so the view sends larger selections in chunks of 100 and merges the reports.- The sidebar renders a summary strip with a chip per finding code and one card per item.
- Assign unassigned to me calls the
assign-to-meendpoint with the ids that have theunassignedfinding.assign-to-me.jsadds the calling user as assignee and saves; the sidebar then re-validates.
Files¶
- release-checklist/
- manifest.json
- server-scripts/
- validate.js POST validate
- assign-to-me.js POST assign-to-me
- public/
- icon16.png
- icon32.png
- src/
- App.tsx
- polarion.ts endpointFetch helper
- types.ts the endpoint contracts
- main.tsx
- styles.css
- …
manifest.json¶
A sidebar view and two POST endpoints:
{
"manifestVersion": "1.0",
"identifier": "com.example.releasechecklist",
"title": "Release checklist",
"description": "A sidebar that checks the selected work items against release rules computed by the application's own server-side endpoints, and can assign items to the current user.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.2",
"views": {
"sidebars": [
{
"identifier": "checklist",
"title": "Release checklist",
"rootDirectory": "checklist",
"document": "index.html",
"menuIcon": "icon16.png",
"icon": "icon32.png"
}
]
},
"serverScripts": {
"endpoints": [
{
"urlPath": "validate",
"method": "POST",
"script": "validate.js"
},
{
"urlPath": "assign-to-me",
"method": "POST",
"script": "assign-to-me.js"
}
]
}
}
The contract¶
The request and response shapes are declared once, in TypeScript, and used by the view. Together with the README they are the documentation of the endpoints.
/** Shapes returned by the application's own endpoints (server-scripts/). */
export type FindingCode = "no-description" | "unassigned" | "no-links" | "missing-priority" | "open-too-long" | "not-found";
export interface Finding {
code: FindingCode;
message: string;
}
export interface ItemResult {
/** "PROJECT/WI-ID" */
id: string;
title: string;
status: string | null;
findings: Finding[];
}
/** POST validate */
export interface ValidateResult {
results: ItemResult[];
summary: {
items: number;
withFindings: number;
byCode: Partial<Record<FindingCode, number>>;
};
}
/** POST assign-to-me */
export interface AssignResult {
updated: string[];
failed: { id: string; error: string }[];
}
export const FINDING_LABELS: Record<FindingCode, string> = {
"no-description": "No description",
"unassigned": "Unassigned",
"no-links": "No links",
"missing-priority": "No priority",
"open-too-long": "Open > 90 days",
"not-found": "Not readable",
};
server-scripts/validate.js¶
// POST /polarion/apps/com.example.releasechecklist/rest/validate
// Body: { "objectId": "PROJECT/WI-ID", "objectIds": "[\"PROJECT/WI-ID\", …]" }
// objectId is mandatory on every endpoint call; the list travels as a JSON string
// because POST bodies accept string values only.
//
// Checks each work item against a few release rules on the server and returns
// the findings in one response. Runs as the logged-in user; items the user may
// not read come back with a `not-found` finding.
//
// Response (inside Polarion's { timestamp, success, data } envelope):
// { results: [ { id, title, status, findings: [ { code, message } ] } ],
// summary: { items, withFindings, byCode: { code: count } } }
const trackerService = context.scriptContext().services().tracker();
let result = {};
// Polarion's IArguments is the script-level `arguments`; inside a function the
// name refers to the function's own arguments, so capture it once at the top.
const scriptArguments = arguments;
const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000;
const RESOLVED_STATUSES = ['resolved', 'done', 'closed', 'verified', 'rejected'];
const MAX_OBJECT_IDS = 100;
const OBJECT_ID = /^[^/\s]+\/[^/\s]+$/;
/**
* Reads `objectIds`: a JSON array of "PROJECT/WI-ID" strings, sent as a string because POST bodies
* accept string values only. Returns [{ id, projectId, workItemId }]; throws on any other input.
*/
function readObjectIds() {
// getAsString throws "Argument objectIds is missing" when the view did not send it.
const raw = scriptArguments.getAsString('objectIds');
let list;
try {
list = JSON.parse(raw);
} catch (e) {
throw new Error('objectIds must be a JSON array of "PROJECT/WI-ID" strings');
}
if (!Array.isArray(list) || list.length === 0) {
throw new Error('objectIds must be a non-empty JSON array of "PROJECT/WI-ID" strings');
}
if (list.length > MAX_OBJECT_IDS) {
throw new Error('objectIds: at most ' + MAX_OBJECT_IDS + ' items per call');
}
return list.map(function (id) {
if (typeof id !== 'string' || !OBJECT_ID.test(id)) {
throw new Error('objectIds: expected "PROJECT/WI-ID", got ' + JSON.stringify(id));
}
const parts = id.split('/');
return { id: id, projectId: parts[0], workItemId: parts[1] };
});
}
function isEmptyText(text) {
if (text === null || text === undefined) return true;
const content = text.getContent ? text.getContent() : String(text);
return content === null || String(content).replace(/<[^>]*>/g, '').trim() === '';
}
function checkItem(wi) {
const findings = [];
const statusId = wi.getStatus() ? String(wi.getStatus().getId()).toLowerCase() : '';
if (isEmptyText(wi.getDescription())) {
findings.push({ code: 'no-description', message: 'The description is empty.' });
}
if (wi.getAssignees().isEmpty()) {
findings.push({ code: 'unassigned', message: 'Nobody is assigned.' });
}
const direct = wi.getLinkedWorkItemsStructsDirect().toArray();
const back = wi.getLinkedWorkItemsStructsBack().toArray();
if (direct.length === 0 && back.length === 0) {
findings.push({ code: 'no-links', message: 'The item has no links in either direction.' });
}
if (wi.getPriority() === null || wi.getPriority() === undefined) {
findings.push({ code: 'missing-priority', message: 'No priority is set.' });
}
const created = wi.getCreated();
if (created && RESOLVED_STATUSES.indexOf(statusId) === -1) {
const createdDate = new Date(created.getTime());
if (Date.now() - createdDate.getTime() > NINETY_DAYS_MS) {
findings.push({ code: 'open-too-long', message: 'Open for more than 90 days.' });
}
}
return findings;
}
try {
const ids = readObjectIds();
const results = [];
const byCode = {};
let withFindings = 0;
for (let i = 0; i < ids.length; i++) {
const entry = { id: ids[i].id, title: '', status: null, findings: [] };
try {
const wi = trackerService.getWorkItem(ids[i].projectId, ids[i].workItemId);
if (wi.isUnresolvable()) {
throw new Error('not found');
}
entry.title = wi.getTitle();
entry.status = wi.getStatus() ? wi.getStatus().getName() : null;
entry.findings = checkItem(wi);
} catch (e) {
entry.findings = [{ code: 'not-found', message: 'Could not read the work item: ' + e }];
}
if (entry.findings.length > 0) withFindings++;
for (let f = 0; f < entry.findings.length; f++) {
const code = entry.findings[f].code;
byCode[code] = (byCode[code] || 0) + 1;
}
results.push(entry);
}
result = {
results: results,
summary: { items: results.length, withFindings: withFindings, byCode: byCode },
};
} catch (e) {
// An `error` key turns the response into an error response for the caller.
result = { error: 'validate failed: ' + e };
}
result;
Points worth noting:
- Reading a list from the body. The view sends the list as a JSON string;
readObjectIds()reads it withscriptArguments.getAsString('objectIds')and accepts exactly one format: a JSON array of"PROJECT/WI-ID"strings, at most 100. Anything else (no array, an empty list, an id without the project) fails the whole call with a message that names the expected format, andreadObjectIds()returns the ids already split intoprojectIdandworkItemId, so the loop does not parse them again.scriptArgumentsis Polarion'sargumentscaptured at the top level, because inside a functionargumentsmeans something else. - Rules are small functions over
IWorkItem. Adding a rule means oneifblock and one finding code; the view only needs a label for the new code. - Per-item error handling. An item the user may not read, or an id that does not exist, becomes a
not-foundfinding instead of failing the whole request. - Summary computed on the server. The view renders
summary.byCodedirectly.
server-scripts/assign-to-me.js¶
// POST /polarion/apps/com.example.releasechecklist/rest/assign-to-me
// Body: { "objectId": "PROJECT/WI-ID", "objectIds": "[\"PROJECT/WI-ID\", …]" }
// objectId is mandatory on every endpoint call; the list travels as a JSON string
// because POST bodies accept string values only.
//
// Adds the calling user as assignee of every listed work item and saves.
// Runs as the logged-in user, who needs permission to modify the items.
//
// API calls to check against the javadoc of your Polarion version:
// ISecurityService.getCurrentUser() -> user id of the caller
// ITrackerService.getProjectsService() -> IProjectService
// IProjectService.getUser(String) -> IUser
// IWorkItem.getAssignees(), addAssignee(IUser), save()
//
// Response: { updated: [ids], failed: [ { id, error } ] }
const services = context.scriptContext().services();
const trackerService = services.tracker();
const securityService = services.security();
let result = {};
// Polarion's IArguments is the script-level `arguments`; inside a function the
// name refers to the function's own arguments, so capture it once at the top.
const scriptArguments = arguments;
const MAX_OBJECT_IDS = 100;
const OBJECT_ID = /^[^/\s]+\/[^/\s]+$/;
/**
* Reads `objectIds`: a JSON array of "PROJECT/WI-ID" strings, sent as a string because POST bodies
* accept string values only. Returns [{ id, projectId, workItemId }]; throws on any other input.
*/
function readObjectIds() {
// getAsString throws "Argument objectIds is missing" when the view did not send it.
const raw = scriptArguments.getAsString('objectIds');
let list;
try {
list = JSON.parse(raw);
} catch (e) {
throw new Error('objectIds must be a JSON array of "PROJECT/WI-ID" strings');
}
if (!Array.isArray(list) || list.length === 0) {
throw new Error('objectIds must be a non-empty JSON array of "PROJECT/WI-ID" strings');
}
if (list.length > MAX_OBJECT_IDS) {
throw new Error('objectIds: at most ' + MAX_OBJECT_IDS + ' items per call');
}
return list.map(function (id) {
if (typeof id !== 'string' || !OBJECT_ID.test(id)) {
throw new Error('objectIds: expected "PROJECT/WI-ID", got ' + JSON.stringify(id));
}
const parts = id.split('/');
return { id: id, projectId: parts[0], workItemId: parts[1] };
});
}
try {
const ids = readObjectIds();
const userId = securityService.getCurrentUser();
const user = trackerService.getProjectsService().getUser(userId);
if (!user || user.isUnresolvable()) {
throw new Error('Current user not found: ' + userId);
}
const updated = [];
const failed = [];
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
try {
const wi = trackerService.getWorkItem(id.projectId, id.workItemId);
if (wi.isUnresolvable()) throw new Error('not found');
let already = false;
const assignees = wi.getAssignees().toArray();
for (let a = 0; a < assignees.length; a++) {
if (String(assignees[a].getId()) === String(userId)) already = true;
}
if (!already) {
wi.addAssignee(user);
wi.save();
}
updated.push(id.id);
} catch (e) {
failed.push({ id: id.id, error: String(e) });
}
}
result = { updated: updated, failed: failed };
} catch (e) {
result = { error: 'assign-to-me failed: ' + e };
}
result;
The write endpoint resolves the calling user through the security service, loops over the items, saves each, and reports updated and failed lists rather than aborting on the first error.
Note
The comment at the top of the script lists the Java API calls it relies on. All of them were exercised against a Polarion 2612 server; verify them against the javadoc when your version differs.
src/App.tsx¶
import { useCallback, useEffect, useRef, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { endpointFetch } from "./polarion";
import { FINDING_LABELS, type AssignResult, type FindingCode, type ItemResult, type ValidateResult } from "./types";
/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the endpoints expect "PROJECT/WI-1". */
function fullId(projectId: string, id: string): string {
return id.includes("/") ? id : `${projectId}/${id}`;
}
// The endpoints accept at most 100 ids per call (MAX_OBJECT_IDS in the server scripts),
// while the table can select more. Larger selections are sent in chunks of 100.
const MAX_IDS_PER_CALL = 100;
function chunk<T>(list: T[]): T[][] {
const parts: T[][] = [];
for (let i = 0; i < list.length; i += MAX_IDS_PER_CALL) parts.push(list.slice(i, i + MAX_IDS_PER_CALL));
return parts;
}
/** Joins the reports of several validate calls into one. */
function mergeReports(parts: ValidateResult[]): ValidateResult {
const byCode: ValidateResult["summary"]["byCode"] = {};
for (const part of parts) {
for (const [code, n] of Object.entries(part.summary.byCode) as [FindingCode, number][]) {
byCode[code] = (byCode[code] ?? 0) + n;
}
}
return {
results: parts.flatMap((p) => p.results),
summary: {
items: parts.reduce((sum, p) => sum + p.summary.items, 0),
withFindings: parts.reduce((sum, p) => sum + p.summary.withFindings, 0),
byCode,
},
};
}
function itemUrl(id: string): string {
const [project, wi] = id.split("/");
return `${window.location.origin}/polarion/#/project/${project}/workitem?id=${wi}`;
}
function ItemCard({ item }: { item: ItemResult }) {
const wiId = item.id.split("/")[1] ?? item.id;
return (
<div className={`box item${item.findings.length === 0 ? " clean" : ""}`}>
<div className="item-head">
<a href={itemUrl(item.id)} target="_top">
{wiId}
</a>
{item.status && <span className="chip status">{item.status}</span>}
</div>
<div className="item-title">{item.title || <span className="muted">(no title)</span>}</div>
{item.findings.length === 0 ? (
<div className="finding ok">✓ Ready for release</div>
) : (
<ul className="findings">
{item.findings.map((f) => (
<li key={f.code} className={`finding code-${f.code}`}>
<span className="chip warn">{FINDING_LABELS[f.code] ?? f.code}</span> {f.message}
</li>
))}
</ul>
)}
</div>
);
}
export default function App() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [report, setReport] = useState<ValidateResult | null>(null);
const [busy, setBusy] = useState<"idle" | "checking" | "assigning">("idle");
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
// 1. Context (initial selection) and 2. selection events.
useEffect(() => {
let cancelled = false;
fetchContext()
.then((ctx) => {
if (cancelled) {
return;
}
setContext(ctx);
setSelectedIds(ctx.selectedWorkItemIds ?? []);
})
.catch((error: unknown) => {
if (cancelled) {
return;
}
console.error("Unable to fetch the Polarion context:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the Polarion context: ${message}`);
});
const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
setSelectedIds(data.selectedWorkItemIds ?? []);
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
// Remove the subscription and release the message listener.
unsubscribe();
destroy();
};
}, []);
// 3. Ask our own endpoint to validate the selected items.
const validate = useCallback(async (ctx: PolarionContext, ids: string[], isCurrent: () => boolean = () => true) => {
if (!ctx.projectId || ids.length === 0) {
setReport(null);
return;
}
setBusy("checking");
setError(null);
try {
const objectIds = ids.map((id) => fullId(ctx.projectId!, id));
// `objectId` is required by Polarion on every endpoint call; the list travels
// in `objectIds` as a JSON string (POST bodies accept string values only).
const parts = await Promise.all(
chunk(objectIds).map((part) =>
endpointFetch<ValidateResult>(ctx, "/validate", {
method: "POST",
body: JSON.stringify({ objectId: part[0], objectIds: JSON.stringify(part) }),
}),
),
);
if (isCurrent()) setReport(mergeReports(parts));
} catch (error) {
if (!isCurrent()) return;
console.error("Unable to validate the selection:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to validate the selection: ${message}`);
} finally {
if (isCurrent()) setBusy("idle");
}
}, []);
// Debounce: wait until the selection has been stable for 200 ms. A request
// that is still running when the selection changes again is ignored on return.
// The old report is dropped at once, so its "Assign" button cannot act on the
// previous selection while the new one is being validated.
const requestRef = useRef(0);
const recheck = useCallback(
(ctx: PolarionContext, ids: string[]) => {
const request = ++requestRef.current;
return validate(ctx, ids, () => request === requestRef.current);
},
[validate],
);
// Counts selection changes, so work started for one selection can tell that it is outdated.
const selectionRef = useRef(0);
useEffect(() => {
if (!context) return;
++selectionRef.current;
++requestRef.current;
setReport(null);
setNotice(null);
const timer = setTimeout(() => void recheck(context, selectedIds), 200);
return () => clearTimeout(timer);
}, [context, selectedIds, recheck]);
async function assignToMe() {
if (!context || !report) return;
const ids = report.results.filter((r) => r.findings.some((f) => f.code === "unassigned")).map((r) => r.id);
if (ids.length === 0) return;
const selection = selectionRef.current;
setBusy("assigning");
setNotice(null);
setError(null);
try {
const parts = await Promise.all(
chunk(ids).map((part) =>
endpointFetch<AssignResult>(context, "/assign-to-me", {
method: "POST",
body: JSON.stringify({ objectId: part[0], objectIds: JSON.stringify(part) }),
}),
),
);
const updated = parts.flatMap((p) => p.updated);
const failed = parts.flatMap((p) => p.failed);
setNotice(`${updated.length} item(s) assigned to you` + (failed.length ? `, ${failed.length} failed: ${failed[0].error}` : "."));
// Re-validate only if the selection is still the one that was assigned; otherwise the
// new selection's own validation owns the report.
if (selection === selectionRef.current) await recheck(context, selectedIds);
} catch (error) {
console.error("Unable to assign the work items:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to assign the work items: ${message}`);
} finally {
setBusy("idle");
}
}
if (!context && !error) {
return <p className="muted">Waiting for the Polarion context…</p>;
}
const unassignedCount = report?.summary.byCode.unassigned ?? 0;
const codes = report ? (Object.keys(report.summary.byCode) as FindingCode[]) : [];
return (
<div>
<p className="headline">Release checklist</p>
{error && <div className="box error">{error}</div>}
{selectedIds.length === 0 ? (
<div className="box hint">Select one or more work items in the table to check them.</div>
) : (
<>
<div className="box summary">
<div className="summary-line">{busy === "checking" ? "Checking…" : report ? `${report.summary.items} checked, ${report.summary.withFindings} with findings` : `${selectedIds.length} selected`}</div>
{codes.length > 0 && (
<div className="chips">
{codes.map((code) => (
<span key={code} className="chip warn">
{FINDING_LABELS[code] ?? code}: {report!.summary.byCode[code]}
</span>
))}
</div>
)}
<div className="actions">
<button onClick={() => context && recheck(context, selectedIds)} disabled={busy !== "idle"}>
Re-check
</button>
<button onClick={assignToMe} disabled={busy !== "idle" || unassignedCount === 0}>
{busy === "assigning" ? "Assigning…" : `Assign unassigned to me (${unassignedCount})`}
</button>
</div>
{notice && <div className="muted small">{notice}</div>}
</div>
{report?.results.map((item) => (
<ItemCard key={item.id} item={item} />
))}
</>
)}
</div>
);
}
Points worth noting:
- Same event pattern as the selection sidebar, plus a debounce effect so that keyboard navigation through the table does not fire a request per row.
- The endpoint shapes the UI. No JSON:API assembly in the view;
report.resultsandreport.summaryare rendered as they arrive. - A report belongs to one selection. When the selection changes, the old report is dropped at once and any validation still running is ignored on return, so Assign unassigned to me never acts on items that are no longer selected.
- Writes go through an endpoint too. One request per 100 items assigns all unassigned items and returns a result the view can explain.
Build and deploy¶
cd examples/release-checklist
npm install
npm run package # → com.example.releasechecklist.zip (with server-scripts/)
Upload the ZIP. Open a project's Work Items table, click Show Sidebar and choose Release checklist. Select a few items; the findings appear after a moment.
Things to try¶
- Add a rule
no-testsfor requirements without averifiesback link, and a label for it inFINDING_LABELS. - Replace the fixed 90-day threshold with a
maxAgeDaysparameter sent by the view. - Add a Set priority to Medium action with a third endpoint, and compare with doing the same through the REST API (
PATCH attributes.priority) from the view.
