⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(importers): add shared source importers
Andrejd003d903d2c4
diff --git a/apps/api/package.json b/apps/api/package.jsonindex 0dbfa22b2..ac00e06b8 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -55,7 +55,8 @@"pg": "^8.23.1","valibot": "^1.5.0","zod": "^4.6.5",- "@kaneo/mcp": "workspace:*"+ "@kaneo/mcp": "workspace:*",+ "@kaneo/importers": "workspace:*"},"devDependencies": {"@types/node": "^26.6.2",diff --git a/packages/importers/LICENSE b/packages/importers/LICENSEnew file mode 100644index 000000000..85db1d012--- /dev/null+++ b/packages/importers/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Kaneo MCP contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/importers/package.json b/packages/importers/package.jsonnew file mode 100644index 000000000..f265dc3f5--- /dev/null+++ b/packages/importers/package.json@@ -0,0 +1,37 @@+{+ "name": "@kaneo/importers",+ "version": "0.0.0",+ "private": true,+ "description": "Read projects from PLANKA, Plane, Linear, Trello and other Kaneo instances into one import model",+ "type": "module",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "./planka": {+ "types": "./dist/planka/index.d.ts",+ "default": "./dist/planka/index.js"+ }+ },+ "license": "MIT",+ "scripts": {+ "build": "vp run compile",+ "lint": "vp check .",+ "test": "vp run test:run",+ "test:watch": "vp test --config vitest.config.ts"+ },+ "dependencies": {+ "turndown": "^7.2.4",+ "turndown-plugin-gfm": "^1.0.2"+ },+ "devDependencies": {+ "@kaneo/typescript-config": "workspace:*",+ "@types/node": "^26.6.2",+ "typescript": "^7.0.2",+ "vite-plus": "catalog:",+ "@types/turndown": "^5.0.5"+ }+}diff --git a/packages/importers/src/http.ts b/packages/importers/src/http.tsnew file mode 100644index 000000000..f2bab3a84--- /dev/null+++ b/packages/importers/src/http.ts@@ -0,0 +1,186 @@+import type { FetchLike } from "./types.js";++export class SourceHttpError extends Error {+ constructor(+ message: string,+ readonly status: number,+ readonly body: unknown,+ ) {+ super(message);+ this.name = "SourceHttpError";+ }+}++export type JsonClientOptions = {+ service: string;+ baseUrl: string;+ headers: () => Record<string, string>;+ fetch?: FetchLike;+ signal?: AbortSignal;+ timeoutMs?: number;+ maxRetries?: number;+ describeUnauthorized?: string;+};++export type JsonClient = {+ request<T>(path: string, init?: RequestInit): Promise<T>;+};++const DEFAULT_TIMEOUT_MS = 30_000;+const DEFAULT_MAX_RETRIES = 5;+const MAX_RETRY_WAIT_MS = 60_000;++export function normalizeBaseUrl(raw: string): string {+ const trimmed = raw.trim().replace(/\/+$/, "");+ const withProtocol = /^https?:\/\//i.test(trimmed)+ ? trimmed+ : `https://${trimmed}`;+ try {+ const url = new URL(withProtocol);+ const path = url.pathname.replace(/\/+$/, "");+ return `${url.protocol}//${url.host}${path}`;+ } catch {+ return withProtocol;+ }+}++export function createJsonClient(options: JsonClientOptions): JsonClient {+ const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;++ async function request<T>(path: string, init?: RequestInit): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ const headers = new Headers(init?.headers);+ for (const [name, value] of Object.entries(options.headers())) {+ headers.set(name, value);+ }+ headers.set("Accept", "application/json");+ if (init?.body != null && !headers.has("Content-Type")) {+ headers.set("Content-Type", "application/json");+ }++ const signals = [AbortSignal.timeout(timeoutMs)];+ if (options.signal) signals.push(options.signal);++ let res: Response;+ try {+ res = await fetchImpl(`${options.baseUrl}${path}`, {+ ...init,+ headers,+ signal: AbortSignal.any(signals),+ });+ } catch (error) {+ if (options.signal?.aborted) throw error;+ const reason = error instanceof Error ? error.message : String(error);+ throw new Error(`${options.service} ${stripQuery(path)}: ${reason}`);+ }++ if (res.status === 429 && attempt < maxRetries) {+ await res.body?.cancel();+ await wait(retryDelayMs(res.headers, attempt), options.signal);+ continue;+ }++ const body = await readBody(res);+ if (!res.ok) {+ throw new SourceHttpError(+ `${options.service} ${stripQuery(path)}: ${describeError(+ body,+ res.status,+ options,+ )}`,+ res.status,+ body,+ );+ }++ return body as T;+ }+ }++ return { request };+}++export function retryDelayMs(headers: Headers, attempt: number): number {+ const retryAfter = headers.get("retry-after");+ if (retryAfter) {+ const seconds = Number(retryAfter);+ if (Number.isFinite(seconds)) return clampWait(seconds * 1000);+ const date = Date.parse(retryAfter);+ if (!Number.isNaN(date)) return clampWait(date - Date.now());+ }++ const reset =+ headers.get("x-ratelimit-reset") ?? headers.get("x-rate-limit-reset");+ if (reset) {+ const value = Number(reset);+ if (Number.isFinite(value)) {+ const resetMs = value > 1e12 ? value : value * 1000;+ if (resetMs > Date.now()) return clampWait(resetMs - Date.now());+ }+ }++ return clampWait(2 ** attempt * 1000);+}++function clampWait(ms: number): number {+ return Math.min(MAX_RETRY_WAIT_MS, Math.max(250, ms));+}++function wait(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(signal.reason);+ return;+ }+ const timer = setTimeout(() => {+ signal?.removeEventListener("abort", onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(timer);+ reject(signal?.reason);+ }+ signal?.addEventListener("abort", onAbort, { once: true });+ });+}++async function readBody(res: Response): Promise<unknown> {+ const text = await res.text();+ if (!text) return null;+ try {+ return JSON.parse(text) as unknown;+ } catch {+ return text;+ }+}++function stripQuery(path: string): string {+ const index = path.indexOf("?");+ return index === -1 ? path : path.slice(0, index);+}++function describeError(+ body: unknown,+ status: number,+ options: JsonClientOptions,+): string {+ if (status === 401) {+ return (+ options.describeUnauthorized ??+ `unauthorized (HTTP 401), check your ${options.service} credentials`+ );+ }+ if (typeof body === "object" && body !== null) {+ const record = body as Record<string, unknown>;+ for (const key of ["message", "problem", "error", "detail"]) {+ const value = record[key];+ if (typeof value === "string" && value.length > 0) return value;+ }+ }+ if (typeof body === "string" && body.length > 0 && !/^\s*</.test(body)) {+ return body.length > 300 ? `${body.slice(0, 300)}…` : body;+ }+ return `HTTP ${status}`;+}diff --git a/packages/importers/src/index.ts b/packages/importers/src/index.tsnew file mode 100644index 000000000..828aa9d42--- /dev/null+++ b/packages/importers/src/index.ts@@ -0,0 +1,63 @@+import { connectKaneo, type KaneoCredentials } from "./kaneo/index.js";+import { connectLinear, type LinearCredentials } from "./linear/index.js";+import { connectPlane, type PlaneCredentials } from "./plane/index.js";+import { connectPlanka, type PlankaCredentials } from "./planka/index.js";+import { connectTrello, type TrelloCredentials } from "./trello/index.js";+import type { ConnectOptions, ImportSource } from "./types.js";++export { normalizeBaseUrl, SourceHttpError } from "./http.js";+export {+ SOURCE_PROJECT_KEY_MAX,+ sanitizeProjectKey,+ toProjectKey,+ uniqueKey,+} from "./keys.js";+export { trelloAuthorizeUrl } from "./trello/index.js";+export type * from "./types.js";+export type {+ KaneoCredentials,+ LinearCredentials,+ PlaneCredentials,+ PlankaCredentials,+ TrelloCredentials,+};++export const IMPORT_SOURCE_IDS = [+ "planka",+ "plane",+ "linear",+ "trello",+ "kaneo",+] as const;++export type ImportSourceId = (typeof IMPORT_SOURCE_IDS)[number];++export type ImportCredentials = {+ planka: PlankaCredentials;+ plane: PlaneCredentials;+ linear: LinearCredentials;+ trello: TrelloCredentials;+ kaneo: KaneoCredentials;+};++export type ImportConnection = {+ [Source in ImportSourceId]: { source: Source } & ImportCredentials[Source];+}[ImportSourceId];++export function connectSource(+ connection: ImportConnection,+ options: ConnectOptions = {},+): Promise<ImportSource> {+ switch (connection.source) {+ case "planka":+ return connectPlanka(connection, options);+ case "plane":+ return connectPlane(connection, options);+ case "linear":+ return connectLinear(connection, options);+ case "trello":+ return connectTrello(connection, options);+ case "kaneo":+ return connectKaneo(connection, options);+ }+}diff --git a/packages/importers/src/kaneo/board.test.ts b/packages/importers/src/kaneo/board.test.tsnew file mode 100644index 000000000..321c802ab--- /dev/null+++ b/packages/importers/src/kaneo/board.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from "vite-plus/test";+import { mergeBoardPages, orderTasks } from "./board.js";+import type { KaneoBoard, KaneoBoardColumn, KaneoBoardTask } from "./client.js";++function task(+ id: string,+ status: string,+ overrides: Partial<KaneoBoardTask> = {},+): KaneoBoardTask {+ return {+ id,+ title: id,+ number: null,+ description: null,+ status,+ priority: "no-priority",+ position: null,+ userId: null,+ labels: [],+ externalLinks: [],+ ...overrides,+ };+}++function column(+ slug: string,+ position: number,+ tasks: KaneoBoardTask[] = [],+): KaneoBoardColumn {+ return { id: slug, slug, name: slug, isFinal: false, position, tasks };+}++function board(overrides: Partial<KaneoBoard>): KaneoBoard {+ return {+ id: "p1",+ name: "Project",+ description: null,+ workspaceId: "ws1",+ columns: [],+ plannedTasks: [],+ archivedTasks: [],+ ...overrides,+ };+}++describe("mergeBoardPages", () => {+ it("dedupes tasks across related pages and merges their labels", () => {+ const red = { id: "l1", name: "Bug", color: "red" };+ const blue = { id: "l2", name: "UI", color: "purple" };+ const merged = mergeBoardPages([+ board({+ columns: [column("to-do", 0, [task("t1", "to-do", { labels: [red] })])],+ }),+ board({+ columns: [+ column("to-do", 0, [task("t1", "to-do", { labels: [red, blue] })]),+ ],+ }),+ ]);++ expect(merged.tasks).toHaveLength(1);+ expect(merged.tasks[0]?.labels).toEqual([red, blue]);+ });++ it("collects planned and archived tasks and orders columns by position", () => {+ const merged = mergeBoardPages([+ board({+ columns: [column("done", 2), column("to-do", 0)],+ plannedTasks: [task("t2", "planned")],+ }),+ board({+ columns: [column("in-progress", 1)],+ archivedTasks: [task("t3", "archived")],+ }),+ ]);++ expect(merged.columns.map((c) => c.slug)).toEqual([+ "to-do",+ "in-progress",+ "done",+ ]);+ expect(merged.tasks.map((t) => t.id)).toEqual(["t2", "t3"]);+ });+});++describe("orderTasks", () => {+ it("orders by column, then position, then number, with planned and archived last", () => {+ const columns = [column("to-do", 0), column("done", 1)];+ const ordered = orderTasks(columns, [+ task("archived", "archived", { position: 0 }),+ task("done-1", "done", { position: 0 }),+ task("todo-b", "to-do", { position: 2 }),+ task("planned", "planned", { position: 0 }),+ task("todo-a", "to-do", { position: 1 }),+ task("todo-c", "to-do", { position: 2, number: 1 }),+ ]);++ expect(ordered.map((t) => t.id)).toEqual([+ "todo-a",+ "todo-c",+ "todo-b",+ "done-1",+ "planned",+ "archived",+ ]);+ });+});diff --git a/packages/importers/src/kaneo/board.ts b/packages/importers/src/kaneo/board.tsnew file mode 100644index 000000000..be0c78be5--- /dev/null+++ b/packages/importers/src/kaneo/board.ts@@ -0,0 +1,124 @@+import type { KaneoBoard, KaneoBoardColumn, KaneoBoardTask } from "./client.js";++export type MergedBoard = {+ columns: KaneoBoardColumn[];+ tasks: KaneoBoardTask[];+};++export const PLANNED_STATUS = "planned";+export const ARCHIVED_STATUS = "archived";++export function columnSlug(column: KaneoBoardColumn): string {+ return column.slug ?? column.id;+}++export function boardTasks(board: KaneoBoard): KaneoBoardTask[] {+ return [+ ...board.columns.flatMap((column) => column.tasks ?? []),+ ...(board.plannedTasks ?? []),+ ...(board.archivedTasks ?? []),+ ];+}++export function mergeBoardPages(pages: KaneoBoard[]): MergedBoard {+ const columns = new Map<string, KaneoBoardColumn>();+ const tasks = new Map<string, KaneoBoardTask>();++ for (const page of pages) {+ for (const column of page.columns) {+ const slug = columnSlug(column);+ if (!columns.has(slug)) columns.set(slug, { ...column, tasks: [] });+ }+ for (const task of boardTasks(page)) {+ const existing = tasks.get(task.id);+ if (!existing) {+ tasks.set(task.id, {+ ...task,+ labels: uniqueBy(task.labels ?? [], labelIdentity),+ externalLinks: uniqueBy(task.externalLinks ?? [], (link) => link.id),+ });+ continue;+ }+ existing.labels = uniqueBy(+ [...(existing.labels ?? []), ...(task.labels ?? [])],+ labelIdentity,+ );+ existing.externalLinks = uniqueBy(+ [...(existing.externalLinks ?? []), ...(task.externalLinks ?? [])],+ (link) => link.id,+ );+ }+ }++ return {+ columns: stableSortBy([...columns.values()], (column) => [+ column.position ?? Number.POSITIVE_INFINITY,+ ]),+ tasks: [...tasks.values()],+ };+}++export function orderTasks(+ columns: KaneoBoardColumn[],+ tasks: KaneoBoardTask[],+): KaneoBoardTask[] {+ const byStatus = new Map<string, KaneoBoardTask[]>();+ for (const task of tasks) {+ const bucket = byStatus.get(task.status) ?? [];+ bucket.push(task);+ byStatus.set(task.status, bucket);+ }++ const statuses = [+ ...columns.map(columnSlug),+ PLANNED_STATUS,+ ...[...byStatus.keys()].filter(+ (status) =>+ status !== PLANNED_STATUS &&+ status !== ARCHIVED_STATUS &&+ !columns.some((column) => columnSlug(column) === status),+ ),+ ARCHIVED_STATUS,+ ];++ return [...new Set(statuses)].flatMap((status) =>+ stableSortBy(byStatus.get(status) ?? [], (task) => [+ task.position ?? Number.POSITIVE_INFINITY,+ task.number ?? Number.POSITIVE_INFINITY,+ ]),+ );+}++function labelIdentity(label: { id?: string; name: string }): string {+ return label.id ?? `name:${label.name}`;+}++function uniqueBy<T>(items: T[], identity: (item: T) => string): T[] {+ const seen = new Set<string>();+ return items.filter((item) => {+ const key = identity(item);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++function stableSortBy<T>(items: T[], keys: (item: T) => number[]): T[] {+ return items+ .map((item, index) => ({ item, index, keys: keys(item) }))+ .sort((a, b) => {+ for (let i = 0; i < a.keys.length; i++) {+ const diff = compareNumbers(a.keys[i], b.keys[i]);+ if (diff !== 0) return diff;+ }+ return a.index - b.index;+ })+ .map(({ item }) => item);+}++function compareNumbers(a: number | undefined, b: number | undefined): number {+ const left = a ?? Number.POSITIVE_INFINITY;+ const right = b ?? Number.POSITIVE_INFINITY;+ if (left === right) return 0;+ return left < right ? -1 : 1;+}diff --git a/packages/importers/src/kaneo/client.ts b/packages/importers/src/kaneo/client.tsnew file mode 100644index 000000000..392167d8e--- /dev/null+++ b/packages/importers/src/kaneo/client.ts@@ -0,0 +1,245 @@+import { createJsonClient, SourceHttpError } from "../http.js";+import type { FetchLike } from "../types.js";++export type KaneoWorkspace = {+ id: string;+ name: string;+};++export type KaneoProject = {+ id: string;+ name: string;+ archivedAt?: string | null;+};++export type KaneoLabel = {+ id?: string;+ name: string;+ color: string | null;+};++export type KaneoExternalLink = {+ id: string;+};++export type KaneoBoardTask = {+ id: string;+ title: string;+ number: number | null;+ description: string | null;+ descriptionDeferred?: boolean;+ status: string;+ priority: string | null;+ startDate?: string | null;+ dueDate?: string | null;+ position: number | null;+ createdAt?: string | null;+ userId: string | null;+ assigneeName?: string | null;+ labels?: KaneoLabel[];+ externalLinks?: KaneoExternalLink[];+};++export type KaneoBoardColumn = {+ id: string;+ slug?: string;+ name: string;+ isFinal?: boolean;+ position?: number;+ tasks?: KaneoBoardTask[];+};++export type KaneoBoard = {+ id: string;+ name: string;+ slug?: string | null;+ description: string | null;+ descriptionDeferred?: boolean;+ workspaceId: string;+ columns: KaneoBoardColumn[];+ plannedTasks?: KaneoBoardTask[];+ archivedTasks?: KaneoBoardTask[];+};++export type KaneoBoardPagination = {+ total?: number;+ totalPages?: number;+ relatedTotalPages?: number;+};++export type KaneoBoardPage = {+ board: KaneoBoard;+ pagination: KaneoBoardPagination;+};++export type KaneoMember = {+ id: string;+ name: string;+ email: string;+};++export type KaneoActivity = {+ id: string;+ type: string;+ userId: string | null;+ content: string | null;+ createdAt: string;+ externalUserName?: string | null;+};++export type KaneoComment = {+ id: string;+ user?: { name?: string | null } | null;+};++export type KaneoRelation = {+ id?: string;+ sourceTaskId: string;+ targetTaskId: string;+ relationType: string;+};++export type KaneoCustomField = {+ id: string;+ name: string;+};++export type KaneoClientOptions = {+ baseUrl: string;+ apiKey: string;+ fetch?: FetchLike;+ signal?: AbortSignal;+};++export type KaneoClient = {+ listWorkspaces(): Promise<KaneoWorkspace[]>;+ listProjects(workspaceId: string): Promise<KaneoProject[]>;+ getBoardPage(+ projectId: string,+ page: number,+ relatedPage: number,+ ): Promise<KaneoBoardPage>;+ getProjectDescription(projectId: string): Promise<string | null>;+ getTaskDescription(taskId: string): Promise<string | null>;+ listMembers(workspaceId: string): Promise<KaneoMember[]>;+ listActivities(taskId: string): Promise<KaneoActivity[]>;+ listComments(taskId: string): Promise<KaneoComment[]>;+ listRelations(taskId: string): Promise<KaneoRelation[]>;+ listCustomFields(projectId: string): Promise<KaneoCustomField[]>;+};++export const BOARD_PAGE_SIZE = 100;++export function createKaneoClient(options: KaneoClientOptions): KaneoClient {+ const http = createJsonClient({+ service: "Kaneo",+ baseUrl: options.baseUrl,+ headers: () => ({ Authorization: `Bearer ${options.apiKey}` }),+ fetch: options.fetch,+ signal: options.signal,+ describeUnauthorized:+ "Kaneo rejected the API key (HTTP 401). Check that the key is active and was created on this instance.",+ });++ async function list<T>(path: string): Promise<T[]> {+ const body = await http.request<unknown>(path);+ if (!Array.isArray(body)) throw notKaneoError(options.baseUrl);+ return body as T[];+ }++ const id = encodeURIComponent;++ return {+ async listWorkspaces() {+ try {+ return await list<KaneoWorkspace>("/api/workspace");+ } catch (error) {+ if (!(error instanceof SourceHttpError) || error.status !== 404) {+ throw error;+ }+ }+ try {+ return await list<KaneoWorkspace>("/api/auth/organization/list");+ } catch (error) {+ if (error instanceof SourceHttpError && error.status === 404) {+ throw notKaneoError(options.baseUrl);+ }+ throw error;+ }+ },+ listProjects(workspaceId) {+ return list<KaneoProject>(+ `/api/project?workspaceId=${id(workspaceId)}&includeArchived=true`,+ );+ },+ async getBoardPage(projectId, page, relatedPage) {+ const query = new URLSearchParams({+ page: String(page),+ limit: String(BOARD_PAGE_SIZE),+ sortBy: "position",+ sortOrder: "asc",+ });+ if (relatedPage > 1) query.set("relatedPage", String(relatedPage));+ const body = await http.request<unknown>(+ `/api/task/tasks/${id(projectId)}?${query}`,+ );+ return toBoardPage(body);+ },+ async getProjectDescription(projectId) {+ const project = await http.request<{ description?: string | null }>(+ `/api/project/${id(projectId)}`,+ );+ return project?.description ?? null;+ },+ async getTaskDescription(taskId) {+ const task = await http.request<{ description?: string | null }>(+ `/api/task/${id(taskId)}`,+ );+ return task?.description ?? null;+ },+ listMembers(workspaceId) {+ return list<KaneoMember>(`/api/workspace/${id(workspaceId)}/members`);+ },+ listActivities(taskId) {+ return list<KaneoActivity>(`/api/activity/${id(taskId)}`);+ },+ listComments(taskId) {+ return list<KaneoComment>(`/api/comment/${id(taskId)}`);+ },+ listRelations(taskId) {+ return list<KaneoRelation>(`/api/task-relation/${id(taskId)}`);+ },+ listCustomFields(projectId) {+ return list<KaneoCustomField>(+ `/api/custom-field/project/${id(projectId)}`,+ );+ },+ };+}++export function toBoardPage(body: unknown): KaneoBoardPage {+ if (isRecord(body) && isBoard(body.data)) {+ const pagination = isRecord(body.pagination)+ ? (body.pagination as KaneoBoardPagination)+ : {};+ return { board: body.data, pagination };+ }+ if (isBoard(body)) return { board: body, pagination: {} };+ throw new Error(+ "Kaneo returned an unexpected response for the project board.",+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function isBoard(value: unknown): value is KaneoBoard {+ return isRecord(value) && Array.isArray(value.columns);+}++function notKaneoError(baseUrl: string): Error {+ return new Error(+ `No Kaneo API answered at ${baseUrl}. Check the instance URL; if the web app and API are hosted separately, use the API URL.`,+ );+}diff --git a/packages/importers/src/kaneo/colors.test.ts b/packages/importers/src/kaneo/colors.test.tsnew file mode 100644index 000000000..d332f5b61--- /dev/null+++ b/packages/importers/src/kaneo/colors.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vite-plus/test";+import { kaneoColorToHex } from "./colors.js";++describe("kaneoColorToHex", () => {+ it("maps Kaneo palette names to hex", () => {+ expect(kaneoColorToHex("purple")).toBe("#8b5cf6");+ expect(kaneoColorToHex("dark-gray")).toBe("#64748b");+ expect(kaneoColorToHex("Red")).toBe("#dc2626");+ });++ it("normalizes hex values", () => {+ expect(kaneoColorToHex("#ABCDEF")).toBe("#abcdef");+ expect(kaneoColorToHex("#abc")).toBe("#aabbcc");+ expect(kaneoColorToHex("#abcd")).toBe("#aabbcc");+ expect(kaneoColorToHex("#11223344")).toBe("#112233");+ });++ it("falls back to gray for unknown values", () => {+ expect(kaneoColorToHex("var(--color-sky-500)")).toBe("#6b7280");+ expect(kaneoColorToHex("")).toBe("#6b7280");+ expect(kaneoColorToHex(null)).toBe("#6b7280");+ });+});diff --git a/packages/importers/src/kaneo/colors.ts b/packages/importers/src/kaneo/colors.tsnew file mode 100644index 000000000..9fd1b6e4d--- /dev/null+++ b/packages/importers/src/kaneo/colors.ts@@ -0,0 +1,26 @@+const NAMED_COLORS: Record<string, string> = {+ gray: "#78716c",+ "dark-gray": "#64748b",+ purple: "#8b5cf6",+ teal: "#059669",+ green: "#16a34a",+ yellow: "#d97706",+ orange: "#ea580c",+ pink: "#e11d48",+ red: "#dc2626",+};++const FALLBACK_COLOR = "#6b7280";++export function kaneoColorToHex(color: string | null | undefined): string {+ const value = color?.trim().toLowerCase();+ if (!value) return FALLBACK_COLOR;++ const named = NAMED_COLORS[value];+ if (named) return named;++ const hex = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/.exec(value)?.[1];+ if (!hex) return FALLBACK_COLOR;+ if (hex.length >= 6) return `#${hex.slice(0, 6)}`;+ return `#${[...hex.slice(0, 3)].map((digit) => digit + digit).join("")}`;+}diff --git a/packages/importers/src/kaneo/index.ts b/packages/importers/src/kaneo/index.tsnew file mode 100644index 000000000..b7198bf7a--- /dev/null+++ b/packages/importers/src/kaneo/index.ts@@ -0,0 +1 @@+export { connectKaneo, type KaneoCredentials } from "./source.js";diff --git a/packages/importers/src/kaneo/mapping.test.ts b/packages/importers/src/kaneo/mapping.test.tsnew file mode 100644index 000000000..d6342d0f8--- /dev/null+++ b/packages/importers/src/kaneo/mapping.test.ts@@ -0,0 +1,322 @@+import { describe, expect, it } from "vite-plus/test";+import type { KaneoActivity, KaneoBoardTask, KaneoMember } from "./client.js";+import {+ collectLabels,+ mapColumns,+ mapComments,+ mapPriority,+ mapRelations,+ mapTask,+ needsAuthorNames,+ UNKNOWN_AUTHOR,+} from "./mapping.js";++function task(overrides: Partial<KaneoBoardTask> = {}): KaneoBoardTask {+ return {+ id: "t1",+ title: "Write docs",+ number: 1,+ description: "Some **markdown**",+ status: "to-do",+ priority: "high",+ position: 0,+ userId: null,+ labels: [],+ externalLinks: [],+ ...overrides,+ };+}++function activity(overrides: Partial<KaneoActivity>): KaneoActivity {+ return {+ id: "a1",+ type: "comment",+ userId: "u1",+ content: "Hello",+ createdAt: "2026-01-01T10:00:00.000Z",+ externalUserName: null,+ ...overrides,+ };+}++const members = new Map<string, KaneoMember>([+ ["u1", { id: "u1", name: "Ada", email: "[email protected]" }],+]);++describe("mapPriority", () => {+ it("passes Kaneo priorities through", () => {+ expect(mapPriority("urgent")).toBe("urgent");+ expect(mapPriority("no-priority")).toBe("no-priority");+ expect(mapPriority("Medium")).toBe("medium");+ });++ it("falls back to no-priority", () => {+ expect(mapPriority(null)).toBe("no-priority");+ expect(mapPriority("critical")).toBe("no-priority");+ });+});++describe("mapColumns", () => {+ it("uses the slug as key and keeps isFinal", () => {+ expect(+ mapColumns([+ { id: "to-do", slug: "to-do", name: "To Do", isFinal: false },+ { id: "shipped", slug: "shipped", name: "Shipped", isFinal: true },+ ]),+ ).toEqual([+ { key: "to-do", name: "To Do", isFinal: false },+ { key: "shipped", name: "Shipped", isFinal: true },+ ]);+ });++ it("treats a legacy done column as final when isFinal is missing", () => {+ expect(mapColumns([{ id: "done", name: "Done" }])).toEqual([+ { key: "done", name: "Done", isFinal: true },+ ]);+ });+});++describe("collectLabels", () => {+ it("dedupes by name and converts colors", () => {+ expect(+ collectLabels([+ task({ labels: [{ id: "l1", name: "Bug", color: "red" }] }),+ task({+ id: "t2",+ labels: [+ { id: "l2", name: "Bug", color: "red" },+ { id: "l3", name: "UI", color: "#ABC" },+ ],+ }),+ ]),+ ).toEqual([+ { key: "Bug", name: "Bug", color: "#dc2626" },+ { key: "UI", name: "UI", color: "#aabbcc" },+ ]);+ });+});++describe("mapTask", () => {+ const columnKeys = new Set(["to-do", "done"]);++ it("maps a board task", () => {+ expect(+ mapTask(+ task({+ userId: "u1",+ assigneeName: "Ada L.",+ startDate: "2026-02-01T00:00:00.000Z",+ dueDate: "2026-02-03T00:00:00.000Z",+ createdAt: "2026-01-01T00:00:00.000Z",+ labels: [+ { id: "l1", name: "Bug", color: "red" },+ { id: "l2", name: "Bug", color: "red" },+ ],+ }),+ columnKeys,+ members,+ ),+ ).toEqual({+ key: "t1",+ number: 1,+ columnKey: "to-do",+ title: "Write docs",+ description: "Some **markdown**",+ priority: "high",+ startDate: "2026-02-01T00:00:00.000Z",+ dueDate: "2026-02-03T00:00:00.000Z",+ createdAt: "2026-01-01T00:00:00.000Z",+ assignee: { name: "Ada", email: "[email protected]" },+ labelKeys: ["Bug"],+ comments: [],+ });+ });++ it("maps planned tasks to no column and archived tasks to archived", () => {+ expect(+ mapTask(task({ status: "planned" }), columnKeys, members),+ ).toMatchObject({ columnKey: null });+ const archived = mapTask(task({ status: "archived" }), columnKeys, members);+ expect(archived.columnKey).toBeNull();+ expect(archived.archived).toBe(true);+ });++ it("leaves the number out when the source task has none", () => {+ expect(+ mapTask(task({ number: null }), columnKeys, members),+ ).not.toHaveProperty("number");+ });++ it("keeps the assignee name when the member is gone", () => {+ expect(+ mapTask(+ task({ userId: "u9", assigneeName: "Former" }),+ columnKeys,+ members,+ ).assignee,+ ).toEqual({ name: "Former" });+ });++ it("prefers a fully loaded description", () => {+ expect(+ mapTask(+ task({ description: null, descriptionDeferred: true }),+ columnKeys,+ members,+ {+ description: "Full text",+ },+ ).description,+ ).toBe("Full text");+ });+});++describe("mapComments", () => {+ it("keeps only comments, oldest first, with the right authors", () => {+ const comments = mapComments(+ [+ activity({+ id: "a3",+ userId: "u2",+ content: "Third",+ createdAt: "2026-01-03T00:00:00.000Z",+ }),+ activity({+ id: "a2",+ type: "status_changed",+ content: "moved",+ createdAt: "2026-01-02T12:00:00.000Z",+ }),+ activity({+ id: "a2b",+ externalUserName: "Trello Tom",+ content: "Second",+ createdAt: "2026-01-02T00:00:00.000Z",+ }),+ activity({ id: "a1", content: "First" }),+ activity({ id: "a0", content: " " }),+ ],+ members,+ new Map([["a3", "Grace"]]),+ );++ expect(comments).toEqual([+ {+ author: { name: "Ada", email: "[email protected]" },+ body: "First",+ createdAt: "2026-01-01T10:00:00.000Z",+ },+ {+ author: { name: "Trello Tom" },+ body: "Second",+ createdAt: "2026-01-02T00:00:00.000Z",+ },+ {+ author: { name: "Grace" },+ body: "Third",+ createdAt: "2026-01-03T00:00:00.000Z",+ },+ ]);+ });++ it("keeps API order reversed for comments with the same timestamp", () => {+ const comments = mapComments(+ [+ activity({ id: "b", content: "Later" }),+ activity({ id: "a", content: "Earlier" }),+ ],+ members,+ );+ expect(comments.map((comment) => comment.body)).toEqual([+ "Earlier",+ "Later",+ ]);+ });++ it("falls back to an unknown author", () => {+ expect(+ mapComments([activity({ userId: null })], members)[0]?.author,+ ).toEqual({ name: UNKNOWN_AUTHOR });+ });+});++describe("needsAuthorNames", () => {+ it("is true only when a comment author is neither external nor a member", () => {+ expect(needsAuthorNames([activity({})], members)).toBe(false);+ expect(+ needsAuthorNames(+ [activity({ userId: "u2", externalUserName: "X" })],+ members,+ ),+ ).toBe(false);+ expect(needsAuthorNames([activity({ userId: "u2" })], members)).toBe(true);+ expect(+ needsAuthorNames(+ [activity({ userId: "u2", type: "status_changed" })],+ members,+ ),+ ).toBe(false);+ });+});++describe("mapRelations", () => {+ it("dedupes, keeps in-project links and counts the rest", () => {+ const ids = new Set(["t1", "t2", "t3"]);+ expect(+ mapRelations(+ [+ {+ id: "r1",+ sourceTaskId: "t1",+ targetTaskId: "t2",+ relationType: "subtask",+ },+ {+ id: "r1",+ sourceTaskId: "t1",+ targetTaskId: "t2",+ relationType: "subtask",+ },+ {+ id: "r2",+ sourceTaskId: "t2",+ targetTaskId: "t3",+ relationType: "blocks",+ },+ {+ id: "r3",+ sourceTaskId: "t3",+ targetTaskId: "t1",+ relationType: "related",+ },+ {+ id: "r4",+ sourceTaskId: "t1",+ targetTaskId: "x9",+ relationType: "related",+ },+ {+ id: "r4",+ sourceTaskId: "t1",+ targetTaskId: "x9",+ relationType: "related",+ },+ {+ id: "r5",+ sourceTaskId: "t1",+ targetTaskId: "t3",+ relationType: "duplicates",+ },+ ],+ ids,+ ),+ ).toEqual({+ relations: [+ { sourceKey: "t1", targetKey: "t2", type: "subtask" },+ { sourceKey: "t2", targetKey: "t3", type: "blocks" },+ { sourceKey: "t3", targetKey: "t1", type: "related" },+ ],+ outsideProject: 1,+ });+ });+});diff --git a/packages/importers/src/kaneo/mapping.ts b/packages/importers/src/kaneo/mapping.tsnew file mode 100644index 000000000..4b5abd909--- /dev/null+++ b/packages/importers/src/kaneo/mapping.ts@@ -0,0 +1,220 @@+import { toIsoDate } from "../markdown.js";+import type {+ ImportedColumn,+ ImportedComment,+ ImportedLabel,+ ImportedPerson,+ ImportedPriority,+ ImportedRelation,+ ImportedRelationType,+ ImportedTask,+} from "../types.js";+import { ARCHIVED_STATUS, columnSlug } from "./board.js";+import type {+ KaneoActivity,+ KaneoBoardColumn,+ KaneoBoardTask,+ KaneoMember,+ KaneoRelation,+} from "./client.js";+import { kaneoColorToHex } from "./colors.js";++const PRIORITIES: ImportedPriority[] = [+ "no-priority",+ "low",+ "medium",+ "high",+ "urgent",+];++const RELATION_TYPES: ImportedRelationType[] = ["subtask", "blocks", "related"];++export const UNKNOWN_AUTHOR = "Unknown user";++export function mapPriority(+ value: string | null | undefined,+): ImportedPriority {+ const normalized = value?.trim().toLowerCase();+ return (+ PRIORITIES.find((priority) => priority === normalized) ?? "no-priority"+ );+}++export function mapColumns(columns: KaneoBoardColumn[]): ImportedColumn[] {+ return columns.map((column) => {+ const key = columnSlug(column);+ return {+ key,+ name: column.name,+ isFinal: column.isFinal ?? key === "done",+ };+ });+}++export function collectLabels(tasks: KaneoBoardTask[]): ImportedLabel[] {+ const labels = new Map<string, ImportedLabel>();+ for (const task of tasks) {+ for (const label of task.labels ?? []) {+ const name = label.name.trim();+ if (!name || labels.has(name)) continue;+ labels.set(name, {+ key: name,+ name,+ color: kaneoColorToHex(label.color),+ });+ }+ }+ return [...labels.values()];+}++export function mapAssignee(+ task: KaneoBoardTask,+ members: Map<string, KaneoMember>,+): ImportedPerson | undefined {+ if (!task.userId) return undefined;+ const member = members.get(task.userId);+ const name = member?.name?.trim() || task.assigneeName?.trim() || undefined;+ const email = member?.email?.trim() || undefined;+ if (!name && !email) return undefined;+ return { ...(name ? { name } : {}), ...(email ? { email } : {}) };+}++export type TaskExtras = {+ description?: string | null;+ comments?: ImportedComment[];+};++export function mapTask(+ task: KaneoBoardTask,+ columnKeys: Set<string>,+ members: Map<string, KaneoMember>,+ extras: TaskExtras = {},+): ImportedTask {+ const archived = task.status === ARCHIVED_STATUS;+ const assignee = mapAssignee(task, members);+ const labelKeys = [+ ...new Set(+ (task.labels ?? []).map((label) => label.name.trim()).filter(Boolean),+ ),+ ];++ return {+ key: task.id,+ ...(typeof task.number === "number" ? { number: task.number } : {}),+ columnKey: !archived && columnKeys.has(task.status) ? task.status : null,+ ...(archived ? { archived: true } : {}),+ title: task.title,+ description: extras.description ?? task.description ?? "",+ priority: mapPriority(task.priority),+ startDate: toIsoDate(task.startDate),+ dueDate: toIsoDate(task.dueDate),+ createdAt: toIsoDate(task.createdAt),+ ...(assignee ? { assignee } : {}),+ labelKeys,+ comments: extras.comments ?? [],+ };+}++export function commentActivities(+ activities: KaneoActivity[],+): KaneoActivity[] {+ return activities+ .filter(+ (activity) => activity.type === "comment" && activity.content?.trim(),+ )+ .map((activity, index) => ({ activity, index }))+ .sort((a, b) => {+ const diff = timeOf(a.activity.createdAt) - timeOf(b.activity.createdAt);+ return diff !== 0 ? diff : b.index - a.index;+ })+ .map(({ activity }) => activity);+}++export function needsAuthorNames(+ activities: KaneoActivity[],+ members: Map<string, KaneoMember>,+): boolean {+ return commentActivities(activities).some(+ (activity) =>+ !activity.externalUserName?.trim() &&+ !(activity.userId && members.has(activity.userId)),+ );+}++export function commentAuthor(+ activity: KaneoActivity,+ members: Map<string, KaneoMember>,+ names: Map<string, string>,+): ImportedPerson {+ const external = activity.externalUserName?.trim();+ if (external) return { name: external };++ const member = activity.userId ? members.get(activity.userId) : undefined;+ if (member) {+ const email = member.email?.trim();+ return {+ name: member.name?.trim() || email || UNKNOWN_AUTHOR,+ ...(email ? { email } : {}),+ };+ }++ return { name: names.get(activity.id)?.trim() || UNKNOWN_AUTHOR };+}++export function mapComments(+ activities: KaneoActivity[],+ members: Map<string, KaneoMember>,+ names: Map<string, string> = new Map(),+): ImportedComment[] {+ return commentActivities(activities).map((activity) => ({+ author: commentAuthor(activity, members, names),+ body: activity.content ?? "",+ createdAt: toIsoDate(activity.createdAt),+ }));+}++export type MappedRelations = {+ relations: ImportedRelation[];+ outsideProject: number;+};++export function mapRelations(+ relations: KaneoRelation[],+ taskIds: Set<string>,+): MappedRelations {+ const seen = new Set<string>();+ const mapped: ImportedRelation[] = [];+ let outsideProject = 0;++ for (const relation of relations) {+ const type = RELATION_TYPES.find(+ (value) => value === relation.relationType,+ );+ if (!type || relation.sourceTaskId === relation.targetTaskId) continue;++ const identity = `${relation.sourceTaskId}:${relation.targetTaskId}:${type}`;+ if (seen.has(identity)) continue;+ seen.add(identity);++ if (+ !taskIds.has(relation.sourceTaskId) ||+ !taskIds.has(relation.targetTaskId)+ ) {+ outsideProject++;+ continue;+ }++ mapped.push({+ sourceKey: relation.sourceTaskId,+ targetKey: relation.targetTaskId,+ type,+ });+ }++ return { relations: mapped, outsideProject };+}++function timeOf(value: string): number {+ const time = Date.parse(value);+ return Number.isNaN(time) ? 0 : time;+}diff --git a/packages/importers/src/kaneo/optional.ts b/packages/importers/src/kaneo/optional.tsnew file mode 100644index 000000000..ca82dfe21--- /dev/null+++ b/packages/importers/src/kaneo/optional.ts@@ -0,0 +1,27 @@+import { SourceHttpError } from "../http.js";++export type OptionalResult<T> =+ | { status: "ok"; value: T }+ | { status: "gone" }+ | { status: "unsupported" };++const RESOURCE_GONE = /^(task|project|workspace) not found$/i;++export async function readOptional<T>(+ request: () => Promise<T>,+): Promise<OptionalResult<T>> {+ try {+ return { status: "ok", value: await request() };+ } catch (error) {+ if (!(error instanceof SourceHttpError) || error.status !== 404) {+ throw error;+ }+ return { status: isResourceGone(error.body) ? "gone" : "unsupported" };+ }+}++function isResourceGone(body: unknown): boolean {+ if (typeof body !== "object" || body === null) return false;+ const message = (body as Record<string, unknown>).message;+ return typeof message === "string" && RESOURCE_GONE.test(message.trim());+}diff --git a/packages/importers/src/kaneo/read-board.ts b/packages/importers/src/kaneo/read-board.tsnew file mode 100644index 000000000..dfa4d618c--- /dev/null+++ b/packages/importers/src/kaneo/read-board.ts@@ -0,0 +1,36 @@+import { boardTasks, type MergedBoard, mergeBoardPages } from "./board.js";+import type { KaneoBoard, KaneoClient } from "./client.js";++export type ReadBoardResult = MergedBoard & {+ project: KaneoBoard;+};++export async function readBoard(+ client: KaneoClient,+ projectId: string,+ onProgress?: (message: string) => void,+): Promise<ReadBoardResult> {+ const pages: KaneoBoard[] = [];+ let totalPages = 1;+ let read = 0;++ for (let page = 1; page <= totalPages; page++) {+ const first = await client.getBoardPage(projectId, page, 1);+ pages.push(first.board);+ totalPages = Math.max(1, first.pagination.totalPages ?? 1);++ const relatedPages = Math.max(1, first.pagination.relatedTotalPages ?? 1);+ for (let related = 2; related <= relatedPages; related++) {+ const extra = await client.getBoardPage(projectId, page, related);+ pages.push(extra.board);+ }++ read += boardTasks(first.board).length;+ const total = Math.max(read, first.pagination.total ?? read);+ onProgress?.(`Reading tasks (${read} of ${total})`);+ }++ const [project] = pages;+ if (!project) throw new Error("Kaneo returned no board for this project.");+ return { project, ...mergeBoardPages(pages) };+}diff --git a/packages/importers/src/kaneo/read-project.ts b/packages/importers/src/kaneo/read-project.tsnew file mode 100644index 000000000..2f129639c--- /dev/null+++ b/packages/importers/src/kaneo/read-project.ts@@ -0,0 +1,93 @@+import { SourceHttpError } from "../http.js";+import type { ImportedProject, ReadProjectOptions } from "../types.js";+import { orderTasks } from "./board.js";+import type { KaneoClient, KaneoMember } from "./client.js";+import { collectLabels, mapColumns, mapRelations, mapTask } from "./mapping.js";+import { readOptional } from "./optional.js";+import { readBoard } from "./read-board.js";+import { readTaskDetails } from "./read-task-details.js";+import { buildWarnings, MEMBERS_UNAVAILABLE_WARNING } from "./warnings.js";++export async function readKaneoProject(+ client: KaneoClient,+ projectId: string,+ options: ReadProjectOptions,+): Promise<ImportedProject> {+ const { project, columns, tasks } = await readBoard(+ client,+ projectId,+ options.onProgress,+ );+ const warnings: string[] = [];++ const membersResult = await readOptional(() =>+ client.listMembers(project.workspaceId),+ );+ if (membersResult.status !== "ok") warnings.push(MEMBERS_UNAVAILABLE_WARNING);+ const members = new Map<string, KaneoMember>(+ membersResult.status === "ok"+ ? membersResult.value.map((member) => [member.id, member])+ : [],+ );++ const customFieldNames = await readCustomFieldNames(client, projectId);+ const description = project.descriptionDeferred+ ? await client.getProjectDescription(projectId)+ : project.description;++ const ordered = orderTasks(columns, tasks);+ const details = await readTaskDetails(client, ordered, {+ includeComments: options.includeComments,+ members,+ onProgress: options.onProgress,+ });+ warnings.push(...details.warnings);++ const importedColumns = mapColumns(columns);+ const columnKeys = new Set(importedColumns.map((column) => column.key));+ const importedTasks = ordered.map((task) =>+ mapTask(task, columnKeys, members, {+ description: details.descriptions.get(task.id),+ comments: details.comments.get(task.id),+ }),+ );+ const { relations, outsideProject } = mapRelations(+ details.relations,+ new Set(ordered.map((task) => task.id)),+ );++ warnings.push(+ ...buildWarnings({+ tasks: ordered,+ imported: importedTasks,+ members,+ customFieldNames,+ relationsOutsideProject: outsideProject,+ }),+ );++ const key = project.slug?.trim();+ return {+ name: project.name,+ ...(key ? { key } : {}),+ ...(description?.trim() ? { description } : {}),+ columns: importedColumns,+ labels: collectLabels(ordered),+ tasks: importedTasks,+ relations,+ warnings,+ };+}++async function readCustomFieldNames(+ client: KaneoClient,+ projectId: string,+): Promise<string[]> {+ try {+ const fields = await client.listCustomFields(projectId);+ return fields.map((field) => field.name.trim()).filter(Boolean);+ } catch (error) {+ if (error instanceof SourceHttpError && error.status < 500) return [];+ throw error;+ }+}diff --git a/packages/importers/src/kaneo/read-task-details.ts b/packages/importers/src/kaneo/read-task-details.tsnew file mode 100644index 000000000..18c770167--- /dev/null+++ b/packages/importers/src/kaneo/read-task-details.ts@@ -0,0 +1,107 @@+import type { ImportedComment } from "../types.js";+import type {+ KaneoBoardTask,+ KaneoClient,+ KaneoMember,+ KaneoRelation,+} from "./client.js";+import { mapComments, needsAuthorNames } from "./mapping.js";+import { readOptional } from "./optional.js";+import {+ COMMENTS_UNAVAILABLE_WARNING,+ RELATIONS_UNAVAILABLE_WARNING,+} from "./warnings.js";++export type TaskDetails = {+ descriptions: Map<string, string>;+ comments: Map<string, ImportedComment[]>;+ relations: KaneoRelation[];+ warnings: string[];+};++export type ReadTaskDetailsOptions = {+ includeComments: boolean;+ members: Map<string, KaneoMember>;+ onProgress?: (message: string) => void;+};++const PROGRESS_EVERY = 50;++export async function readTaskDetails(+ client: KaneoClient,+ tasks: KaneoBoardTask[],+ options: ReadTaskDetailsOptions,+): Promise<TaskDetails> {+ const details: TaskDetails = {+ descriptions: new Map(),+ comments: new Map(),+ relations: [],+ warnings: [],+ };+ let relationsSupported = true;+ let commentsSupported = options.includeComments;+ let commentNamesSupported = true;+ const subject = options.includeComments+ ? "comments and task links"+ : "task links";++ for (const [index, task] of tasks.entries()) {+ if (task.descriptionDeferred) {+ const result = await readOptional(() =>+ client.getTaskDescription(task.id),+ );+ if (result.status === "ok" && result.value != null) {+ details.descriptions.set(task.id, result.value);+ }+ }++ if (relationsSupported) {+ const result = await readOptional(() => client.listRelations(task.id));+ if (result.status === "ok") details.relations.push(...result.value);+ if (result.status === "unsupported") {+ relationsSupported = false;+ details.warnings.push(RELATIONS_UNAVAILABLE_WARNING);+ }+ }++ if (commentsSupported) {+ const result = await readOptional(() => client.listActivities(task.id));+ if (result.status === "unsupported") {+ commentsSupported = false;+ details.warnings.push(COMMENTS_UNAVAILABLE_WARNING);+ }+ if (result.status === "ok") {+ const activities = result.value;+ let names = new Map<string, string>();+ if (+ commentNamesSupported &&+ needsAuthorNames(activities, options.members)+ ) {+ const fallback = await readOptional(() =>+ client.listComments(task.id),+ );+ if (fallback.status === "unsupported") commentNamesSupported = false;+ if (fallback.status === "ok") {+ names = new Map(+ fallback.value.flatMap((comment) => {+ const name = comment.user?.name?.trim();+ return name ? [[comment.id, name] as const] : [];+ }),+ );+ }+ }+ details.comments.set(+ task.id,+ mapComments(activities, options.members, names),+ );+ }+ }++ const done = index + 1;+ if (done % PROGRESS_EVERY === 0 || done === tasks.length) {+ options.onProgress?.(`Reading ${subject} (${done} of ${tasks.length})`);+ }+ }++ return details;+}diff --git a/packages/importers/src/kaneo/source.test.ts b/packages/importers/src/kaneo/source.test.tsnew file mode 100644index 000000000..185d6670c--- /dev/null+++ b/packages/importers/src/kaneo/source.test.ts@@ -0,0 +1,545 @@+import { describe, expect, it, vi } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import { connectKaneo } from "./index.js";++type Reply = { status: number; body: unknown };++const BASE = "https://kaneo.example.com";+const API_KEY = "key-123";++const ok = (body: unknown): Reply => ({ status: 200, body });+const fail = (status: number, message: string): Reply => ({+ status,+ body: { message, code: "ERR" },+});++function fakeFetch(routes: Record<string, Reply>) {+ const calls: Array<{ path: string; headers: Headers }> = [];+ const fetch = vi.fn<FetchLike>(async (input, init) => {+ const url = new URL(input);+ const path = `${url.pathname}${url.search}`;+ calls.push({ path, headers: new Headers(init?.headers) });+ const reply = routes[path] ?? fail(404, "Not found");+ const body =+ typeof reply.body === "string" ? reply.body : JSON.stringify(reply.body);+ return new Response(body, {+ status: reply.status,+ headers: { "content-type": "application/json" },+ });+ });+ return { fetch, calls, paths: () => calls.map((call) => call.path) };+}++function boardPath(projectId: string, page: number, relatedPage = 1): string {+ const related = relatedPage > 1 ? `&relatedPage=${relatedPage}` : "";+ return `/api/task/tasks/${projectId}?page=${page}&limit=100&sortBy=position&sortOrder=asc${related}`;+}++function boardTask(id: string, status: string, extra: object = {}) {+ return {+ id,+ title: `Task ${id}`,+ number: Number(id.slice(1)),+ description: `Description of ${id}`,+ status,+ priority: "medium",+ startDate: null,+ dueDate: null,+ position: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ userId: null,+ assigneeName: null,+ assigneeId: null,+ assigneeImage: null,+ projectId: "p1",+ subtaskCounts: { completed: 0, total: 0 },+ labels: [],+ externalLinks: [],+ ...extra,+ };+}++function boardResponse(+ data: {+ columns: object[];+ plannedTasks?: object[];+ archivedTasks?: object[];+ },+ pagination: { total: number; totalPages: number; relatedTotalPages: number },+) {+ return {+ data: {+ id: "p1",+ name: "Website",+ slug: "WEB",+ icon: null,+ description: "Project **readme**",+ isPublic: false,+ workspaceId: "ws1",+ backgroundVersion: null,+ plannedTasks: [],+ archivedTasks: [],+ ...data,+ },+ pagination: {+ page: 1,+ pageSize: 100,+ relatedPage: 1,+ relatedPageSize: 100,+ ...pagination,+ },+ };+}++const bug = { id: "l1", name: "Bug", color: "red" };+const ui = { id: "l2", name: "UI", color: "purple" };++const t1 = boardTask("t1", "to-do", {+ userId: "u1",+ assigneeName: "Ada",+ labels: [bug],+ dueDate: "2026-03-01T00:00:00.000Z",+});+const t2 = boardTask("t2", "to-do", {+ position: 1,+ priority: "urgent",+ userId: "u9",+ assigneeName: "Former Member",+ description: null,+ descriptionDeferred: true,+ externalLinks: [{ id: "e1" }],+});+const t3 = boardTask("t3", "done");+const t4 = boardTask("t4", "planned", { priority: "low" });+const t5 = boardTask("t5", "archived");++const columns = [+ {+ id: "to-do",+ slug: "to-do",+ name: "To Do",+ icon: null,+ isFinal: false,+ position: 0,+ },+ {+ id: "done",+ slug: "done",+ name: "Done",+ icon: null,+ isFinal: true,+ position: 1,+ },+];++function routes(): Record<string, Reply> {+ return {+ "/api/workspace": ok([+ { id: "ws1", name: "Acme", slug: "acme" },+ { id: "ws2", name: "Locked", slug: "locked" },+ ]),+ "/api/project?workspaceId=ws1&includeArchived=true": ok([+ { id: "p1", name: "Website", archivedAt: null },+ { id: "p2", name: "Old site", archivedAt: "2026-01-01T00:00:00.000Z" },+ ]),+ "/api/project?workspaceId=ws2&includeArchived=true": fail(403, "Forbidden"),+ [boardPath("p1", 1)]: ok(+ boardResponse(+ {+ columns: [+ { ...columns[0], tasks: [t1, t2] },+ { ...columns[1], tasks: [] },+ ],+ },+ { total: 5, totalPages: 2, relatedTotalPages: 2 },+ ),+ ),+ [boardPath("p1", 1, 2)]: ok(+ boardResponse(+ {+ columns: [+ {+ ...columns[0],+ tasks: [+ { ...t1, labels: [ui] },+ { ...t2, externalLinks: [] },+ ],+ },+ ],+ },+ { total: 5, totalPages: 2, relatedTotalPages: 2 },+ ),+ ),+ [boardPath("p1", 2)]: ok(+ boardResponse(+ {+ columns: [+ { ...columns[0], tasks: [] },+ { ...columns[1], tasks: [t3] },+ ],+ plannedTasks: [t4],+ archivedTasks: [t5],+ },+ { total: 5, totalPages: 2, relatedTotalPages: 1 },+ ),+ ),+ "/api/workspace/ws1/members": ok([+ {+ id: "u1",+ name: "Ada",+ email: "[email protected]",+ image: null,+ role: "owner",+ },+ ]),+ "/api/custom-field/project/p1": ok([{ id: "cf1", name: "Estimate" }]),+ "/api/task/t2": ok({+ id: "t2",+ description: `Full text `,+ }),+ "/api/task-relation/t1": ok([+ {+ id: "r1",+ sourceTaskId: "t1",+ targetTaskId: "t3",+ relationType: "subtask",+ },+ {+ id: "r2",+ sourceTaskId: "t1",+ targetTaskId: "x9",+ relationType: "related",+ },+ ]),+ "/api/task-relation/t2": ok([]),+ "/api/task-relation/t3": ok([+ {+ id: "r1",+ sourceTaskId: "t1",+ targetTaskId: "t3",+ relationType: "subtask",+ },+ ]),+ "/api/task-relation/t4": ok([+ {+ id: "r3",+ sourceTaskId: "t4",+ targetTaskId: "t5",+ relationType: "blocks",+ },+ ]),+ "/api/task-relation/t5": ok([+ {+ id: "r3",+ sourceTaskId: "t4",+ targetTaskId: "t5",+ relationType: "blocks",+ },+ ]),+ "/api/activity/t1": ok([+ {+ id: "a3",+ type: "comment",+ userId: "u1",+ content: "Second",+ createdAt: "2026-01-03T00:00:00.000Z",+ externalUserName: "Ivy from Trello",+ },+ {+ id: "a2",+ type: "status_changed",+ userId: "u1",+ content: null,+ createdAt: "2026-01-02T00:00:00.000Z",+ externalUserName: null,+ },+ {+ id: "a1",+ type: "comment",+ userId: "u1",+ content: "First",+ createdAt: "2026-01-01T00:00:00.000Z",+ externalUserName: null,+ },+ ]),+ "/api/activity/t2": ok([+ {+ id: "a4",+ type: "comment",+ userId: "u7",+ content: "From a former member",+ createdAt: "2026-01-04T00:00:00.000Z",+ externalUserName: null,+ },+ ]),+ "/api/comment/t2": ok([{ id: "a4", user: { name: "Grace", image: null } }]),+ "/api/activity/t3": ok([]),+ "/api/activity/t4": ok([]),+ "/api/activity/t5": ok([]),+ };+}++describe("connectKaneo", () => {+ it("validates the key against the normalized API URL with a bearer header", async () => {+ const fake = fakeFetch(routes());+ await connectKaneo(+ { url: `${BASE}/api/`, apiKey: ` ${API_KEY} ` },+ { fetch: fake.fetch },+ );++ expect(fake.fetch).toHaveBeenCalledTimes(1);+ expect(fake.fetch.mock.calls[0]?.[0]).toBe(`${BASE}/api/workspace`);+ expect(fake.calls[0]?.headers.get("authorization")).toBe(+ `Bearer ${API_KEY}`,+ );+ });++ it("explains a rejected API key without echoing it", async () => {+ const fake = fakeFetch({ "/api/workspace": fail(401, "Unauthorized") });+ const error = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ ).catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toMatch(/rejected the API key/);+ expect((error as Error).message).not.toContain(API_KEY);+ });++ it("falls back to the organization list on older instances", async () => {+ const fake = fakeFetch({+ "/api/auth/organization/list": ok([{ id: "ws1", name: "Acme" }]),+ "/api/project?workspaceId=ws1&includeArchived=true": ok([+ { id: "p1", name: "Website" },+ ]),+ });+ const source = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ );++ expect(await source.listProjects()).toEqual([+ { id: "p1", name: "Website", detail: "Acme" },+ ]);+ });++ it("reports a URL that does not serve the Kaneo API", async () => {+ const fake = fakeFetch({+ "/api/workspace": ok("<!doctype html><html></html>"),+ });++ await expect(+ connectKaneo({ url: BASE, apiKey: API_KEY }, { fetch: fake.fetch }),+ ).rejects.toThrow(`No Kaneo API answered at ${BASE}`);+ });++ it("requires a URL and an API key", async () => {+ await expect(connectKaneo({ url: " ", apiKey: API_KEY })).rejects.toThrow(+ /URL/,+ );+ await expect(connectKaneo({ url: BASE, apiKey: "" })).rejects.toThrow(+ /API key/,+ );+ });+});++describe("listProjects", () => {+ it("lists projects of every readable workspace and flags archived ones", async () => {+ const fake = fakeFetch(routes());+ const source = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ );++ expect(await source.listProjects()).toEqual([+ { id: "p1", name: "Website", detail: "Acme" },+ { id: "p2", name: "Old site", detail: "Acme (archived)" },+ ]);+ });+});++describe("readProject", () => {+ it("reads the whole board with comments, relations and warnings", async () => {+ const fake = fakeFetch(routes());+ const source = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ );+ const progress: string[] = [];++ const project = await source.readProject("p1", {+ includeComments: true,+ onProgress: (message) => progress.push(message),+ });++ expect(project.name).toBe("Website");+ expect(project.key).toBe("WEB");+ expect(project.description).toBe("Project **readme**");+ expect(project.columns).toEqual([+ { key: "to-do", name: "To Do", isFinal: false },+ { key: "done", name: "Done", isFinal: true },+ ]);+ expect(project.labels).toEqual([+ { key: "Bug", name: "Bug", color: "#dc2626" },+ { key: "UI", name: "UI", color: "#8b5cf6" },+ ]);+ expect(+ project.tasks.map((task) => [+ task.key,+ task.columnKey,+ task.archived ?? false,+ ]),+ ).toEqual([+ ["t1", "to-do", false],+ ["t2", "to-do", false],+ ["t3", "done", false],+ ["t4", null, false],+ ["t5", null, true],+ ]);+ expect(project.tasks.map((task) => task.number)).toEqual([1, 2, 3, 4, 5]);++ const [first, second] = project.tasks;+ expect(first).toMatchObject({+ title: "Task t1",+ description: "Description of t1",+ priority: "medium",+ dueDate: "2026-03-01T00:00:00.000Z",+ createdAt: "2026-01-01T00:00:00.000Z",+ assignee: { name: "Ada", email: "[email protected]" },+ labelKeys: ["Bug", "UI"],+ comments: [+ {+ author: { name: "Ada", email: "[email protected]" },+ body: "First",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ {+ author: { name: "Ivy from Trello" },+ body: "Second",+ createdAt: "2026-01-03T00:00:00.000Z",+ },+ ],+ });+ expect(second).toMatchObject({+ priority: "urgent",+ description: `Full text `,+ assignee: { name: "Former Member" },+ comments: [{ author: { name: "Grace" }, body: "From a former member" }],+ });+ expect(second?.assignee?.email).toBeUndefined();++ expect(project.relations).toEqual([+ { sourceKey: "t1", targetKey: "t3", type: "subtask" },+ { sourceKey: "t4", targetKey: "t5", type: "blocks" },+ ]);++ expect(project.warnings).toEqual([+ "1 task has an assignee whose email address could not be found, so the assignee may not carry over.",+ "Custom fields are not copied: Estimate.",+ "1 task has integration links (such as GitHub issues) that are not copied.",+ "1 task references images or files stored on the source instance. They are not copied and may not display.",+ "1 task link points to tasks in other projects and is not copied.",+ ]);+ for (const warning of project.warnings)+ expect(warning).not.toContain(String.fromCharCode(0x2014));++ expect(progress).toEqual([+ "Reading tasks (2 of 5)",+ "Reading tasks (5 of 5)",+ "Reading comments and task links (5 of 5)",+ ]);+ expect(+ fake.paths().filter((path) => path.startsWith("/api/comment/")),+ ).toEqual(["/api/comment/t2"]);+ for (const call of fake.calls) {+ expect(call.path).not.toContain(API_KEY);+ expect(call.headers.get("authorization")).toBe(`Bearer ${API_KEY}`);+ }+ });++ it("skips comment requests when comments are not wanted", async () => {+ const fake = fakeFetch(routes());+ const source = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ );++ const project = await source.readProject("p1", { includeComments: false });++ expect(project.tasks.every((task) => task.comments.length === 0)).toBe(+ true,+ );+ expect(+ fake+ .paths()+ .some(+ (path) =>+ path.startsWith("/api/activity/") ||+ path.startsWith("/api/comment/"),+ ),+ ).toBe(false);+ });++ it("degrades gracefully on an older instance", async () => {+ const legacyBoard = {+ id: "p1",+ name: "Website",+ description: null,+ workspaceId: "ws1",+ columns: [+ { id: "to-do", name: "To Do", tasks: [boardTask("t1", "to-do")] },+ { id: "done", name: "Done", tasks: [boardTask("t3", "done")] },+ ],+ };+ const fake = fakeFetch({+ "/api/auth/organization/list": ok([{ id: "ws1", name: "Acme" }]),+ [boardPath("p1", 1)]: ok(legacyBoard),+ "/api/activity/t1": ok([]),+ "/api/activity/t3": ok([]),+ });+ const source = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ );++ const project = await source.readProject("p1", { includeComments: true });++ expect(project.columns).toEqual([+ { key: "to-do", name: "To Do", isFinal: false },+ { key: "done", name: "Done", isFinal: true },+ ]);+ expect(project.tasks.map((task) => task.key)).toEqual(["t1", "t3"]);+ expect(project.relations).toEqual([]);+ expect(project.warnings).toEqual([+ "Workspace members could not be read, so assignees and comment authors carry over by name only.",+ "This Kaneo version does not expose task links, so they are not copied.",+ ]);+ expect(+ fake.paths().filter((path) => path.startsWith("/api/task-relation/")),+ ).toHaveLength(1);+ });++ it("skips tasks deleted while reading", async () => {+ const fake = fakeFetch({+ ...routes(),+ "/api/task-relation/t3": fail(404, "Task not found"),+ "/api/activity/t3": fail(404, "Task not found"),+ });+ const source = await connectKaneo(+ { url: BASE, apiKey: API_KEY },+ { fetch: fake.fetch },+ );++ const project = await source.readProject("p1", { includeComments: true });++ expect(project.warnings).not.toContain(+ "This Kaneo version does not expose task links, so they are not copied.",+ );+ expect(fake.paths()).toContain("/api/task-relation/t4");+ expect(project.relations).toContainEqual({+ sourceKey: "t1",+ targetKey: "t3",+ type: "subtask",+ });+ });+});diff --git a/packages/importers/src/kaneo/source.ts b/packages/importers/src/kaneo/source.tsnew file mode 100644index 000000000..84820d915--- /dev/null+++ b/packages/importers/src/kaneo/source.ts@@ -0,0 +1,77 @@+import { SourceHttpError } from "../http.js";+import type { ConnectOptions, ImportSource, SourceProject } from "../types.js";+import {+ createKaneoClient,+ type KaneoClient,+ type KaneoWorkspace,+} from "./client.js";+import { readKaneoProject } from "./read-project.js";+import { normalizeKaneoUrl } from "./url.js";++export type KaneoCredentials = {+ url: string;+ apiKey: string;+};++export async function connectKaneo(+ credentials: KaneoCredentials,+ options: ConnectOptions = {},+): Promise<ImportSource> {+ if (!credentials.url?.trim()) {+ throw new Error("Enter the URL of the Kaneo instance to import from.");+ }+ const apiKey = credentials.apiKey?.trim();+ if (!apiKey) {+ throw new Error("Enter an API key from the Kaneo instance to import from.");+ }++ const baseUrl = normalizeKaneoUrl(credentials.url);+ const clientFor = (signal?: AbortSignal) =>+ createKaneoClient({ baseUrl, apiKey, fetch: options.fetch, signal });++ const workspaces = await clientFor(options.signal).listWorkspaces();++ return {+ listProjects() {+ return listKaneoProjects(clientFor(options.signal), workspaces);+ },+ readProject(projectId, readOptions) {+ return readKaneoProject(+ clientFor(readOptions.signal ?? options.signal),+ projectId,+ readOptions,+ );+ },+ };+}++export async function listKaneoProjects(+ client: KaneoClient,+ workspaces: KaneoWorkspace[],+): Promise<SourceProject[]> {+ const projects: SourceProject[] = [];+ for (const workspace of workspaces) {+ let found;+ try {+ found = await client.listProjects(workspace.id);+ } catch (error) {+ if (+ error instanceof SourceHttpError &&+ (error.status === 403 || error.status === 404)+ ) {+ continue;+ }+ throw error;+ }+ for (const project of found) {+ projects.push({+ id: project.id,+ name: project.name,+ detail: project.archivedAt+ ? `${workspace.name} (archived)`+ : workspace.name,+ });+ }+ }+ return projects;+}diff --git a/packages/importers/src/kaneo/url.test.ts b/packages/importers/src/kaneo/url.test.tsnew file mode 100644index 000000000..1daa1977c--- /dev/null+++ b/packages/importers/src/kaneo/url.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vite-plus/test";+import { normalizeKaneoUrl } from "./url.js";++describe("normalizeKaneoUrl", () => {+ it("keeps a plain instance URL", () => {+ expect(normalizeKaneoUrl("https://cloud.kaneo.app")).toBe(+ "https://cloud.kaneo.app",+ );+ });++ it("strips a trailing /api and slashes", () => {+ expect(normalizeKaneoUrl("https://cloud.kaneo.app/api/")).toBe(+ "https://cloud.kaneo.app",+ );+ expect(normalizeKaneoUrl("https://example.com/kaneo/api")).toBe(+ "https://example.com/kaneo",+ );+ });++ it("adds https when the protocol is missing", () => {+ expect(normalizeKaneoUrl("kaneo.example.com/api")).toBe(+ "https://kaneo.example.com",+ );+ });++ it("drops web app routes pasted from the address bar", () => {+ expect(+ normalizeKaneoUrl(+ "https://cloud.kaneo.app/dashboard/workspace/ws1/project/p1/board",+ ),+ ).toBe("https://cloud.kaneo.app");+ expect(normalizeKaneoUrl("http://localhost:5173/auth/sign-in")).toBe(+ "http://localhost:5173",+ );+ });+});diff --git a/packages/importers/src/kaneo/url.ts b/packages/importers/src/kaneo/url.tsnew file mode 100644index 000000000..dabe19f3a--- /dev/null+++ b/packages/importers/src/kaneo/url.ts@@ -0,0 +1,17 @@+import { normalizeBaseUrl } from "../http.js";++const WEB_APP_ROUTE = /\/(?:dashboard|auth)(?:\/.*)?$/;++export function normalizeKaneoUrl(raw: string): string {+ const base = normalizeBaseUrl(raw);+ try {+ const url = new URL(base);+ const path = url.pathname+ .replace(WEB_APP_ROUTE, "")+ .replace(/\/+$/, "")+ .replace(/\/api$/, "");+ return `${url.protocol}//${url.host}${path}`;+ } catch {+ return base.replace(/\/api$/, "");+ }+}diff --git a/packages/importers/src/kaneo/warnings.ts b/packages/importers/src/kaneo/warnings.tsnew file mode 100644index 000000000..728add630--- /dev/null+++ b/packages/importers/src/kaneo/warnings.ts@@ -0,0 +1,77 @@+import type { ImportedTask } from "../types.js";+import type { KaneoBoardTask, KaneoMember } from "./client.js";++export type WarningFacts = {+ tasks: KaneoBoardTask[];+ imported: ImportedTask[];+ members: Map<string, KaneoMember>;+ customFieldNames: string[];+ relationsOutsideProject: number;+};++const ASSET_REFERENCE = /\/api\/asset\/[\w-]+/;++export const MEMBERS_UNAVAILABLE_WARNING =+ "Workspace members could not be read, so assignees and comment authors carry over by name only.";+export const RELATIONS_UNAVAILABLE_WARNING =+ "This Kaneo version does not expose task links, so they are not copied.";+export const COMMENTS_UNAVAILABLE_WARNING =+ "This Kaneo version does not expose comments, so they are not copied.";++export function buildWarnings(facts: WarningFacts): string[] {+ const warnings: string[] = [];++ const unresolved = facts.tasks.filter(+ (task) => task.userId && !facts.members.get(task.userId)?.email?.trim(),+ ).length;+ if (unresolved > 0) {+ warnings.push(+ `${tasksHave(unresolved)} an assignee whose email address could not be found, so the assignee may not carry over.`,+ );+ }++ if (facts.customFieldNames.length > 0) {+ warnings.push(+ `Custom fields are not copied: ${facts.customFieldNames.join(", ")}.`,+ );+ }++ const withLinks = facts.tasks.filter(+ (task) => (task.externalLinks ?? []).length > 0,+ ).length;+ if (withLinks > 0) {+ warnings.push(+ `${tasksHave(withLinks)} integration links (such as GitHub issues) that are not copied.`,+ );+ }++ const withAssets = facts.imported.filter(referencesAssets).length;+ if (withAssets > 0) {+ warnings.push(+ `${count(withAssets, "task")} ${withAssets === 1 ? "references" : "reference"} images or files stored on the source instance. They are not copied and may not display.`,+ );+ }++ if (facts.relationsOutsideProject > 0) {+ warnings.push(+ `${count(facts.relationsOutsideProject, "task link")} ${facts.relationsOutsideProject === 1 ? "points" : "point"} to tasks in other projects and ${facts.relationsOutsideProject === 1 ? "is" : "are"} not copied.`,+ );+ }++ return warnings;+}++function referencesAssets(task: ImportedTask): boolean {+ return (+ ASSET_REFERENCE.test(task.description) ||+ task.comments.some((comment) => ASSET_REFERENCE.test(comment.body))+ );+}++function tasksHave(n: number): string {+ return `${count(n, "task")} ${n === 1 ? "has" : "have"}`;+}++function count(n: number, noun: string): string {+ return `${n} ${noun}${n === 1 ? "" : "s"}`;+}diff --git a/packages/importers/src/keys.test.ts b/packages/importers/src/keys.test.tsnew file mode 100644index 000000000..b7ba87312--- /dev/null+++ b/packages/importers/src/keys.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vite-plus/test";+import {+ sanitizeProjectKey,+ toColumnSlug,+ toProjectKey,+ uniqueKey,+} from "./keys.js";++describe("toColumnSlug", () => {+ it("lowercases and hyphenates", () => {+ expect(toColumnSlug("In Progress")).toBe("in-progress");+ expect(toColumnSlug("To Do")).toBe("to-do");+ });++ it("strips punctuation and edge hyphens", () => {+ expect(toColumnSlug(" Ready?! for review ")).toBe("ready-for-review");+ expect(toColumnSlug("--Done--")).toBe("done");+ });++ it("keeps non-latin letters", () => {+ expect(toColumnSlug("Готово")).toBe("готово");+ });++ it("returns empty for names with no alphanumerics", () => {+ expect(toColumnSlug("???")).toBe("");+ expect(toColumnSlug(" ")).toBe("");+ });+});++describe("toProjectKey", () => {+ it("uses initials for multi-word names", () => {+ expect(toProjectKey("Marketing Website Redesign")).toBe("MWR");+ });++ it("uses a prefix for single-word names", () => {+ expect(toProjectKey("Engineering")).toBe("ENGINEER");+ });++ it("caps at 8 characters", () => {+ expect(toProjectKey("a b c d e f g h i j k").length).toBeLessThanOrEqual(8);+ });++ it("falls back when the name has nothing usable", () => {+ expect(toProjectKey("???")).toBe("PROJ");+ expect(toProjectKey("")).toBe("PROJ");+ });+});++describe("sanitizeProjectKey", () => {+ it("keeps a clean source key", () => {+ expect(sanitizeProjectKey("WEB")).toBe("WEB");+ expect(sanitizeProjectKey("ENG2")).toBe("ENG2");+ });++ it("uppercases and drops anything but letters and digits", () => {+ expect(sanitizeProjectKey(" web-app_1 ")).toBe("WEBAPP1");+ expect(sanitizeProjectKey("ops.team")).toBe("OPSTEAM");+ });++ it("normalizes compatibility characters", () => {+ expect(sanitizeProjectKey("WEB")).toBe("WEB");+ expect(sanitizeProjectKey("web")).toBe("WEB");+ });++ it("keeps non-latin letters", () => {+ expect(sanitizeProjectKey("гот")).toBe("ГОТ");+ });++ it("caps at 16 code points without splitting one", () => {+ expect(sanitizeProjectKey("ABCDEFGHIJKLMNOPQRS")).toBe("ABCDEFGHIJKLMNOP");+ const astral = "𠀀".repeat(20);+ expect(Array.from(sanitizeProjectKey(astral) ?? "")).toEqual(+ Array.from("𠀀".repeat(16)),+ );+ });++ it("returns null when nothing usable is left", () => {+ expect(sanitizeProjectKey("")).toBeNull();+ expect(sanitizeProjectKey(" -_. ")).toBeNull();+ expect(sanitizeProjectKey(null)).toBeNull();+ expect(sanitizeProjectKey(undefined)).toBeNull();+ });+});++describe("uniqueKey", () => {+ it("returns the candidate when free", () => {+ expect(uniqueKey("ENG", new Set())).toBe("ENG");+ });++ it("suffixes on collision", () => {+ expect(uniqueKey("ENG", new Set(["ENG"]))).toBe("ENG-2");+ expect(uniqueKey("ENG", new Set(["ENG", "ENG-2"]))).toBe("ENG-3");+ });++ it("stays within the length cap when suffixing", () => {+ const result = uniqueKey("ENGINEER", new Set(["ENGINEER"]));+ expect(result.length).toBeLessThanOrEqual(8);+ expect(result).toBe("ENGINE-2");+ });++ it("keeps longer keys when given a larger cap", () => {+ expect(uniqueKey("MARKETING", new Set(["MARKETING"]), 16)).toBe(+ "MARKETING-2",+ );+ });++ it("does not split a code point when suffixing", () => {+ const candidate = "𠀀".repeat(8);+ expect(Array.from(uniqueKey(candidate, new Set([candidate])))).toEqual(+ Array.from(`${"𠀀".repeat(6)}-2`),+ );+ });+});++describe("toProjectKey with characters outside the basic plane", () => {+ it("keeps whole code points when taking initials", () => {+ expect(toProjectKey("𠀀abc 𠀁def")).toBe("𠀀𠀁");+ });++ it("does not split a code point when truncating", () => {+ expect(Array.from(toProjectKey("𠀀𠀁𠀂𠀃𠀄𠀅𠀆𠀇𠀈"))).toEqual(+ Array.from("𠀀𠀁𠀂𠀃𠀄𠀅𠀆𠀇"),+ );+ });+});diff --git a/packages/planka-import/src/keys.ts b/packages/importers/src/keys.tssimilarity index 66%rename from packages/planka-import/src/keys.tsrename to packages/importers/src/keys.tsindex d75de98ac..7e65222ca 100644--- a/packages/planka-import/src/keys.ts+++ b/packages/importers/src/keys.ts@@ -16,6 +16,7 @@ export function toColumnSlug(name: string): string {export const RESERVED_COLUMN_SLUGS = ["planned", "archived"];const PROJECT_KEY_MAX = 8;+export const SOURCE_PROJECT_KEY_MAX = 16;export function toProjectKey(name: string): string {const words = name@@ -29,13 +30,26 @@ export function toProjectKey(name: string): string {const key =words.length > 1- ? words.map((word) => word[0]).join("")+ ? words.map((word) => Array.from(word)[0]).join(""): (words[0] as string);- const normalized = key.toUpperCase().slice(0, PROJECT_KEY_MAX);+ const normalized = Array.from(key.toUpperCase())+ .slice(0, PROJECT_KEY_MAX)+ .join("");return normalized.length > 0 ? normalized : "PROJ";}+export function sanitizeProjectKey(+ raw: string | null | undefined,+): string | null {+ if (!raw) return null;+ const key = Array.from(raw.normalize("NFKC").toUpperCase())+ .filter((char) => /^[\p{L}\p{N}]$/u.test(char))+ .slice(0, SOURCE_PROJECT_KEY_MAX)+ .join("");+ return key.length > 0 ? key : null;+}+export function uniqueKey(candidate: string,taken: Set<string>,@@ -43,9 +57,12 @@ export function uniqueKey(): string {if (!taken.has(candidate)) return candidate;+ const chars = Array.from(candidate);for (let suffix = 2; ; suffix++) {const tail = String(suffix);- const head = candidate.slice(0, Math.max(1, maxLength - tail.length - 1));+ const head = chars+ .slice(0, Math.max(1, maxLength - tail.length - 1))+ .join("");const next = `${head}-${tail}`;if (!taken.has(next)) return next;}diff --git a/packages/importers/src/linear/client.ts b/packages/importers/src/linear/client.tsnew file mode 100644index 000000000..8ef4f0f6b--- /dev/null+++ b/packages/importers/src/linear/client.ts@@ -0,0 +1,176 @@+import type { FetchLike } from "../types.js";+import { createLinearGraphQL, type LinearGraphQL } from "./graphql.js";+import {+ COMMENTS_QUERY,+ ISSUES_QUERY,+ TEAM_QUERY,+ TEAMS_QUERY,+ VIEWER_QUERY,+} from "./queries.js";++export type LinearPageInfo = {+ hasNextPage: boolean;+ endCursor: string | null;+};++export type LinearConnection<T> = {+ nodes: T[];+ pageInfo: LinearPageInfo;+};++export type LinearViewer = {+ id: string;+ name: string | null;+ email: string | null;+};++export type LinearTeamSummary = {+ id: string;+ key: string;+ name: string;+ issueCount: number | null;+};++export type LinearWorkflowState = {+ id: string;+ name: string;+ type: string;+ position: number;+ color: string | null;+};++export type LinearTeam = {+ id: string;+ key: string;+ name: string;+ description: string | null;+ states: { nodes: LinearWorkflowState[] };+};++export type LinearUser = {+ name: string | null;+ email: string | null;+};++export type LinearLabel = {+ id: string;+ name: string;+ color: string | null;+ parent: { name: string } | null;+};++export type LinearRelation = {+ type: string;+ relatedIssue: { id: string } | null;+};++export type LinearIssue = {+ id: string;+ number: number;+ title: string;+ description: string | null;+ priority: number | null;+ dueDate: string | null;+ sortOrder: number | null;+ createdAt: string | null;+ state: { id: string } | null;+ assignee: LinearUser | null;+ parent: { id: string } | null;+ labels: { nodes: LinearLabel[]; pageInfo: { hasNextPage: boolean } };+ relations: { nodes: LinearRelation[]; pageInfo: { hasNextPage: boolean } };+};++export type LinearComment = {+ body: string | null;+ createdAt: string | null;+ user: LinearUser | null;+ botActor: { name: string | null } | null;+ issue: { id: string } | null;+};++export type LinearClientOptions = {+ apiKey: string;+ fetch?: FetchLike;+ signal?: AbortSignal;+};++export class LinearClient {+ private readonly options: LinearClientOptions;+ private readonly graphql: LinearGraphQL;++ constructor(options: LinearClientOptions) {+ this.options = options;+ this.graphql = createLinearGraphQL(options);+ }++ withSignal(signal: AbortSignal | undefined): LinearClient {+ if (!signal) return this;+ const current = this.options.signal;+ return new LinearClient({+ ...this.options,+ signal: current ? AbortSignal.any([current, signal]) : signal,+ });+ }++ async viewer(): Promise<LinearViewer> {+ const data = await this.graphql<{ viewer: LinearViewer }>(VIEWER_QUERY);+ return data.viewer;+ }++ listTeams(): Promise<LinearTeamSummary[]> {+ return this.collect<+ { teams: LinearConnection<LinearTeamSummary> },+ LinearTeamSummary+ >(TEAMS_QUERY, {}, (data) => data.teams);+ }++ async getTeam(teamId: string): Promise<LinearTeam> {+ const data = await this.graphql<{ team: LinearTeam }>(TEAM_QUERY, {+ teamId,+ });+ return data.team;+ }++ listIssues(+ teamId: string,+ onPage?: (count: number) => void,+ ): Promise<LinearIssue[]> {+ return this.collect<{ issues: LinearConnection<LinearIssue> }, LinearIssue>(+ ISSUES_QUERY,+ { teamId },+ (data) => data.issues,+ onPage,+ );+ }++ listComments(+ teamId: string,+ onPage?: (count: number) => void,+ ): Promise<LinearComment[]> {+ return this.collect<+ { comments: LinearConnection<LinearComment> },+ LinearComment+ >(COMMENTS_QUERY, { teamId }, (data) => data.comments, onPage);+ }++ private async collect<Data, Node>(+ query: string,+ variables: Record<string, unknown>,+ select: (data: Data) => LinearConnection<Node>,+ onPage?: (count: number) => void,+ ): Promise<Node[]> {+ const nodes: Node[] = [];+ let after: string | null = null;+ do {+ const connection = select(+ await this.graphql<Data>(query, { ...variables, after }),+ );+ nodes.push(...connection.nodes);+ onPage?.(nodes.length);+ after = connection.pageInfo.hasNextPage+ ? connection.pageInfo.endCursor+ : null;+ } while (after);+ return nodes;+ }+}diff --git a/packages/importers/src/linear/columns.ts b/packages/importers/src/linear/columns.tsnew file mode 100644index 000000000..66f088977--- /dev/null+++ b/packages/importers/src/linear/columns.ts@@ -0,0 +1,51 @@+import type { ImportedColumn } from "../types.js";+import type { LinearWorkflowState } from "./client.js";++const STATE_TYPE_ORDER = [+ "triage",+ "backlog",+ "unstarted",+ "started",+ "completed",+ "canceled",+ "duplicate",+];++const FINAL_STATE_TYPES = new Set(["completed", "canceled", "duplicate"]);++const BACKLOG_STATE_TYPES = new Set(["triage", "backlog"]);++const HIDDEN_WHEN_EMPTY = new Set(["duplicate"]);++export function orderStates(+ states: LinearWorkflowState[],+): LinearWorkflowState[] {+ return [...states].sort(+ (a, b) =>+ typeRank(a.type) - typeRank(b.type) ||+ a.position - b.position ||+ a.name.localeCompare(b.name),+ );+}++export function mapColumns(+ states: LinearWorkflowState[],+ usedStateIds: ReadonlySet<string>,+): ImportedColumn[] {+ return orderStates(states)+ .filter((state) => !BACKLOG_STATE_TYPES.has(state.type))+ .filter(+ (state) =>+ !HIDDEN_WHEN_EMPTY.has(state.type) || usedStateIds.has(state.id),+ )+ .map((state) => ({+ key: state.id,+ name: state.name,+ isFinal: FINAL_STATE_TYPES.has(state.type),+ }));+}++function typeRank(type: string): number {+ const index = STATE_TYPE_ORDER.indexOf(type);+ return index === -1 ? STATE_TYPE_ORDER.length : index;+}diff --git a/packages/importers/src/linear/comments.ts b/packages/importers/src/linear/comments.tsnew file mode 100644index 000000000..43f411e2a--- /dev/null+++ b/packages/importers/src/linear/comments.ts@@ -0,0 +1,42 @@+import { toIsoDate } from "../markdown.js";+import type { ImportedComment, ImportedPerson } from "../types.js";+import type { LinearComment } from "./client.js";+import { toPerson } from "./people.js";++const FALLBACK_AUTHOR = "Linear";++export function commentAuthor(comment: LinearComment): ImportedPerson {+ const user = toPerson(comment.user);+ if (user?.name) return user;+ const name = comment.botActor?.name?.trim() || FALLBACK_AUTHOR;+ return { ...user, name };+}++export function groupComments(+ comments: LinearComment[],+): Map<string, ImportedComment[]> {+ const byIssue = new Map<string, ImportedComment[]>();+ const ordered = [...comments].sort(+ (a, b) => timestamp(a.createdAt) - timestamp(b.createdAt),+ );++ for (const comment of ordered) {+ const issueId = comment.issue?.id;+ if (!issueId) continue;+ const createdAt = toIsoDate(comment.createdAt);+ const list = byIssue.get(issueId) ?? [];+ list.push({+ author: commentAuthor(comment),+ body: comment.body ?? "",+ ...(createdAt ? { createdAt } : {}),+ });+ byIssue.set(issueId, list);+ }++ return byIssue;+}++function timestamp(value: string | null): number {+ const parsed = value ? Date.parse(value) : Number.NaN;+ return Number.isNaN(parsed) ? 0 : parsed;+}diff --git a/packages/importers/src/linear/graphql.test.ts b/packages/importers/src/linear/graphql.test.tsnew file mode 100644index 000000000..f61cb39fa--- /dev/null+++ b/packages/importers/src/linear/graphql.test.ts@@ -0,0 +1,172 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import {+ createLinearGraphQL,+ INVALID_API_KEY_MESSAGE,+ RATE_LIMITED_MESSAGE,+} from "./graphql.js";++const API_KEY = "lin_api_secret";++type Reply = {+ status?: number;+ body: unknown;+ headers?: Record<string, string>;+};++function scripted(...replies: Reply[]) {+ const requests: Array<{ url: string; init: RequestInit | undefined }> = [];+ const fetch: FetchLike = async (url, init) => {+ requests.push({ url, init });+ const reply = replies[Math.min(requests.length, replies.length) - 1];+ if (!reply) throw new Error("no reply scripted");+ return new Response(JSON.stringify(reply.body), {+ status: reply.status ?? 200,+ headers: { "Content-Type": "application/json", ...reply.headers },+ });+ };+ return { fetch, requests };+}++const RATE_LIMITED = {+ errors: [+ {+ message: "Rate limit exceeded",+ extensions: { code: "RATELIMITED" },+ },+ ],+};++afterEach(() => {+ vi.useRealTimers();+});++describe("createLinearGraphQL", () => {+ it("posts the query with the raw API key, never as a bearer", async () => {+ const { fetch, requests } = scripted({+ body: { data: { viewer: { id: "u1" } } },+ });+ const graphql = createLinearGraphQL({ apiKey: API_KEY, fetch });++ const data = await graphql<{ viewer: { id: string } }>(+ "query Q { viewer { id } }",+ {+ a: 1,+ },+ );++ expect(data.viewer.id).toBe("u1");+ expect(requests[0]?.url).toBe("https://api.linear.app/graphql");+ expect(requests[0]?.init?.method).toBe("POST");+ const headers = new Headers(requests[0]?.init?.headers);+ expect(headers.get("authorization")).toBe(API_KEY);+ expect(headers.get("content-type")).toBe("application/json");+ expect(JSON.parse(String(requests[0]?.init?.body))).toEqual({+ query: "query Q { viewer { id } }",+ variables: { a: 1 },+ });+ });++ it("surfaces the first GraphQL error message", async () => {+ const { fetch } = scripted({+ body: {+ data: null,+ errors: [{ message: "Field 'nope' is not defined" }],+ },+ });+ await expect(+ createLinearGraphQL({ apiKey: API_KEY, fetch })("query Q { nope }"),+ ).rejects.toThrow("Linear: Field 'nope' is not defined");++ const bad = scripted({+ status: 400,+ body: {+ errors: [+ {+ message: "Variable $teamId is invalid",+ extensions: { code: "INVALID_INPUT" },+ },+ ],+ },+ });+ await expect(+ createLinearGraphQL({ apiKey: API_KEY, fetch: bad.fetch })(+ "query Q { x }",+ ),+ ).rejects.toThrow("Linear: Variable $teamId is invalid");+ });++ it("explains a rejected API key without leaking it", async () => {+ const graphqlAuth = scripted({+ status: 400,+ body: {+ errors: [+ {+ message: "Authentication required, not authenticated",+ extensions: {+ code: "AUTHENTICATION_ERROR",+ type: "authentication error",+ },+ },+ ],+ },+ });+ const httpAuth = scripted({+ status: 401,+ body: { message: "Unauthorized" },+ });++ for (const { fetch } of [graphqlAuth, httpAuth]) {+ const error = await createLinearGraphQL({ apiKey: API_KEY, fetch })(+ "query Q { viewer { id } }",+ ).catch((caught: unknown) => caught as Error);+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe(INVALID_API_KEY_MESSAGE);+ expect((error as Error).message).not.toContain(API_KEY);+ }+ });++ it("waits for the rate limit reset header and retries RATELIMITED responses", async () => {+ vi.useFakeTimers();+ const reset = Date.now() + 5_000;+ const { fetch, requests } = scripted(+ {+ status: 400,+ body: RATE_LIMITED,+ headers: {+ "X-RateLimit-Requests-Reset": String(reset),+ "X-RateLimit-Complexity-Reset": String(Date.now() + 1_000),+ },+ },+ { body: { data: { ok: true } } },+ );++ const pending = createLinearGraphQL({ apiKey: API_KEY, fetch })<{+ ok: boolean;+ }>("query Q { ok }");++ await vi.advanceTimersByTimeAsync(4_900);+ expect(requests).toHaveLength(1);++ await vi.advanceTimersByTimeAsync(200);+ expect(requests).toHaveLength(2);+ await expect(pending).resolves.toEqual({ ok: true });+ });++ it("backs off without headers and gives up with a clear message", async () => {+ vi.useFakeTimers();+ const { fetch, requests } = scripted({ status: 400, body: RATE_LIMITED });++ const pending = createLinearGraphQL({ apiKey: API_KEY, fetch })(+ "query Q { ok }",+ ).catch((caught: unknown) => caught as Error);++ await vi.advanceTimersByTimeAsync(999);+ expect(requests).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(60_000);++ const error = await pending;+ expect(requests).toHaveLength(6);+ expect((error as Error).message).toBe(RATE_LIMITED_MESSAGE);+ });+});diff --git a/packages/importers/src/linear/graphql.ts b/packages/importers/src/linear/graphql.tsnew file mode 100644index 000000000..f31fbc69c--- /dev/null+++ b/packages/importers/src/linear/graphql.ts@@ -0,0 +1,163 @@+import { createJsonClient, SourceHttpError } from "../http.js";+import type { FetchLike } from "../types.js";++export const LINEAR_API_URL = "https://api.linear.app";++export const INVALID_API_KEY_MESSAGE =+ "Linear rejected the API key. Create a personal API key under Settings > Account > Security & access and try again.";++export const RATE_LIMITED_MESSAGE =+ "Linear rate limit reached. Wait a few minutes and try the import again.";++const RATE_LIMIT_RESET_HEADERS = [+ "x-ratelimit-requests-reset",+ "x-ratelimit-complexity-reset",+];++export type LinearGraphQLError = {+ message?: string;+ extensions?: { code?: string; type?: string; statusCode?: number };+};++type GraphQLResponse<T> = {+ data?: T | null;+ errors?: LinearGraphQLError[];+};++export class LinearApiError extends Error {+ constructor(+ message: string,+ readonly code: string | undefined,+ ) {+ super(message);+ this.name = "LinearApiError";+ }+}++export type LinearGraphQL = <T>(+ query: string,+ variables?: Record<string, unknown>,+) => Promise<T>;++export type LinearGraphQLOptions = {+ apiKey: string;+ fetch?: FetchLike;+ signal?: AbortSignal;+};++export function createLinearGraphQL(+ options: LinearGraphQLOptions,+): LinearGraphQL {+ const baseFetch: FetchLike =+ options.fetch ?? ((input, init) => fetch(input, init));+ const http = createJsonClient({+ service: "Linear",+ baseUrl: LINEAR_API_URL,+ headers: () => ({ Authorization: options.apiKey }),+ fetch: retryRateLimitedResponses(baseFetch),+ signal: options.signal,+ describeUnauthorized: INVALID_API_KEY_MESSAGE,+ });++ return async <T>(+ query: string,+ variables: Record<string, unknown> = {},+ ): Promise<T> => {+ let response: GraphQLResponse<T> | null;+ try {+ response = await http.request<GraphQLResponse<T> | null>("/graphql", {+ method: "POST",+ body: JSON.stringify({ query, variables }),+ });+ } catch (error) {+ if (error instanceof SourceHttpError) throw fromHttpError(error);+ throw error;+ }++ const failure = firstError(response);+ if (failure) throw fromGraphQLError(failure);+ if (!response?.data) {+ throw new LinearApiError("Linear returned an empty response.", undefined);+ }+ return response.data;+ };+}++export function retryRateLimitedResponses(fetchImpl: FetchLike): FetchLike {+ return async (input, init) => {+ const res = await fetchImpl(input, init);+ if (res.status < 400 || res.status === 429) return res;++ const text = await res.text();+ const failure = firstError(parseJson(text));+ if (failure?.extensions?.code !== "RATELIMITED") {+ return new Response(text, {+ status: res.status,+ statusText: res.statusText,+ headers: res.headers,+ });+ }+ return new Response(text, {+ status: 429,+ headers: rateLimitHeaders(res.headers),+ });+ };+}++function rateLimitHeaders(source: Headers): Headers {+ const headers = new Headers({ "Content-Type": "application/json" });+ const retryAfter = source.get("retry-after");+ if (retryAfter) headers.set("Retry-After", retryAfter);++ const resets = RATE_LIMIT_RESET_HEADERS.map((name) => source.get(name))+ .filter((value): value is string => value !== null)+ .map(Number)+ .filter((value) => Number.isFinite(value) && value > 0);+ if (resets.length > 0) {+ headers.set("X-RateLimit-Reset", String(Math.max(...resets)));+ }+ return headers;+}++function fromHttpError(error: SourceHttpError): Error {+ if (error.status === 401) {+ return new LinearApiError(INVALID_API_KEY_MESSAGE, "AUTHENTICATION_ERROR");+ }+ const failure = firstError(error.body);+ return failure ? fromGraphQLError(failure) : error;+}++function fromGraphQLError(error: LinearGraphQLError): LinearApiError {+ const code = error.extensions?.code;+ if (+ code === "AUTHENTICATION_ERROR" ||+ error.extensions?.type === "authentication error"+ ) {+ return new LinearApiError(INVALID_API_KEY_MESSAGE, code);+ }+ if (code === "RATELIMITED") {+ return new LinearApiError(RATE_LIMITED_MESSAGE, code);+ }+ return new LinearApiError(+ `Linear: ${error.message?.trim() || "the request failed"}`,+ code,+ );+}++function firstError(body: unknown): LinearGraphQLError | undefined {+ if (typeof body !== "object" || body === null) return undefined;+ const errors = (body as { errors?: unknown }).errors;+ if (!Array.isArray(errors) || errors.length === 0) return undefined;+ const first: unknown = errors[0];+ return typeof first === "object" && first !== null+ ? (first as LinearGraphQLError)+ : {};+}++function parseJson(text: string): unknown {+ try {+ return JSON.parse(text) as unknown;+ } catch {+ return null;+ }+}diff --git a/packages/importers/src/linear/index.ts b/packages/importers/src/linear/index.tsnew file mode 100644index 000000000..19150f691--- /dev/null+++ b/packages/importers/src/linear/index.ts@@ -0,0 +1,34 @@+export {+ type LinearClientOptions,+ LinearClient,+ type LinearComment,+ type LinearConnection,+ type LinearIssue,+ type LinearLabel,+ type LinearPageInfo,+ type LinearRelation,+ type LinearTeam,+ type LinearTeamSummary,+ type LinearUser,+ type LinearViewer,+ type LinearWorkflowState,+} from "./client.js";+export { mapColumns, orderStates } from "./columns.js";+export { commentAuthor, groupComments } from "./comments.js";+export {+ createLinearGraphQL,+ INVALID_API_KEY_MESSAGE,+ LINEAR_API_URL,+ LinearApiError,+ RATE_LIMITED_MESSAGE,+} from "./graphql.js";+export { FALLBACK_COLOR, mapLabels, toHexColor } from "./labels.js";+export {+ buildWarnings,+ mapIssue,+ mapPriority,+ mapTeam,+ sortIssues,+} from "./mapping.js";+export { mapRelations } from "./relations.js";+export { connectLinear, type LinearCredentials } from "./source.js";diff --git a/packages/importers/src/linear/labels.ts b/packages/importers/src/linear/labels.tsnew file mode 100644index 000000000..6ae1c32c5--- /dev/null+++ b/packages/importers/src/linear/labels.ts@@ -0,0 +1,49 @@+import type { ImportedLabel } from "../types.js";+import type { LinearIssue, LinearLabel } from "./client.js";++export const FALLBACK_COLOR = "#6b7280";++export function toHexColor(color: string | null | undefined): string {+ const value = color?.trim().toLowerCase() ?? "";+ if (/^#[0-9a-f]{6}$/.test(value)) return value;+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(value);+ if (!short) return FALLBACK_COLOR;+ const [, red, green, blue] = short;+ return `#${red}${red}${green}${green}${blue}${blue}`;+}++export function mapLabels(issues: LinearIssue[]): ImportedLabel[] {+ const used = new Map<string, LinearLabel>();+ for (const issue of issues) {+ for (const label of issue.labels.nodes) {+ if (!used.has(label.id)) used.set(label.id, label);+ }+ }++ const nameCounts = new Map<string, number>();+ for (const label of used.values()) {+ const name = comparableName(label.name);+ nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);+ }++ return [...used.values()]+ .map((label) => ({+ key: label.id,+ name: labelName(+ label,+ (nameCounts.get(comparableName(label.name)) ?? 0) > 1,+ ),+ color: toHexColor(label.color),+ }))+ .sort((a, b) => a.name.localeCompare(b.name));+}++function labelName(label: LinearLabel, ambiguous: boolean): string {+ const name = label.name.trim();+ const parent = label.parent?.name.trim();+ return ambiguous && parent ? `${parent}: ${name}` : name;+}++function comparableName(name: string): string {+ return name.trim().toLowerCase();+}diff --git a/packages/importers/src/linear/mapping.test.ts b/packages/importers/src/linear/mapping.test.tsnew file mode 100644index 000000000..3bc4204f8--- /dev/null+++ b/packages/importers/src/linear/mapping.test.ts@@ -0,0 +1,355 @@+import { describe, expect, it } from "vite-plus/test";+import type {+ LinearComment,+ LinearIssue,+ LinearLabel,+ LinearTeam,+ LinearWorkflowState,+} from "./client.js";+import { mapColumns } from "./columns.js";+import { groupComments } from "./comments.js";+import { mapLabels, toHexColor } from "./labels.js";+import {+ buildWarnings,+ mapIssue,+ mapPriority,+ mapTeam,+ sortIssues,+} from "./mapping.js";+import { mapRelations } from "./relations.js";++function issue(id: string, overrides: Partial<LinearIssue> = {}): LinearIssue {+ return {+ id,+ number: 1,+ title: `Issue ${id}`,+ description: null,+ priority: 0,+ dueDate: null,+ sortOrder: 0,+ createdAt: null,+ state: { id: "todo" },+ assignee: null,+ parent: null,+ labels: { nodes: [], pageInfo: { hasNextPage: false } },+ relations: { nodes: [], pageInfo: { hasNextPage: false } },+ ...overrides,+ };+}++function withLabels(...nodes: LinearLabel[]): LinearIssue["labels"] {+ return { nodes, pageInfo: { hasNextPage: false } };+}++function withRelations(+ ...nodes: Array<[string, string]>+): LinearIssue["relations"] {+ return {+ nodes: nodes.map(([type, id]) => ({ type, relatedIssue: { id } })),+ pageInfo: { hasNextPage: false },+ };+}++function state(+ id: string,+ type: string,+ position: number,+): LinearWorkflowState {+ return { id, name: id, type, position, color: "#000000" };+}++const STATES = [+ state("done", "completed", 0),+ state("canceled", "canceled", 0),+ state("in-review", "started", 2),+ state("todo", "unstarted", 0),+ state("in-progress", "started", 1),+ state("backlog", "backlog", 0),+ state("triage", "triage", 0),+ state("duplicate", "duplicate", 0),+];++describe("mapColumns", () => {+ it("orders states by type group then position and marks final states", () => {+ expect(mapColumns(STATES, new Set(["triage", "duplicate"]))).toEqual([+ { key: "todo", name: "todo", isFinal: false },+ { key: "in-progress", name: "in-progress", isFinal: false },+ { key: "in-review", name: "in-review", isFinal: false },+ { key: "done", name: "done", isFinal: true },+ { key: "canceled", name: "canceled", isFinal: true },+ { key: "duplicate", name: "duplicate", isFinal: true },+ ]);+ });++ it("leaves backlog and triage states to the Kaneo backlog instead of columns", () => {+ expect(+ mapColumns(STATES, new Set(["triage", "backlog"])).map(+ (column) => column.key,+ ),+ ).not.toEqual(expect.arrayContaining(["triage"]));+ expect(+ mapColumns(STATES, new Set(["backlog"])).map((column) => column.key),+ ).not.toContain("backlog");+ });++ it("skips duplicate states without issues but keeps other empty states", () => {+ expect(mapColumns(STATES, new Set()).map((column) => column.key)).toEqual([+ "todo",+ "in-progress",+ "in-review",+ "done",+ "canceled",+ ]);+ });+});++describe("mapPriority", () => {+ it("maps Linear priority numbers", () => {+ expect(mapPriority(0)).toBe("no-priority");+ expect(mapPriority(1)).toBe("urgent");+ expect(mapPriority(2)).toBe("high");+ expect(mapPriority(3)).toBe("medium");+ expect(mapPriority(4)).toBe("low");+ expect(mapPriority(null)).toBe("no-priority");+ expect(mapPriority(7)).toBe("no-priority");+ });+});++describe("toHexColor", () => {+ it("normalizes hex colors and falls back to gray", () => {+ expect(toHexColor("#BEC2C8")).toBe("#bec2c8");+ expect(toHexColor("#abc")).toBe("#aabbcc");+ expect(toHexColor("blue")).toBe("#6b7280");+ expect(toHexColor(null)).toBe("#6b7280");+ });+});++describe("mapLabels", () => {+ it("keeps only used labels and qualifies names shared by two labels", () => {+ const bug = { id: "l-bug", name: "Bug", color: "#EB5757", parent: null };+ const frontend = {+ id: "l-fe",+ name: "Frontend",+ color: "#4ea7fc",+ parent: { name: "Area" },+ };+ const backendBug = {+ id: "l-bbug",+ name: "bug",+ color: "not-a-color",+ parent: { name: "Backend" },+ };+ const labels = mapLabels([+ issue("a", { labels: withLabels(bug, frontend) }),+ issue("b", { labels: withLabels(backendBug, bug) }),+ ]);++ expect(labels).toEqual([+ { key: "l-bbug", name: "Backend: bug", color: "#6b7280" },+ { key: "l-bug", name: "Bug", color: "#eb5757" },+ { key: "l-fe", name: "Frontend", color: "#4ea7fc" },+ ]);+ });+});++describe("mapRelations", () => {+ it("maps parents, blocks and related links once, inside the team only", () => {+ const relations = mapRelations([+ issue("parent", {+ relations: withRelations(["blocks", "child"], ["related", "other"]),+ }),+ issue("child", {+ parent: { id: "parent" },+ relations: withRelations(+ ["related", "other"],+ ["similar", "parent"],+ ["blocks", "outside"],+ ),+ }),+ issue("other", {+ relations: withRelations(["related", "child"], ["duplicate", "parent"]),+ }),+ issue("orphan", { parent: { id: "outside-parent" } }),+ ]);++ expect(relations).toEqual([+ { sourceKey: "parent", targetKey: "child", type: "blocks" },+ { sourceKey: "parent", targetKey: "other", type: "related" },+ { sourceKey: "parent", targetKey: "child", type: "subtask" },+ { sourceKey: "child", targetKey: "other", type: "related" },+ { sourceKey: "child", targetKey: "parent", type: "related" },+ ]);+ });+});++describe("groupComments", () => {+ it("groups comments per issue oldest first with user, bot and fallback authors", () => {+ const comments: LinearComment[] = [+ {+ body: "Second",+ createdAt: "2024-03-02T10:00:00.000Z",+ user: null,+ botActor: { name: "GitHub" },+ issue: { id: "a" },+ },+ {+ body: "First",+ createdAt: "2024-03-01T10:00:00.000Z",+ user: { name: "Ada Lovelace", email: "[email protected]" },+ botActor: null,+ issue: { id: "a" },+ },+ {+ body: "Elsewhere",+ createdAt: "2024-03-03T10:00:00.000Z",+ user: null,+ botActor: null,+ issue: { id: "b" },+ },+ ];++ const grouped = groupComments(comments);++ expect(grouped.get("a")).toEqual([+ {+ author: { name: "Ada Lovelace", email: "[email protected]" },+ body: "First",+ createdAt: "2024-03-01T10:00:00.000Z",+ },+ {+ author: { name: "GitHub" },+ body: "Second",+ createdAt: "2024-03-02T10:00:00.000Z",+ },+ ]);+ expect(grouped.get("b")?.[0]?.author).toEqual({ name: "Linear" });+ });+});++describe("mapIssue", () => {+ it("maps fields and keeps the description as is", () => {+ const task = mapIssue(+ issue("a", {+ number: 123,+ title: "Fix login",+ description: "Steps:\n\n- open app",+ priority: 2,+ dueDate: "2024-05-01",+ createdAt: "2024-04-01T08:30:00.000Z",+ state: { id: "todo" },+ assignee: { name: "Ada Lovelace", email: "[email protected]" },+ labels: withLabels({+ id: "l-bug",+ name: "Bug",+ color: "#eb5757",+ parent: null,+ }),+ }),+ new Set(["todo"]),+ [],+ );++ expect(task).toEqual({+ key: "a",+ number: 123,+ columnKey: "todo",+ title: "Fix login",+ description: "Steps:\n\n- open app",+ priority: "high",+ dueDate: "2024-05-01T00:00:00.000Z",+ createdAt: "2024-04-01T08:30:00.000Z",+ assignee: { name: "Ada Lovelace", email: "[email protected]" },+ labelKeys: ["l-bug"],+ comments: [],+ });+ });++ it("uses no column when the state is not imported", () => {+ const task = mapIssue(issue("a", { state: { id: "gone" } }), new Set(), []);+ expect(task.columnKey).toBeNull();+ expect(task.assignee).toBeUndefined();+ });+});++describe("sortIssues", () => {+ it("orders by state column then sort order", () => {+ const ordered = sortIssues(+ [+ issue("done-1", { state: { id: "done" }, sortOrder: -5 }),+ issue("todo-2", { state: { id: "todo" }, sortOrder: 20 }),+ issue("backlog-1", { state: { id: "backlog" }, sortOrder: 99 }),+ issue("todo-1", { state: { id: "todo" }, sortOrder: -3.5 }),+ issue("unknown", { state: { id: "missing" } }),+ ],+ STATES,+ );+ expect(ordered.map((item) => item.id)).toEqual([+ "backlog-1",+ "todo-1",+ "todo-2",+ "done-1",+ "unknown",+ ]);+ });+});++describe("buildWarnings", () => {+ it("only warns about data that was cut off", () => {+ expect(buildWarnings([issue("a")])).toEqual([]);++ const truncated = issue("b", {+ labels: { nodes: [], pageInfo: { hasNextPage: true } },+ relations: { nodes: [], pageInfo: { hasNextPage: true } },+ });+ expect(buildWarnings([truncated, truncated])).toEqual([+ "2 issues had more than 20 labels; only the first 20 were imported.",+ "2 issues had more than 10 linked issues; only the first 10 links were imported.",+ ]);+ });+});++describe("mapTeam", () => {+ it("builds the project from a team", () => {+ const team: LinearTeam = {+ id: "team-1",+ key: "ENG",+ name: "Engineering",+ description: " Product engineering ",+ states: { nodes: STATES },+ };+ const project = mapTeam(+ team,+ [+ issue("a", { number: 7, state: { id: "duplicate" } }),+ issue("b", { number: 3 }),+ ],+ [+ {+ body: "Hello",+ createdAt: "2024-03-01T10:00:00.000Z",+ user: { name: "Ada", email: "[email protected]" },+ botActor: null,+ issue: { id: "b" },+ },+ ],+ );++ expect(project.name).toBe("Engineering");+ expect(project.key).toBe("ENG");+ expect(project.description).toBe("Product engineering");+ expect(project.columns.map((column) => column.key)).toEqual([+ "todo",+ "in-progress",+ "in-review",+ "done",+ "canceled",+ "duplicate",+ ]);+ expect(project.tasks.map((task) => task.key)).toEqual(["b", "a"]);+ expect(project.tasks.map((task) => task.number)).toEqual([3, 7]);+ expect(project.tasks[0]?.comments).toHaveLength(1);+ expect(project.tasks[1]?.comments).toEqual([]);+ expect(project.labels).toEqual([]);+ expect(project.relations).toEqual([]);+ });+});diff --git a/packages/importers/src/linear/mapping.ts b/packages/importers/src/linear/mapping.tsnew file mode 100644index 000000000..353420cdd--- /dev/null+++ b/packages/importers/src/linear/mapping.ts@@ -0,0 +1,123 @@+import { toIsoDate } from "../markdown.js";+import type {+ ImportedComment,+ ImportedPriority,+ ImportedProject,+ ImportedTask,+} from "../types.js";+import type {+ LinearComment,+ LinearIssue,+ LinearTeam,+ LinearWorkflowState,+} from "./client.js";+import { mapColumns, orderStates } from "./columns.js";+import { groupComments } from "./comments.js";+import { mapLabels } from "./labels.js";+import { toPerson } from "./people.js";+import { LABELS_PER_ISSUE, RELATIONS_PER_ISSUE } from "./queries.js";+import { mapRelations } from "./relations.js";++const PRIORITIES: Record<number, ImportedPriority> = {+ 1: "urgent",+ 2: "high",+ 3: "medium",+ 4: "low",+};++export function mapPriority(+ priority: number | null | undefined,+): ImportedPriority {+ return (priority != null && PRIORITIES[priority]) || "no-priority";+}++export function sortIssues(+ issues: LinearIssue[],+ states: LinearWorkflowState[],+): LinearIssue[] {+ const rank = new Map(+ orderStates(states).map((state, index) => [state.id, index]),+ );+ const rankOf = (issue: LinearIssue) =>+ (issue.state && rank.get(issue.state.id)) ?? states.length;+ return [...issues].sort(+ (a, b) => rankOf(a) - rankOf(b) || (a.sortOrder ?? 0) - (b.sortOrder ?? 0),+ );+}++export function mapIssue(+ issue: LinearIssue,+ columnKeys: ReadonlySet<string>,+ comments: ImportedComment[],+): ImportedTask {+ const stateId = issue.state?.id;+ const dueDate = toIsoDate(issue.dueDate);+ const createdAt = toIsoDate(issue.createdAt);+ const assignee = toPerson(issue.assignee);+ return {+ key: issue.id,+ number: issue.number,+ columnKey: stateId && columnKeys.has(stateId) ? stateId : null,+ title: issue.title,+ description: issue.description ?? "",+ priority: mapPriority(issue.priority),+ ...(dueDate ? { dueDate } : {}),+ ...(createdAt ? { createdAt } : {}),+ ...(assignee ? { assignee } : {}),+ labelKeys: issue.labels.nodes.map((label) => label.id),+ comments,+ };+}++export function buildWarnings(issues: LinearIssue[]): string[] {+ const warnings: string[] = [];+ const manyLabels = issues.filter(+ (issue) => issue.labels.pageInfo.hasNextPage,+ ).length;+ if (manyLabels > 0) {+ warnings.push(+ `${issueCount(manyLabels)} had more than ${LABELS_PER_ISSUE} labels; only the first ${LABELS_PER_ISSUE} were imported.`,+ );+ }+ const manyRelations = issues.filter(+ (issue) => issue.relations.pageInfo.hasNextPage,+ ).length;+ if (manyRelations > 0) {+ warnings.push(+ `${issueCount(manyRelations)} had more than ${RELATIONS_PER_ISSUE} linked issues; only the first ${RELATIONS_PER_ISSUE} links were imported.`,+ );+ }+ return warnings;+}++export function mapTeam(+ team: LinearTeam,+ issues: LinearIssue[],+ comments: LinearComment[],+): ImportedProject {+ const states = team.states.nodes;+ const usedStateIds = new Set(+ issues.flatMap((issue) => (issue.state ? [issue.state.id] : [])),+ );+ const columns = mapColumns(states, usedStateIds);+ const columnKeys = new Set(columns.map((column) => column.key));+ const commentsByIssue = groupComments(comments);+ const description = team.description?.trim();++ return {+ name: team.name,+ key: team.key,+ ...(description ? { description } : {}),+ columns,+ labels: mapLabels(issues),+ tasks: sortIssues(issues, states).map((issue) =>+ mapIssue(issue, columnKeys, commentsByIssue.get(issue.id) ?? []),+ ),+ relations: mapRelations(issues),+ warnings: buildWarnings(issues),+ };+}++function issueCount(count: number): string {+ return count === 1 ? "1 issue" : `${count} issues`;+}diff --git a/packages/importers/src/linear/people.ts b/packages/importers/src/linear/people.tsnew file mode 100644index 000000000..5e3bbcbf8--- /dev/null+++ b/packages/importers/src/linear/people.ts@@ -0,0 +1,11 @@+import type { ImportedPerson } from "../types.js";+import type { LinearUser } from "./client.js";++export function toPerson(+ user: LinearUser | null | undefined,+): ImportedPerson | undefined {+ const name = user?.name?.trim();+ const email = user?.email?.trim();+ if (!name && !email) return undefined;+ return { ...(name ? { name } : {}), ...(email ? { email } : {}) };+}diff --git a/packages/importers/src/linear/queries.ts b/packages/importers/src/linear/queries.tsnew file mode 100644index 000000000..e4a8b403b--- /dev/null+++ b/packages/importers/src/linear/queries.ts@@ -0,0 +1,78 @@+export const TEAMS_PAGE_SIZE = 100;+export const STATES_PER_TEAM = 100;+export const ISSUES_PAGE_SIZE = 50;+export const LABELS_PER_ISSUE = 20;+export const RELATIONS_PER_ISSUE = 10;+export const COMMENTS_PAGE_SIZE = 100;++export const VIEWER_QUERY = `query ImportViewer {+ viewer { id name email }+}`;++export const TEAMS_QUERY = `query ImportTeams($after: String) {+ teams(first: ${TEAMS_PAGE_SIZE}, after: $after) {+ nodes { id key name issueCount }+ pageInfo { hasNextPage endCursor }+ }+}`;++export const TEAM_QUERY = `query ImportTeam($teamId: String!) {+ team(id: $teamId) {+ id+ key+ name+ description+ states(first: ${STATES_PER_TEAM}) {+ nodes { id name type position color }+ }+ }+}`;++export const ISSUES_QUERY = `query ImportIssues($teamId: ID!, $after: String) {+ issues(+ first: ${ISSUES_PAGE_SIZE}+ after: $after+ includeArchived: false+ filter: { team: { id: { eq: $teamId } } }+ ) {+ nodes {+ id+ number+ title+ description+ priority+ dueDate+ sortOrder+ createdAt+ state { id }+ assignee { name email }+ parent { id }+ labels(first: ${LABELS_PER_ISSUE}) {+ nodes { id name color parent { name } }+ pageInfo { hasNextPage }+ }+ relations(first: ${RELATIONS_PER_ISSUE}) {+ nodes { type relatedIssue { id } }+ pageInfo { hasNextPage }+ }+ }+ pageInfo { hasNextPage endCursor }+ }+}`;++export const COMMENTS_QUERY = `query ImportComments($teamId: ID!, $after: String) {+ comments(+ first: ${COMMENTS_PAGE_SIZE}+ after: $after+ filter: { issue: { team: { id: { eq: $teamId } } } }+ ) {+ nodes {+ body+ createdAt+ user { name email }+ botActor { name }+ issue { id }+ }+ pageInfo { hasNextPage endCursor }+ }+}`;diff --git a/packages/importers/src/linear/relations.ts b/packages/importers/src/linear/relations.tsnew file mode 100644index 000000000..3cff31937--- /dev/null+++ b/packages/importers/src/linear/relations.ts@@ -0,0 +1,44 @@+import type { ImportedRelation, ImportedRelationType } from "../types.js";+import type { LinearIssue } from "./client.js";++const RELATION_TYPES: Record<string, ImportedRelationType> = {+ blocks: "blocks",+ related: "related",+ similar: "related",+ duplicate: "related",+};++export function mapRelations(issues: LinearIssue[]): ImportedRelation[] {+ const issueIds = new Set(issues.map((issue) => issue.id));+ const seen = new Set<string>();+ const relations: ImportedRelation[] = [];++ function add(+ sourceKey: string,+ targetKey: string,+ type: ImportedRelationType,+ ): void {+ if (sourceKey === targetKey) return;+ if (!issueIds.has(sourceKey) || !issueIds.has(targetKey)) return;+ const pair =+ type === "related"+ ? [sourceKey, targetKey].sort().join(":")+ : `${sourceKey}:${targetKey}`;+ const id = `${type}:${pair}`;+ if (seen.has(id)) return;+ seen.add(id);+ relations.push({ sourceKey, targetKey, type });+ }++ for (const issue of issues) {+ if (issue.parent) add(issue.parent.id, issue.id, "subtask");+ for (const relation of issue.relations.nodes) {+ const type = RELATION_TYPES[relation.type];+ if (type && relation.relatedIssue) {+ add(issue.id, relation.relatedIssue.id, type);+ }+ }+ }++ return relations;+}diff --git a/packages/importers/src/linear/source.test.ts b/packages/importers/src/linear/source.test.tsnew file mode 100644index 000000000..f34de941c--- /dev/null+++ b/packages/importers/src/linear/source.test.ts@@ -0,0 +1,414 @@+import { describe, expect, it } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import type { LinearComment, LinearIssue } from "./client.js";+import { INVALID_API_KEY_MESSAGE } from "./graphql.js";+import { connectLinear } from "./source.js";++const API_KEY = "lin_api_secret";++type Variables = Record<string, unknown>;+type Handler = (variables: Variables) => unknown;++function fakeLinear(handlers: Record<string, Handler>) {+ const calls: Array<{+ operation: string;+ query: string;+ variables: Variables;+ headers: Headers;+ }> = [];+ const fetch: FetchLike = async (_url, init) => {+ const body = JSON.parse(String(init?.body)) as {+ query: string;+ variables: Variables;+ };+ const operation = /query (\w+)/.exec(body.query)?.[1] ?? "";+ calls.push({+ operation,+ query: body.query,+ variables: body.variables,+ headers: new Headers(init?.headers),+ });+ const handler = handlers[operation];+ const payload = handler+ ? { data: handler(body.variables) }+ : { errors: [{ message: `Unexpected operation ${operation}` }] };+ return new Response(JSON.stringify(payload), {+ status: handler ? 200 : 400,+ headers: { "Content-Type": "application/json" },+ });+ };+ return { fetch, calls };+}++function page<T>(nodes: T[], endCursor: string | null) {+ return { nodes, pageInfo: { hasNextPage: endCursor !== null, endCursor } };+}++function byCursor<T>(+ field: string,+ pages: Record<string, { nodes: T[]; next: string | null }>,+) {+ return (variables: Variables) => {+ const current = pages[String(variables.after ?? "start")];+ if (!current) throw new Error(`unknown cursor ${String(variables.after)}`);+ return { [field]: page(current.nodes, current.next) };+ };+}++function issue(id: string, overrides: Partial<LinearIssue> = {}): LinearIssue {+ return {+ id,+ number: 1,+ title: `Issue ${id}`,+ description: null,+ priority: 0,+ dueDate: null,+ sortOrder: 0,+ createdAt: "2024-01-01T00:00:00.000Z",+ state: { id: "todo" },+ assignee: null,+ parent: null,+ labels: { nodes: [], pageInfo: { hasNextPage: false } },+ relations: { nodes: [], pageInfo: { hasNextPage: false } },+ ...overrides,+ };+}++const TEAM = {+ id: "team-1",+ key: "ENG",+ name: "Engineering",+ description: null,+ states: {+ nodes: [+ {+ id: "done",+ name: "Done",+ type: "completed",+ position: 3,+ color: "#5e6ad2",+ },+ {+ id: "todo",+ name: "Todo",+ type: "unstarted",+ position: 1,+ color: "#e2e2e2",+ },+ {+ id: "triage",+ name: "Triage",+ type: "triage",+ position: 0,+ color: "#fc7840",+ },+ {+ id: "doing",+ name: "In Progress",+ type: "started",+ position: 2,+ color: "#f2c94c",+ },+ ],+ },+};++const BUG = { id: "label-bug", name: "Bug", color: "#EB5757", parent: null };++const ISSUES_PAGE_1 = [+ issue("i-1", {+ number: 1,+ title: "Ship importer",+ priority: 1,+ state: { id: "doing" },+ sortOrder: 2,+ assignee: { name: "Ada Lovelace", email: "[email protected]" },+ labels: { nodes: [BUG], pageInfo: { hasNextPage: false } },+ relations: {+ nodes: [{ type: "blocks", relatedIssue: { id: "i-3" } }],+ pageInfo: { hasNextPage: false },+ },+ }),+ issue("i-2", { number: 2, title: "Write docs", priority: 4, sortOrder: 1 }),+];++const ISSUES_PAGE_2 = [+ issue("i-3", {+ number: 3,+ title: "Release",+ parent: { id: "i-1" },+ state: { id: "done" },+ dueDate: "2024-06-30",+ relations: {+ nodes: [{ type: "related", relatedIssue: { id: "i-2" } }],+ pageInfo: { hasNextPage: false },+ },+ }),+];++const COMMENTS_PAGE_1: LinearComment[] = [+ {+ body: "Looks good",+ createdAt: "2024-02-02T00:00:00.000Z",+ user: { name: "Grace Hopper", email: "[email protected]" },+ botActor: null,+ issue: { id: "i-1" },+ },+];++const COMMENTS_PAGE_2: LinearComment[] = [+ {+ body: "Linked PR #42",+ createdAt: "2024-02-01T00:00:00.000Z",+ user: null,+ botActor: { name: "GitHub" },+ issue: { id: "i-1" },+ },+];++function linearApi() {+ return fakeLinear({+ ImportViewer: () => ({+ viewer: { id: "user-1", name: "Ada", email: "[email protected]" },+ }),+ ImportTeams: byCursor("teams", {+ start: {+ nodes: [+ { id: "team-1", key: "ENG", name: "Engineering", issueCount: 3 },+ ],+ next: "teams-2",+ },+ "teams-2": {+ nodes: [+ { id: "team-2", key: "OPS", name: "Operations", issueCount: 1 },+ ],+ next: null,+ },+ }),+ ImportTeam: (variables) => {+ if (variables.teamId !== "team-1") {+ throw new Error("unknown team");+ }+ return { team: TEAM };+ },+ ImportIssues: byCursor("issues", {+ start: { nodes: ISSUES_PAGE_1, next: "issues-2" },+ "issues-2": { nodes: ISSUES_PAGE_2, next: null },+ }),+ ImportComments: byCursor("comments", {+ start: { nodes: COMMENTS_PAGE_1, next: "comments-2" },+ "comments-2": { nodes: COMMENTS_PAGE_2, next: null },+ }),+ });+}++describe("connectLinear", () => {+ it("validates the API key with the viewer query", async () => {+ const api = linearApi();+ await connectLinear({ apiKey: ` ${API_KEY} ` }, { fetch: api.fetch });++ expect(api.calls.map((call) => call.operation)).toEqual(["ImportViewer"]);+ expect(api.calls[0]?.headers.get("authorization")).toBe(API_KEY);+ });++ it("asks for a key before calling Linear", async () => {+ const api = linearApi();+ await expect(+ connectLinear({ apiKey: " " }, { fetch: api.fetch }),+ ).rejects.toThrow("Enter a Linear personal API key");+ expect(api.calls).toHaveLength(0);+ });++ it("explains an invalid API key", async () => {+ const fetch: FetchLike = async () =>+ new Response(+ JSON.stringify({+ errors: [+ {+ message: "Authentication required, not authenticated",+ extensions: { code: "AUTHENTICATION_ERROR" },+ },+ ],+ }),+ { status: 400, headers: { "Content-Type": "application/json" } },+ );++ await expect(connectLinear({ apiKey: API_KEY }, { fetch })).rejects.toThrow(+ INVALID_API_KEY_MESSAGE,+ );+ });++ it("lists teams across pages with their key and issue count", async () => {+ const api = linearApi();+ const source = await connectLinear(+ { apiKey: API_KEY },+ { fetch: api.fetch },+ );++ expect(await source.listProjects()).toEqual([+ { id: "team-1", name: "Engineering", detail: "ENG · 3 issues" },+ { id: "team-2", name: "Operations", detail: "OPS · 1 issue" },+ ]);+ expect(+ api.calls+ .filter((call) => call.operation === "ImportTeams")+ .map((call) => call.variables.after),+ ).toEqual([null, "teams-2"]);+ });++ it("reads a team with paginated issues and comments", async () => {+ const api = linearApi();+ const source = await connectLinear(+ { apiKey: API_KEY },+ { fetch: api.fetch },+ );+ const progress: string[] = [];++ const project = await source.readProject("team-1", {+ includeComments: true,+ onProgress: (message) => progress.push(message),+ });++ expect(project.name).toBe("Engineering");+ expect(project.key).toBe("ENG");+ expect(project.description).toBeUndefined();+ expect(project.columns).toEqual([+ { key: "todo", name: "Todo", isFinal: false },+ { key: "doing", name: "In Progress", isFinal: false },+ { key: "done", name: "Done", isFinal: true },+ ]);+ expect(project.labels).toEqual([+ { key: "label-bug", name: "Bug", color: "#eb5757" },+ ]);+ expect(project.tasks).toEqual([+ {+ key: "i-2",+ number: 2,+ columnKey: "todo",+ title: "Write docs",+ description: "",+ priority: "low",+ createdAt: "2024-01-01T00:00:00.000Z",+ labelKeys: [],+ comments: [],+ },+ {+ key: "i-1",+ number: 1,+ columnKey: "doing",+ title: "Ship importer",+ description: "",+ priority: "urgent",+ createdAt: "2024-01-01T00:00:00.000Z",+ assignee: { name: "Ada Lovelace", email: "[email protected]" },+ labelKeys: ["label-bug"],+ comments: [+ {+ author: { name: "GitHub" },+ body: "Linked PR #42",+ createdAt: "2024-02-01T00:00:00.000Z",+ },+ {+ author: { name: "Grace Hopper", email: "[email protected]" },+ body: "Looks good",+ createdAt: "2024-02-02T00:00:00.000Z",+ },+ ],+ },+ {+ key: "i-3",+ number: 3,+ columnKey: "done",+ title: "Release",+ description: "",+ priority: "no-priority",+ dueDate: "2024-06-30T00:00:00.000Z",+ createdAt: "2024-01-01T00:00:00.000Z",+ labelKeys: [],+ comments: [],+ },+ ]);+ expect(project.relations).toEqual([+ { sourceKey: "i-1", targetKey: "i-3", type: "blocks" },+ { sourceKey: "i-1", targetKey: "i-3", type: "subtask" },+ { sourceKey: "i-3", targetKey: "i-2", type: "related" },+ ]);+ expect(project.warnings).toEqual([]);++ expect(+ api.calls+ .filter((call) => call.operation === "ImportIssues")+ .map((call) => call.variables),+ ).toEqual([+ { teamId: "team-1", after: null },+ { teamId: "team-1", after: "issues-2" },+ ]);+ expect(+ api.calls.find((call) => call.operation === "ImportIssues")?.query,+ ).toMatch(/^\s+number$/m);+ expect(progress).toEqual([+ "Reading team",+ "Reading issues",+ "Reading issues (2 so far)",+ "Reading issues (3 so far)",+ "Reading comments",+ "Reading comments (1 so far)",+ "Reading comments (2 so far)",+ ]);+ expect(+ api.calls.every((call) => call.headers.get("authorization") === API_KEY),+ ).toBe(true);+ });++ it("skips comments when they are not requested", async () => {+ const api = linearApi();+ const source = await connectLinear(+ { apiKey: API_KEY },+ { fetch: api.fetch },+ );++ const project = await source.readProject("team-1", {+ includeComments: false,+ });++ expect(project.tasks.every((task) => task.comments.length === 0)).toBe(+ true,+ );+ expect(api.calls.some((call) => call.operation === "ImportComments")).toBe(+ false,+ );+ });++ it("explains a missing team", async () => {+ const api = fakeLinear({+ ImportViewer: () => ({+ viewer: { id: "user-1", name: null, email: null },+ }),+ });+ const notFound: FetchLike = async (url, init) => {+ const body = String(init?.body);+ if (body.includes("ImportTeam(")) {+ return new Response(+ JSON.stringify({+ errors: [+ {+ message: "Entity not found: Team",+ extensions: { code: "INVALID_INPUT" },+ },+ ],+ }),+ { status: 400, headers: { "Content-Type": "application/json" } },+ );+ }+ return api.fetch(url, init);+ };+ const source = await connectLinear(+ { apiKey: API_KEY },+ { fetch: notFound },+ );++ await expect(+ source.readProject("missing", { includeComments: false }),+ ).rejects.toThrow("This Linear team was not found.");+ });+});diff --git a/packages/importers/src/linear/source.ts b/packages/importers/src/linear/source.tsnew file mode 100644index 000000000..38211d106--- /dev/null+++ b/packages/importers/src/linear/source.ts@@ -0,0 +1,98 @@+import type {+ ConnectOptions,+ ImportedProject,+ ImportSource,+ ReadProjectOptions,+ SourceProject,+} from "../types.js";+import {+ type LinearComment,+ LinearClient,+ type LinearTeam,+ type LinearTeamSummary,+} from "./client.js";+import { LinearApiError } from "./graphql.js";+import { mapTeam } from "./mapping.js";++export type LinearCredentials = {+ apiKey: string;+};++export async function connectLinear(+ credentials: LinearCredentials,+ options: ConnectOptions,+): Promise<ImportSource> {+ const apiKey = credentials.apiKey?.trim();+ if (!apiKey) {+ throw new Error(+ "Enter a Linear personal API key. Create one under Settings > Account > Security & access.",+ );+ }++ const client = new LinearClient({+ apiKey,+ fetch: options.fetch,+ signal: options.signal,+ });+ await client.viewer();++ return {+ async listProjects(): Promise<SourceProject[]> {+ const teams = await client.listTeams();+ return teams.map((team) => ({+ id: team.id,+ name: team.name,+ detail: teamDetail(team),+ }));+ },++ async readProject(+ teamId: string,+ readOptions: ReadProjectOptions,+ ): Promise<ImportedProject> {+ const scoped = client.withSignal(readOptions.signal);+ const onProgress = readOptions.onProgress;++ onProgress?.("Reading team");+ const team = await readTeam(scoped, teamId);++ onProgress?.("Reading issues");+ const issues = await scoped.listIssues(teamId, (count) =>+ onProgress?.(`Reading issues (${count} so far)`),+ );++ let comments: LinearComment[] = [];+ if (readOptions.includeComments && issues.length > 0) {+ onProgress?.("Reading comments");+ comments = await scoped.listComments(teamId, (count) =>+ onProgress?.(`Reading comments (${count} so far)`),+ );+ }++ return mapTeam(team, issues, comments);+ },+ };+}++function teamDetail(team: LinearTeamSummary): string {+ if (typeof team.issueCount !== "number") return team.key;+ const issues =+ team.issueCount === 1 ? "1 issue" : `${team.issueCount} issues`;+ return `${team.key} · ${issues}`;+}++async function readTeam(+ client: LinearClient,+ teamId: string,+): Promise<LinearTeam> {+ try {+ return await client.getTeam(teamId);+ } catch (error) {+ if (error instanceof LinearApiError && /not found/i.test(error.message)) {+ throw new Error(+ "This Linear team was not found. It may have been deleted, or the API key can no longer access it.",+ );+ }+ throw error;+ }+}diff --git a/packages/importers/src/markdown.ts b/packages/importers/src/markdown.tsnew file mode 100644index 000000000..af873f022--- /dev/null+++ b/packages/importers/src/markdown.ts@@ -0,0 +1,32 @@+export type ChecklistItem = {+ name: string;+ done: boolean;+};++export function checklistSection(+ title: string,+ items: ChecklistItem[],+): string {+ const lines = items.map(+ (item) => `- [${item.done ? "x" : " "}] ${item.name}`,+ );+ const heading = title.trim();+ return heading ? `## ${heading}\n\n${lines.join("\n")}` : lines.join("\n");+}++export function joinSections(+ sections: Array<string | null | undefined>,+): string {+ return sections+ .map((section) => section?.trim())+ .filter((section): section is string => Boolean(section))+ .join("\n\n");+}++export function toIsoDate(+ value: string | null | undefined,+): string | undefined {+ if (!value) return undefined;+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();+}diff --git a/packages/importers/src/plane/client.ts b/packages/importers/src/plane/client.tsnew file mode 100644index 000000000..7772ebc90--- /dev/null+++ b/packages/importers/src/plane/client.ts@@ -0,0 +1,263 @@+import { createJsonClient, type JsonClient, SourceHttpError } from "../http.js";+import type { FetchLike } from "../types.js";+import { MAX_PACE_MS } from "./pacing.js";++export type PlaneUser = {+ id: string;+ email?: string | null;+ display_name?: string | null;+ first_name?: string | null;+ last_name?: string | null;+};++export type PlaneMember = PlaneUser & { member?: PlaneUser | null };++export type PlaneProject = {+ id: string;+ name: string;+ identifier?: string | null;+ description?: string | null;+ archived_at?: string | null;+};++export type PlaneState = {+ id: string;+ name: string;+ color?: string | null;+ group?: string | null;+ sequence?: number | null;+};++export type PlaneLabel = {+ id: string;+ name: string;+ color?: string | null;+ parent?: string | null;+};++export type PlaneWorkItem = {+ id: string;+ name?: string | null;+ description_html?: string | null;+ priority?: string | null;+ state?: string | null;+ assignees?: Array<string | PlaneUser> | null;+ labels?: string[] | null;+ parent?: string | null;+ start_date?: string | null;+ target_date?: string | null;+ sort_order?: number | null;+ sequence_id?: number | null;+ created_at?: string | null;+ archived_at?: string | null;+};++export type PlaneComment = {+ id: string;+ comment_html?: string | null;+ comment_stripped?: string | null;+ created_at?: string | null;+ actor?: string | PlaneUser | null;+ actor_detail?: PlaneUser | null;+};++export type PlanePage<T> =+ | T[]+ | {+ results?: T[] | null;+ next_cursor?: string | null;+ next_page_results?: boolean | null;+ total_results?: number | null;+ total_count?: number | null;+ };++export type PageProgress = (loaded: number, total: number | undefined) => void;++export type WorkItemSegment = "work-items" | "issues";++export const PAGE_SIZE = 100;+export const REQUEST_TIMEOUT_MS = 30_000 + MAX_PACE_MS;++export const WORK_ITEM_FIELDS = [+ "id",+ "name",+ "description_html",+ "priority",+ "state",+ "assignees",+ "labels",+ "parent",+ "start_date",+ "target_date",+ "sort_order",+ "sequence_id",+ "created_at",+ "archived_at",+];++export type PlaneClientOptions = {+ baseUrl: string;+ apiKey: string;+ workspaceSlug: string;+ fetch: FetchLike;+ signal?: AbortSignal;+};++type SharedState = { segment: WorkItemSegment | null };++export class PlaneClient {+ readonly workspaceSlug: string;+ private readonly http: JsonClient;++ constructor(+ private readonly options: PlaneClientOptions,+ private readonly shared: SharedState = { segment: null },+ ) {+ this.workspaceSlug = options.workspaceSlug;+ this.http = createJsonClient({+ service: "Plane",+ baseUrl: options.baseUrl,+ headers: () => ({ "X-API-Key": options.apiKey }),+ fetch: options.fetch,+ signal: options.signal,+ timeoutMs: REQUEST_TIMEOUT_MS,+ });+ }++ withSignal(signal: AbortSignal | undefined): PlaneClient {+ if (!signal) return this;+ const current = this.options.signal;+ return new PlaneClient(+ {+ ...this.options,+ signal: current ? AbortSignal.any([current, signal]) : signal,+ },+ this.shared,+ );+ }++ me(): Promise<PlaneUser | null> {+ return this.http.request<PlaneUser | null>("/api/v1/users/me/");+ }++ listProjects(): Promise<PlaneProject[]> {+ return this.listAll<PlaneProject>(this.workspacePath("/projects/"));+ }++ getProject(projectId: string): Promise<PlaneProject> {+ return this.http.request<PlaneProject>(this.projectPath(projectId, "/"));+ }++ listStates(projectId: string): Promise<PlaneState[]> {+ return this.listAll<PlaneState>(this.projectPath(projectId, "/states/"));+ }++ listLabels(projectId: string): Promise<PlaneLabel[]> {+ return this.listAll<PlaneLabel>(this.projectPath(projectId, "/labels/"));+ }++ listMembers(projectId: string): Promise<PlaneMember[]> {+ return this.listAll<PlaneMember>(this.projectPath(projectId, "/members/"));+ }++ listWorkItems(+ projectId: string,+ options: { expandAssignees?: boolean; onPage?: PageProgress } = {},+ ): Promise<PlaneWorkItem[]> {+ const query: Record<string, string> = {+ fields: WORK_ITEM_FIELDS.join(","),+ };+ if (options.expandAssignees) query.expand = "assignees";+ return this.withWorkItemSegment((segment) =>+ this.listAll<PlaneWorkItem>(+ this.projectPath(projectId, `/${segment}/`),+ query,+ options.onPage,+ ),+ );+ }++ listComments(projectId: string, workItemId: string): Promise<PlaneComment[]> {+ return this.withWorkItemSegment((segment) =>+ this.listAll<PlaneComment>(+ this.projectPath(+ projectId,+ `/${segment}/${encodeURIComponent(workItemId)}/comments/`,+ ),+ { expand: "actor" },+ ),+ );+ }++ private async withWorkItemSegment<T>(+ run: (segment: WorkItemSegment) => Promise<T>,+ ): Promise<T> {+ if (this.shared.segment) return run(this.shared.segment);+ try {+ const result = await run("work-items");+ this.shared.segment = "work-items";+ return result;+ } catch (error) {+ if (!(error instanceof SourceHttpError) || error.status !== 404) {+ throw error;+ }+ }+ const result = await run("issues");+ this.shared.segment = "issues";+ return result;+ }++ private async listAll<T>(+ path: string,+ query: Record<string, string> = {},+ onPage?: PageProgress,+ ): Promise<T[]> {+ const items: T[] = [];+ const seenCursors = new Set<string>();+ let cursor: string | undefined;++ for (;;) {+ const params = new URLSearchParams({+ ...query,+ per_page: String(PAGE_SIZE),+ });+ if (cursor) params.set("cursor", cursor);+ const page = await this.http.request<PlanePage<T> | null>(+ `${path}?${params}`,+ );++ if (Array.isArray(page)) {+ items.push(...page);+ onPage?.(items.length, items.length);+ return items;+ }++ const results = page?.results ?? [];+ items.push(...results);+ const total = page?.total_results ?? page?.total_count;+ onPage?.(items.length, typeof total === "number" ? total : undefined);++ const next = page?.next_cursor;+ if (+ !next ||+ page?.next_page_results === false ||+ results.length === 0 ||+ seenCursors.has(next)+ ) {+ return items;+ }+ seenCursors.add(next);+ cursor = next;+ }+ }++ private workspacePath(suffix: string): string {+ return `/api/v1/workspaces/${encodeURIComponent(this.workspaceSlug)}${suffix}`;+ }++ private projectPath(projectId: string, suffix: string): string {+ return this.workspacePath(+ `/projects/${encodeURIComponent(projectId)}${suffix}`,+ );+ }+}diff --git a/packages/importers/src/plane/html.test.ts b/packages/importers/src/plane/html.test.tsnew file mode 100644index 000000000..4e7880bfc--- /dev/null+++ b/packages/importers/src/plane/html.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vite-plus/test";+import { createHtmlToMarkdown } from "./html.js";++const toMarkdown = createHtmlToMarkdown({+ mentionName: (id) => (id === "user-1" ? "jane" : undefined),+});++describe("createHtmlToMarkdown", () => {+ it("treats empty editor HTML as an empty description", () => {+ expect(toMarkdown(null)).toBe("");+ expect(toMarkdown("")).toBe("");+ expect(toMarkdown("<p></p>")).toBe("");+ expect(toMarkdown('<p class="editor-paragraph-block"></p>')).toBe("");+ expect(toMarkdown("<p><br></p>")).toBe("");+ });++ it("converts headings, emphasis and links", () => {+ expect(+ toMarkdown(+ '<h2>Goal</h2><p>Ship <strong>fast</strong> and <em>safe</em>, see <a href="https://example.com/spec">the spec</a>.</p>',+ ),+ ).toBe(+ "## Goal\n\nShip **fast** and _safe_, see [the spec](https://example.com/spec).",+ );+ });++ it("writes tight bullet and numbered lists from editor paragraphs", () => {+ expect(+ toMarkdown(+ "<ul><li><p>one</p><ul><li><p>nested</p></li></ul></li><li><p>two</p></li></ul><ol><li><p>first</p></li><li><p>second</p></li></ol>",+ ),+ ).toBe("- one\n - nested\n- two\n\n1. first\n2. second");+ });++ it("converts Plane task lists to GFM checkboxes", () => {+ expect(+ toMarkdown(+ '<ul data-type="taskList"><li data-checked="true" data-type="taskItem"><label><input type="checkbox" checked="checked"><span></span></label><div><p>done</p></div></li><li data-checked="false" data-type="taskItem"><label><input type="checkbox"><span></span></label><div><p>todo</p></div></li></ul>',+ ),+ ).toBe("- [x] done\n- [ ] todo");+ });++ it("indents nested task lists under their parent item", () => {+ expect(+ toMarkdown(+ '<ul data-type="taskList"><li data-checked="false" data-type="taskItem"><label><input type="checkbox"><span></span></label><div><p>parent</p><ul data-type="taskList"><li data-checked="true" data-type="taskItem"><label><input type="checkbox" checked="checked"><span></span></label><div><p>child</p></div></li></ul></div></li></ul>',+ ),+ ).toBe("- [ ] parent\n - [x] child");+ });++ it("keeps fenced code blocks and inline code", () => {+ expect(+ toMarkdown(+ '<p>Run <code>pnpm test</code></p><pre><code class="language-ts">const a = 1;\nconst b = 2;</code></pre>',+ ),+ ).toBe("Run `pnpm test`\n\n```ts\nconst a = 1;\nconst b = 2;\n```");+ });++ it("degrades mentions to plain text", () => {+ expect(+ toMarkdown(+ '<p>Ping <mention-component id="m1" entity_identifier="user-1" entity_name="user_mention"></mention-component> and <mention-component label="Bob" entity_identifier="user-2"></mention-component></p>',+ ),+ ).toBe("Ping @jane and @Bob");+ expect(+ toMarkdown(+ '<p>Ping <span data-type="mention" data-id="user-9">@Sam</span> <mention-component entity_identifier="user-9" entity_name="user_mention"></mention-component>now</p>',+ ),+ ).toBe("Ping @Sam now");+ });++ it("escapes resolved mention names and drops unknown mentions", () => {+ const convert = createHtmlToMarkdown({ mentionName: () => "<R&D>" });+ expect(+ convert(+ '<p>Hi <mention-component entity_identifier="x" entity_name="user_mention"></mention-component></p>',+ ),+ ).toBe("Hi @<R&D>");+ expect(+ createHtmlToMarkdown()(+ '<p>Hi <mention-component entity_identifier="x"></mention-component></p>',+ ),+ ).toBe("Hi");+ });++ it("drops images that only live inside Plane", () => {+ expect(+ toMarkdown(+ '<p>Before</p><image-component src="asset-id" width="300"></image-component><img src="/api/assets/v2/abc/" alt=""><img src="https://cdn.example.com/a.png" alt="chart"><p>After</p>',+ ),+ ).toBe("Before\n\n\n\nAfter");+ });++ it("converts tables with a header row", () => {+ expect(+ toMarkdown(+ "<table><tbody><tr><th><p>Name</p></th><th><p>Owner</p></th></tr><tr><td><p>API</p></td><td><p>Jane</p></td></tr></tbody></table>",+ ),+ ).toBe("| Name | Owner |\n| --- | --- |\n| API | Jane |");+ });+});diff --git a/packages/importers/src/plane/html.ts b/packages/importers/src/plane/html.tsnew file mode 100644index 000000000..a7b05d724--- /dev/null+++ b/packages/importers/src/plane/html.ts@@ -0,0 +1,119 @@+import TurndownService from "turndown";+import { gfm } from "turndown-plugin-gfm";++export type HtmlToMarkdownOptions = {+ mentionName?: (userId: string) => string | undefined;+};++export type HtmlToMarkdown = (html: string | null | undefined) => string;++const MENTION_PATTERN =+ /<mention-component\b([^>]*)>([\s\S]*?)<\/mention-component>/gi;+const ATTRIBUTE_PATTERN = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;++export function createHtmlToMarkdown(+ options: HtmlToMarkdownOptions = {},+): HtmlToMarkdown {+ const service = new TurndownService({+ headingStyle: "atx",+ codeBlockStyle: "fenced",+ bulletListMarker: "-",+ });+ service.use(gfm);+ service.addRule("planeParagraph", { filter: "p", replacement: paragraph });+ service.addRule("planeList", { filter: ["ul", "ol"], replacement: list });+ service.addRule("planeListItem", { filter: "li", replacement: listItem });+ service.addRule("planeImage", { filter: "img", replacement: image });++ return (html) => {+ if (!html?.trim()) return "";+ return service+ .turndown(replaceMentions(html, options))+ .replace(/\n{3,}/g, "\n\n")+ .trim();+ };+}++function paragraph(content: string, node: HTMLElement): string {+ const parent = node.parentNode?.nodeName;+ if (parent === "TH" || parent === "TD") {+ return node.previousElementSibling ? ` ${content}` : content;+ }+ if (isListItemContent(node) && !node.previousElementSibling) {+ return `\n${content}\n`;+ }+ return `\n\n${content}\n\n`;+}++function list(content: string, node: HTMLElement): string {+ if (isListItemContent(node) && !node.nextElementSibling) {+ return `\n${content}`;+ }+ return `\n\n${content}\n\n`;+}++function listItem(+ content: string,+ node: HTMLElement,+ options: TurndownService.Options,+): string {+ const parent = node.parentNode as HTMLElement | null;+ let marker = `${options.bulletListMarker ?? "-"} `;+ if (parent?.nodeName === "OL") {+ const start = Number(parent.getAttribute("start") ?? "1");+ const index = Array.prototype.indexOf.call(parent.children, node);+ marker = `${(Number.isFinite(start) ? start : 1) + index}. `;+ }++ const indent = " ".repeat(marker.length);+ const body = content+ .replace(/^\n+/, "")+ .replace(/\n+$/, "")+ .replace(/\n(?=[^\n])/g, `\n${indent}`);+ return `${marker}${checkbox(node)}${body}${node.nextSibling ? "\n" : ""}`;+}++function checkbox(node: HTMLElement): string {+ if (node.getAttribute("data-type") !== "taskItem") return "";+ return node.getAttribute("data-checked") === "true" ? "[x] " : "[ ] ";+}++function image(_content: string, node: HTMLElement): string {+ const src = node.getAttribute("src") ?? "";+ const alt = (node.getAttribute("alt") ?? "").trim();+ if (/^https?:\/\//i.test(src)) return ``;+ return alt;+}++function isListItemContent(node: HTMLElement): boolean {+ const parent = node.parentNode;+ if (!parent) return false;+ if (parent.nodeName === "LI") return true;+ return parent.nodeName === "DIV" && parent.parentNode?.nodeName === "LI";+}++function replaceMentions(html: string, options: HtmlToMarkdownOptions): string {+ return html.replace(+ MENTION_PATTERN,+ (_match, rawAttributes: string, inner: string) => {+ const attributes = new Map<string, string>();+ for (const [, name, double, single] of rawAttributes.matchAll(+ ATTRIBUTE_PATTERN,+ )) {+ if (name) attributes.set(name.toLowerCase(), double ?? single ?? "");+ }++ const label = attributes.get("label")?.trim();+ if (label) return `<span>@${label.replace(/[<>]/g, escapeChar)}</span>`;++ const id = attributes.get("entity_identifier");+ const name = id ? options.mentionName?.(id)?.trim() : undefined;+ if (name) return `<span>@${name.replace(/[&<>]/g, escapeChar)}</span>`;+ return inner;+ },+ );+}++function escapeChar(char: string): string {+ return char === "&" ? "&" : char === "<" ? "<" : ">";+}diff --git a/packages/importers/src/plane/index.ts b/packages/importers/src/plane/index.tsnew file mode 100644index 000000000..b430452e9--- /dev/null+++ b/packages/importers/src/plane/index.ts@@ -0,0 +1,2 @@+export { connectPlane, type PlaneCredentials } from "./source.js";+export { parsePlaneUrl, type PlaneTarget } from "./url.js";diff --git a/packages/importers/src/plane/mapping.test.ts b/packages/importers/src/plane/mapping.test.tsnew file mode 100644index 000000000..612a6d6a9--- /dev/null+++ b/packages/importers/src/plane/mapping.test.ts@@ -0,0 +1,351 @@+import { describe, expect, it } from "vite-plus/test";+import type {+ PlaneComment,+ PlaneLabel,+ PlaneMember,+ PlaneState,+ PlaneWorkItem,+} from "./client.js";+import {+ MEMBERS_WARNING,+ mapColumns,+ mapPlaneProject,+ mapPriority,+ toHexColor,+ toPerson,+ uniqueById,+} from "./mapping.js";++const states: PlaneState[] = [+ { id: "s-done", name: "Done", group: "completed", sequence: 50000 },+ { id: "s-todo", name: "Todo", group: "unstarted", sequence: 25000 },+ { id: "s-cancel", name: "Cancelled", group: "cancelled", sequence: 60000 },+ { id: "s-review", name: "In Review", group: "started", sequence: 45000 },+ { id: "s-progress", name: "In Progress", group: "started", sequence: 35000 },+ { id: "s-backlog", name: "Backlog", group: "backlog", sequence: 15000 },+ { id: "s-triage", name: "Triage", group: "triage", sequence: 10 },+];++const members: PlaneMember[] = [+ {+ id: "u-jane",+ email: "[email protected]",+ display_name: "jane",+ first_name: "Jane",+ last_name: "Doe",+ },+ {+ id: "u-bob",+ email: "[email protected]",+ display_name: "bob",+ first_name: "",+ last_name: "",+ },+];++const labels: PlaneLabel[] = [+ { id: "l-bug", name: "Bug", color: "#FF0000" },+ { id: "l-ui", name: "UI", color: "" },+ { id: "l-unused", name: "Unused", color: "#00ff00" },+];++function item(+ overrides: Partial<PlaneWorkItem> & { id: string },+): PlaneWorkItem {+ return {+ name: overrides.id,+ description_html: "<p></p>",+ priority: "none",+ state: "s-todo",+ assignees: [],+ labels: [],+ parent: null,+ sort_order: 65535,+ ...overrides,+ };+}++function project(+ workItems: PlaneWorkItem[],+ options: {+ members?: PlaneMember[] | null;+ comments?: Map<string, PlaneComment[]>;+ } = {},+) {+ return mapPlaneProject({+ project: {+ id: "p1",+ name: " Website ",+ identifier: "WEB",+ description: "Marketing site",+ },+ states,+ labels,+ members: options.members === undefined ? members : options.members,+ workItems,+ comments: options.comments ?? new Map(),+ });+}++describe("mapColumns", () => {+ it("orders states by group then sequence and marks final groups", () => {+ expect(mapColumns(states)).toEqual([+ { key: "s-todo", name: "Todo", isFinal: false },+ { key: "s-progress", name: "In Progress", isFinal: false },+ { key: "s-review", name: "In Review", isFinal: false },+ { key: "s-done", name: "Done", isFinal: true },+ { key: "s-cancel", name: "Cancelled", isFinal: true },+ ]);+ });++ it("puts unknown groups last", () => {+ expect(+ mapColumns([+ { id: "x", name: "Mystery", group: "custom", sequence: 1 },+ { id: "a", name: "Todo", group: "unstarted", sequence: 2 },+ ]).map((column) => column.key),+ ).toEqual(["a", "x"]);+ });+});++describe("mapPriority", () => {+ it.each([+ ["urgent", "urgent"],+ ["high", "high"],+ ["medium", "medium"],+ ["low", "low"],+ ["none", "no-priority"],+ [null, "no-priority"],+ ["whatever", "no-priority"],+ ])("maps %s to %s", (input, expected) => {+ expect(mapPriority(input)).toBe(expected);+ });+});++describe("toHexColor", () => {+ it("normalizes hex colors and falls back to gray", () => {+ expect(toHexColor("#FF0000")).toBe("#ff0000");+ expect(toHexColor("0f0")).toBe("#00ff00");+ expect(toHexColor("")).toBe("#6b7280");+ expect(toHexColor(null)).toBe("#6b7280");+ expect(toHexColor("red")).toBe("#6b7280");+ });+});++describe("toPerson", () => {+ it("prefers the full name and falls back to the display name", () => {+ expect(toPerson(members[0] as PlaneMember)).toEqual({+ name: "Jane Doe",+ email: "[email protected]",+ });+ expect(toPerson(members[1] as PlaneMember)).toEqual({+ name: "bob",+ email: "[email protected]",+ });+ });+});++describe("uniqueById", () => {+ it("drops work items repeated across pages", () => {+ expect(+ uniqueById([{ id: "a" }, { id: "b" }, { id: "a" }]).map((x) => x.id),+ ).toEqual(["a", "b"]);+ });+});++describe("mapPlaneProject", () => {+ it("orders tasks by column then sort order and maps fields", () => {+ const result = project([+ item({ id: "done", state: "s-done", sort_order: 1 }),+ item({ id: "todo-b", state: "s-todo", sort_order: 200 }),+ item({+ id: "todo-a",+ name: " Write copy ",+ state: "s-todo",+ sort_order: 100,+ priority: "high",+ description_html: "<h2>Plan</h2><ul><li><p>draft</p></li></ul>",+ start_date: "2026-01-05",+ target_date: "2026-01-09",+ created_at: "2026-01-01T10:00:00.000000Z",+ sequence_id: 12,+ }),+ item({ id: "stateless", state: null }),+ item({ id: "backlog", state: "s-backlog" }),+ item({ id: "old", state: "s-done", archived_at: "2026-02-01T00:00:00Z" }),+ ]);++ expect(result.name).toBe("Website");+ expect(result.key).toBe("WEB");+ expect(result.description).toBe("Marketing site");+ expect(result.tasks.map((task) => task.key)).toEqual([+ "todo-a",+ "todo-b",+ "done",+ "old",+ "stateless",+ "backlog",+ ]);+ expect(+ result.tasks.find((task) => task.key === "backlog")?.columnKey,+ ).toBeNull();+ expect(result.tasks[0]).toEqual({+ key: "todo-a",+ number: 12,+ columnKey: "s-todo",+ title: "Write copy",+ description: "## Plan\n\n- draft",+ priority: "high",+ startDate: "2026-01-05T00:00:00.000Z",+ dueDate: "2026-01-09T00:00:00.000Z",+ createdAt: "2026-01-01T10:00:00.000Z",+ labelKeys: [],+ comments: [],+ });+ const byKey = (key: string) =>+ result.tasks.find((task) => task.key === key);+ expect(byKey("done")?.number).toBeUndefined();+ expect(byKey("old")?.archived).toBe(true);+ expect(byKey("todo-a")?.archived).toBeUndefined();+ expect(byKey("stateless")?.columnKey).toBeNull();+ });++ it("keeps the first assignee and counts work items with more", () => {+ const result = project([+ item({ id: "a", assignees: ["u-jane", "u-bob"] }),+ item({ id: "b", assignees: ["u-bob", "u-jane", "u-x"] }),+ item({ id: "c", assignees: ["u-unknown"] }),+ item({ id: "d", assignees: ["u-bob"] }),+ ]);++ expect(result.tasks.map((task) => task.assignee)).toEqual([+ { name: "Jane Doe", email: "[email protected]" },+ { name: "bob", email: "[email protected]" },+ undefined,+ { name: "bob", email: "[email protected]" },+ ]);+ expect(result.warnings).toContain(+ "2 work items have more than one assignee. Kaneo keeps one assignee per task, so only the first was assigned.",+ );+ });++ it("uses expanded assignees when the member list is unavailable", () => {+ const result = project(+ [+ item({+ id: "a",+ assignees: [+ {+ id: "u-z",+ display_name: "zed",+ first_name: "Zed",+ last_name: "",+ },+ ],+ }),+ ],+ { members: null },+ );+ expect(result.tasks[0]?.assignee).toEqual({ name: "Zed" });+ expect(result.warnings).toContain(MEMBERS_WARNING);+ });++ it("only includes labels used by tasks, with hex colors", () => {+ const result = project([+ item({ id: "a", labels: ["l-ui", "l-bug", "l-missing", "l-ui"] }),+ ]);+ expect(result.tasks[0]?.labelKeys).toEqual(["l-ui", "l-bug"]);+ expect(result.labels).toEqual([+ { key: "l-bug", name: "Bug", color: "#ff0000" },+ { key: "l-ui", name: "UI", color: "#6b7280" },+ ]);+ });++ it("turns parents in the project into subtask relations", () => {+ const result = project([+ item({ id: "parent" }),+ item({ id: "child", parent: "parent" }),+ item({ id: "orphan", parent: "elsewhere" }),+ item({ id: "self", parent: "self" }),+ ]);+ expect(result.relations).toEqual([+ { sourceKey: "parent", targetKey: "child", type: "subtask" },+ ]);+ });++ it("maps comments oldest first with Markdown bodies and authors", () => {+ const comments = new Map<string, PlaneComment[]>([+ [+ "a",+ [+ {+ id: "c2",+ comment_html: "<p>Second <strong>reply</strong></p>",+ created_at: "2026-03-02T09:00:00Z",+ actor: { id: "u-jane", display_name: "jane" },+ },+ {+ id: "c1",+ comment_html:+ '<p>First, cc <mention-component entity_identifier="u-bob" entity_name="user_mention"></mention-component></p>',+ created_at: "2026-03-01T09:00:00Z",+ actor: "u-bob",+ },+ {+ id: "c3",+ comment_html: "<p></p>",+ created_at: "2026-03-03T09:00:00Z",+ actor: "u-bob",+ },+ {+ id: "c4",+ comment_html: "<p>From a guest</p>",+ created_at: "2026-03-04T09:00:00Z",+ actor: {+ id: "u-guest",+ display_name: "",+ first_name: "",+ last_name: "",+ },+ },+ ],+ ],+ ]);++ const result = project([item({ id: "a" })], { comments });+ expect(result.tasks[0]?.comments).toEqual([+ {+ author: { name: "bob", email: "[email protected]" },+ body: "First, cc @bob",+ createdAt: "2026-03-01T09:00:00.000Z",+ },+ {+ author: { name: "Jane Doe", email: "[email protected]" },+ body: "Second **reply**",+ createdAt: "2026-03-02T09:00:00.000Z",+ },+ {+ author: { name: "Plane user" },+ body: "From a guest",+ createdAt: "2026-03-04T09:00:00.000Z",+ },+ ]);+ });++ it("has no warnings when nothing was dropped", () => {+ const result = project([item({ id: "a", assignees: ["u-jane"] })]);+ expect(result.warnings).toEqual([]);+ });++ it("leaves the key out when the project has no identifier", () => {+ const result = mapPlaneProject({+ project: { id: "p1", name: "Website", identifier: " " },+ states,+ labels,+ members,+ workItems: [],+ comments: new Map(),+ });+ expect(result).not.toHaveProperty("key");+ });+});diff --git a/packages/importers/src/plane/mapping.ts b/packages/importers/src/plane/mapping.tsnew file mode 100644index 000000000..d0c1dc29a--- /dev/null+++ b/packages/importers/src/plane/mapping.ts@@ -0,0 +1,288 @@+import { toIsoDate } from "../markdown.js";+import type {+ ImportedColumn,+ ImportedComment,+ ImportedLabel,+ ImportedPerson,+ ImportedPriority,+ ImportedProject,+ ImportedRelation,+ ImportedTask,+} from "../types.js";+import type {+ PlaneComment,+ PlaneLabel,+ PlaneMember,+ PlaneProject,+ PlaneState,+ PlaneUser,+ PlaneWorkItem,+} from "./client.js";+import { createHtmlToMarkdown, type HtmlToMarkdown } from "./html.js";++export const STATE_GROUP_ORDER = [+ "triage",+ "backlog",+ "unstarted",+ "started",+ "completed",+ "cancelled",+];++export const FINAL_STATE_GROUPS = new Set(["completed", "cancelled"]);++export const FALLBACK_LABEL_COLOR = "#6b7280";++export const MEMBERS_WARNING =+ "Plane did not share the project member list with this token, so some assignee emails may be missing.";++const PRIORITIES: Record<string, ImportedPriority> = {+ urgent: "urgent",+ high: "high",+ medium: "medium",+ low: "low",+ none: "no-priority",+};++export type PlaneProjectData = {+ project: PlaneProject;+ states: PlaneState[];+ labels: PlaneLabel[];+ members: PlaneMember[] | null;+ workItems: PlaneWorkItem[];+ comments: Map<string, PlaneComment[]>;+};++export function orderStates(states: PlaneState[]): PlaneState[] {+ return [...states].sort(+ (a, b) =>+ groupRank(a.group) - groupRank(b.group) ||+ (a.sequence ?? 0) - (b.sequence ?? 0),+ );+}++const BACKLOG_STATE_GROUPS = new Set(["triage", "backlog"]);++export function mapColumns(states: PlaneState[]): ImportedColumn[] {+ return orderStates(states)+ .filter(+ (state) => !BACKLOG_STATE_GROUPS.has(state.group?.toLowerCase() ?? ""),+ )+ .map((state) => ({+ key: state.id,+ name: state.name?.trim() || "Untitled",+ isFinal: FINAL_STATE_GROUPS.has(state.group?.toLowerCase() ?? ""),+ }));+}++export function mapPriority(+ value: string | null | undefined,+): ImportedPriority {+ return PRIORITIES[value?.toLowerCase() ?? ""] ?? "no-priority";+}++export function toHexColor(value: string | null | undefined): string {+ const hex = value?.trim().replace(/^#/, "").toLowerCase() ?? "";+ if (/^[0-9a-f]{6}$/.test(hex)) return `#${hex}`;+ if (/^[0-9a-f]{3}$/.test(hex)) {+ return `#${[...hex].map((char) => char + char).join("")}`;+ }+ return FALLBACK_LABEL_COLOR;+}++export function toPlaneUser(member: PlaneMember): PlaneUser {+ return member.member && typeof member.member === "object"+ ? member.member+ : member;+}++export function toPerson(user: PlaneUser): ImportedPerson {+ const fullName = [user.first_name, user.last_name]+ .map((part) => part?.trim())+ .filter(Boolean)+ .join(" ");+ const name = fullName || user.display_name?.trim() || undefined;+ const email = user.email?.trim() || undefined;+ return { ...(name ? { name } : {}), ...(email ? { email } : {}) };+}++export function uniqueById<T extends { id: string }>(items: T[]): T[] {+ return [...new Map(items.map((item) => [item.id, item])).values()];+}++export function sortWorkItems(+ items: PlaneWorkItem[],+ columns: ImportedColumn[],+): PlaneWorkItem[] {+ const rank = new Map(columns.map((column, index) => [column.key, index]));+ const columnRank = (item: PlaneWorkItem) =>+ (item.state ? rank.get(item.state) : undefined) ?? columns.length;+ return [...items].sort(+ (a, b) =>+ columnRank(a) - columnRank(b) ||+ (a.sort_order ?? 0) - (b.sort_order ?? 0) ||+ (a.sequence_id ?? 0) - (b.sequence_id ?? 0),+ );+}++export function mapPlaneProject(data: PlaneProjectData): ImportedProject {+ const usersById = new Map<string, PlaneUser>();+ for (const member of data.members ?? []) {+ const user = toPlaneUser(member);+ if (user?.id) usersById.set(user.id, user);+ }+ const toMarkdown = createHtmlToMarkdown({+ mentionName: (id) => {+ const user = usersById.get(id);+ return user+ ? user.display_name?.trim() || toPerson(user).name+ : undefined;+ },+ });++ const columns = mapColumns(data.states);+ const columnKeys = new Set(columns.map((column) => column.key));+ const labelsById = new Map(data.labels.map((label) => [label.id, label]));+ const items = sortWorkItems(data.workItems, columns);+ const itemIds = new Set(items.map((item) => item.id));+ const usedLabelIds = new Set<string>();+ let multipleAssignees = 0;++ const tasks: ImportedTask[] = items.map((item) => {+ const assignees = item.assignees ?? [];+ if (assignees.length > 1) multipleAssignees++;+ const assignee = resolveAssignee(assignees[0], usersById);++ const labelKeys = [+ ...new Set((item.labels ?? []).filter((id) => labelsById.has(id))),+ ];+ for (const id of labelKeys) usedLabelIds.add(id);++ const startDate = toIsoDate(item.start_date);+ const dueDate = toIsoDate(item.target_date);+ const createdAt = toIsoDate(item.created_at);++ return {+ key: item.id,+ ...(typeof item.sequence_id === "number"+ ? { number: item.sequence_id }+ : {}),+ columnKey: item.state && columnKeys.has(item.state) ? item.state : null,+ ...(item.archived_at ? { archived: true } : {}),+ title: item.name?.trim() || "Untitled",+ description: toMarkdown(item.description_html),+ priority: mapPriority(item.priority),+ ...(startDate ? { startDate } : {}),+ ...(dueDate ? { dueDate } : {}),+ ...(createdAt ? { createdAt } : {}),+ ...(assignee ? { assignee } : {}),+ labelKeys,+ comments: mapComments(+ data.comments.get(item.id) ?? [],+ usersById,+ toMarkdown,+ ),+ };+ });++ const labels: ImportedLabel[] = data.labels+ .filter((label) => usedLabelIds.has(label.id))+ .map((label) => ({+ key: label.id,+ name: label.name?.trim() || "Label",+ color: toHexColor(label.color),+ }));++ const relations: ImportedRelation[] = items+ .filter(+ (item) =>+ item.parent && item.parent !== item.id && itemIds.has(item.parent),+ )+ .map((item) => ({+ sourceKey: item.parent as string,+ targetKey: item.id,+ type: "subtask",+ }));++ const warnings: string[] = [];+ if (multipleAssignees > 0) {+ warnings.push(+ `${multipleAssignees} work ${multipleAssignees === 1 ? "item has" : "items have"} more than one assignee. Kaneo keeps one assignee per task, so only the first was assigned.`,+ );+ }+ if (data.members === null) warnings.push(MEMBERS_WARNING);++ const description = data.project.description?.trim();+ const key = data.project.identifier?.trim();+ return {+ name: data.project.name?.trim() || "Plane project",+ ...(key ? { key } : {}),+ ...(description ? { description } : {}),+ columns,+ labels,+ tasks,+ relations,+ warnings,+ };+}++function resolveAssignee(+ assignee: string | PlaneUser | undefined,+ usersById: Map<string, PlaneUser>,+): ImportedPerson | undefined {+ if (!assignee) return undefined;+ const user =+ typeof assignee === "string"+ ? usersById.get(assignee)+ : (usersById.get(assignee.id) ?? assignee);+ if (!user) return undefined;+ const person = toPerson(user);+ return person.name || person.email ? person : undefined;+}++function mapComments(+ comments: PlaneComment[],+ usersById: Map<string, PlaneUser>,+ toMarkdown: HtmlToMarkdown,+): ImportedComment[] {+ const mapped: ImportedComment[] = [];+ for (const comment of comments) {+ const body =+ comment.comment_html != null+ ? toMarkdown(comment.comment_html)+ : (comment.comment_stripped?.trim() ?? "");+ if (!body) continue;++ const actor = commentActor(comment, usersById);+ const person = actor ? toPerson(actor) : {};+ const createdAt = toIsoDate(comment.created_at);+ mapped.push({+ author: {+ name: person.name ?? person.email ?? "Plane user",+ ...(person.email ? { email: person.email } : {}),+ },+ body,+ ...(createdAt ? { createdAt } : {}),+ });+ }+ return mapped.sort((a, b) =>+ (a.createdAt ?? "").localeCompare(b.createdAt ?? ""),+ );+}++function commentActor(+ comment: PlaneComment,+ usersById: Map<string, PlaneUser>,+): PlaneUser | undefined {+ const actor =+ typeof comment.actor === "object" && comment.actor+ ? comment.actor+ : (comment.actor_detail ?? undefined);+ const id = typeof comment.actor === "string" ? comment.actor : actor?.id;+ return (id ? usersById.get(id) : undefined) ?? actor;+}++function groupRank(group: string | null | undefined): number {+ const index = STATE_GROUP_ORDER.indexOf(group?.toLowerCase() ?? "");+ return index === -1 ? STATE_GROUP_ORDER.length : index;+}diff --git a/packages/importers/src/plane/pacing.test.ts b/packages/importers/src/plane/pacing.test.tsnew file mode 100644index 000000000..591fd73e4--- /dev/null+++ b/packages/importers/src/plane/pacing.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it, vi } from "vite-plus/test";+import { createPacedFetch, MAX_PACE_MS, pauseUntil } from "./pacing.js";++const NOW = 1_700_000_000_000;++function respond(headers: Record<string, string>) {+ return new Response("{}", { status: 200, headers });+}++function setup(responses: Response[]) {+ let clock = NOW;+ const sleep = vi.fn(async (ms: number) => {+ clock += ms;+ });+ const inner = vi.fn(async () => responses.shift() ?? respond({}));+ const paced = createPacedFetch(inner, { now: () => clock, sleep });+ return { paced, inner, sleep, advance: (ms: number) => (clock += ms) };+}++describe("pauseUntil", () => {+ it("returns the reset time when one or no requests remain", () => {+ const reset = String(NOW / 1000 + 30);+ for (const remaining of ["0", "1"]) {+ const headers = new Headers({+ "X-RateLimit-Remaining": remaining,+ "X-RateLimit-Reset": reset,+ });+ expect(pauseUntil(headers, NOW)).toBe(NOW + 30_000);+ }+ });++ it("does not pause while requests remain or headers are missing", () => {+ const reset = String(NOW / 1000 + 30);+ expect(+ pauseUntil(+ new Headers({+ "X-RateLimit-Remaining": "2",+ "X-RateLimit-Reset": reset,+ }),+ NOW,+ ),+ ).toBe(0);+ expect(pauseUntil(new Headers({ "X-RateLimit-Remaining": "0" }), NOW)).toBe(+ 0,+ );+ expect(pauseUntil(new Headers({ "X-RateLimit-Reset": reset }), NOW)).toBe(+ 0,+ );+ expect(+ pauseUntil(+ new Headers({+ "X-RateLimit-Remaining": "",+ "X-RateLimit-Reset": reset,+ }),+ NOW,+ ),+ ).toBe(0);+ });++ it("ignores reset times in the past and accepts relative seconds", () => {+ expect(+ pauseUntil(+ new Headers({+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": String(NOW / 1000 - 5),+ }),+ NOW,+ ),+ ).toBe(0);+ expect(+ pauseUntil(+ new Headers({+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": "12",+ }),+ NOW,+ ),+ ).toBe(NOW + 12_000);+ });+});++describe("createPacedFetch", () => {+ it("waits until the reset before the next request when the budget runs out", async () => {+ const { paced, inner, sleep } = setup([+ respond({+ "X-RateLimit-Remaining": "1",+ "X-RateLimit-Reset": String(NOW / 1000 + 20),+ }),+ respond({+ "X-RateLimit-Remaining": "59",+ "X-RateLimit-Reset": String(NOW / 1000 + 80),+ }),+ ]);++ await paced("https://api.plane.so/a");+ expect(sleep).not.toHaveBeenCalled();++ await paced("https://api.plane.so/b");+ expect(sleep).toHaveBeenCalledTimes(1);+ expect(sleep.mock.calls[0]?.[0]).toBe(20_000);++ await paced("https://api.plane.so/c");+ expect(sleep).toHaveBeenCalledTimes(1);+ expect(inner).toHaveBeenCalledTimes(3);+ });++ it("skips the wait when the reset already passed", async () => {+ const { paced, sleep, advance } = setup([+ respond({+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": String(NOW / 1000 + 5),+ }),+ ]);++ await paced("https://api.plane.so/a");+ advance(6_000);+ await paced("https://api.plane.so/b");+ expect(sleep).not.toHaveBeenCalled();+ });++ it("caps the wait and passes the request signal to sleep", async () => {+ const { paced, sleep } = setup([+ respond({+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": String(NOW / 1000 + 600),+ }),+ ]);+ const controller = new AbortController();++ await paced("https://api.plane.so/a");+ await paced("https://api.plane.so/b", { signal: controller.signal });+ expect(sleep).toHaveBeenCalledWith(MAX_PACE_MS, controller.signal);+ });++ it("stops waiting when the request is aborted", async () => {+ const inner = vi.fn(async () =>+ respond({+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": String(Math.floor(Date.now() / 1000) + 30),+ }),+ );+ const paced = createPacedFetch(inner);+ await paced("https://api.plane.so/a");++ const controller = new AbortController();+ const pending = paced("https://api.plane.so/b", {+ signal: controller.signal,+ });+ controller.abort(new Error("stopped"));+ await expect(pending).rejects.toThrow("stopped");+ expect(inner).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/importers/src/plane/pacing.ts b/packages/importers/src/plane/pacing.tsnew file mode 100644index 000000000..a52b34de8--- /dev/null+++ b/packages/importers/src/plane/pacing.ts@@ -0,0 +1,61 @@+import type { FetchLike } from "../types.js";++export const MAX_PACE_MS = 60_000;++export type PacingOptions = {+ now?: () => number;+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;+};++export function createPacedFetch(+ fetchImpl: FetchLike,+ options: PacingOptions = {},+): FetchLike {+ const now = options.now ?? Date.now;+ const sleep = options.sleep ?? sleepFor;+ let resumeAt = 0;++ return async (input, init) => {+ const delay = Math.min(MAX_PACE_MS, resumeAt - now());+ if (delay > 0) await sleep(delay, init?.signal ?? undefined);+ const res = await fetchImpl(input, init);+ resumeAt = pauseUntil(res.headers, now());+ return res;+ };+}++export function pauseUntil(headers: Headers, nowMs: number): number {+ const remaining = headerNumber(headers.get("x-ratelimit-remaining"));+ const reset = headerNumber(headers.get("x-ratelimit-reset"));+ if (remaining === undefined || reset === undefined || remaining > 1) {+ return 0;+ }++ const resetMs =+ reset > 1e12 ? reset : reset > 1e9 ? reset * 1000 : nowMs + reset * 1000;+ return resetMs > nowMs ? resetMs : 0;+}++function headerNumber(value: string | null): number | undefined {+ if (value === null || !value.trim()) return undefined;+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : undefined;+}++function sleepFor(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(signal.reason);+ return;+ }+ const timer = setTimeout(() => {+ signal?.removeEventListener("abort", onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(timer);+ reject(signal?.reason);+ }+ signal?.addEventListener("abort", onAbort, { once: true });+ });+}diff --git a/packages/importers/src/plane/source.test.ts b/packages/importers/src/plane/source.test.tsnew file mode 100644index 000000000..b20a0bbdb--- /dev/null+++ b/packages/importers/src/plane/source.test.ts@@ -0,0 +1,543 @@+import { describe, expect, it } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import { connectPlane } from "./index.js";+import { REJECTED_KEY_MESSAGE } from "./source.js";++type Route = (url: URL) => unknown;+type Call = { url: URL; headers: Headers };++const WS = "/api/v1/workspaces/acme";+const PROJECT = `${WS}/projects/p1`;+const API_KEY = "plane_api_secret";++class Status {+ constructor(+ readonly status: number,+ readonly body: unknown = { detail: "nope" },+ readonly headers: Record<string, string> = {},+ ) {}+}++function fakePlane(routes: Record<string, Route | unknown>) {+ const calls: Call[] = [];+ const fetch: FetchLike = async (input, init) => {+ const url = new URL(input);+ calls.push({ url, headers: new Headers(init?.headers) });+ const route = routes[url.pathname];+ const value = typeof route === "function" ? (route as Route)(url) : route;+ if (value === undefined) return json(404, { detail: "Not found." });+ if (value instanceof Status) {+ return typeof value.body === "string"+ ? new Response(value.body, {+ status: value.status,+ headers: value.headers,+ })+ : json(value.status, value.body, value.headers);+ }+ return json(200, value);+ };+ return { fetch, calls, paths: () => calls.map((call) => call.url.pathname) };+}++function json(+ status: number,+ body: unknown,+ headers: Record<string, string> = {},+) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json", ...headers },+ });+}++function page<T>(results: T[], next: string | null = null) {+ return {+ results,+ next_cursor: next ?? "100:1:0",+ next_page_results: next !== null,+ total_results: undefined as number | undefined,+ };+}++const me = { id: "u-me", email: "[email protected]", display_name: "me" };++const projects = [+ {+ id: "p1",+ name: "Website",+ identifier: "WEB",+ description: "Marketing site",+ archived_at: null,+ },+ {+ id: "p2",+ name: "Old",+ identifier: "OLD",+ archived_at: "2025-01-01T00:00:00Z",+ },+];++const states = [+ {+ id: "s-done",+ name: "Done",+ group: "completed",+ sequence: 3,+ color: "#00ff00",+ },+ {+ id: "s-todo",+ name: "Todo",+ group: "unstarted",+ sequence: 1,+ color: "#cccccc",+ },+ {+ id: "s-doing",+ name: "Doing",+ group: "started",+ sequence: 2,+ color: "#0000ff",+ },+];++const labels = [+ { id: "l-bug", name: "Bug", color: "#E11D48", parent: null },+ { id: "l-idle", name: "Idle", color: "#000000", parent: null },+];++const members = [+ {+ id: "u-jane",+ email: "[email protected]",+ display_name: "jane",+ first_name: "Jane",+ last_name: "Doe",+ },+ {+ id: "u-bob",+ email: "[email protected]",+ display_name: "bob",+ first_name: "Bob",+ last_name: "Ray",+ },+];++function workItem(id: string, overrides: Record<string, unknown> = {}) {+ return {+ id,+ name: `Item ${id}`,+ description_html: "<p></p>",+ priority: "none",+ state: "s-todo",+ assignees: [],+ labels: [],+ parent: null,+ sort_order: 1000,+ sequence_id: 1,+ created_at: "2026-01-01T00:00:00Z",+ archived_at: null,+ ...overrides,+ };+}++function baseRoutes(extra: Record<string, Route | unknown> = {}) {+ return {+ "/api/v1/users/me/": me,+ [`${WS}/projects/`]: page(projects),+ [`${PROJECT}/states/`]: page(states),+ [`${PROJECT}/labels/`]: labels,+ [`${PROJECT}/members/`]: members,+ ...extra,+ };+}++describe("connectPlane", () => {+ it("authenticates with the X-API-Key header against api.plane.so", async () => {+ const plane = fakePlane(baseRoutes());+ await connectPlane(+ {+ url: "https://app.plane.so/acme/projects/p1/issues",+ apiKey: ` ${API_KEY} `,+ },+ { fetch: plane.fetch },+ );++ expect(plane.paths()).toEqual(["/api/v1/users/me/", `${WS}/projects/`]);+ for (const call of plane.calls) {+ expect(call.url.origin).toBe("https://api.plane.so");+ expect(call.headers.get("x-api-key")).toBe(API_KEY);+ expect(call.headers.get("authorization")).toBeNull();+ expect(call.url.href).not.toContain(API_KEY);+ }+ expect(plane.calls[1]?.url.searchParams.get("per_page")).toBe("100");+ });++ it("talks to a self-hosted origin directly", async () => {+ const plane = fakePlane(baseRoutes());+ await connectPlane(+ { url: "plane.example.com/acme/", apiKey: API_KEY },+ { fetch: plane.fetch },+ );+ expect(plane.calls[0]?.url.origin).toBe("https://plane.example.com");+ });++ it.each([401, 403])(+ "explains a rejected API key (HTTP %i)",+ async (status) => {+ const plane = fakePlane(+ baseRoutes({ "/api/v1/users/me/": new Status(status) }),+ );+ const error = await connectPlane(+ { url: "https://app.plane.so/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ ).catch((caught: unknown) => caught as Error);++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe(REJECTED_KEY_MESSAGE);+ expect((error as Error).message).not.toContain(API_KEY);+ },+ );++ it.each([403, 404])(+ "reports an unknown workspace (HTTP %i)",+ async (status) => {+ const plane = fakePlane(+ baseRoutes({ [`${WS}/projects/`]: new Status(status) }),+ );+ await expect(+ connectPlane(+ { url: "https://app.plane.so/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ ),+ ).rejects.toThrow(+ 'Plane could not find the workspace "acme" for this token.',+ );+ },+ );++ it("rejects servers that are not Plane", async () => {+ const plane = fakePlane(+ baseRoutes({+ "/api/v1/users/me/": new Status(200, "<html>hello</html>", {+ "Content-Type": "text/html",+ }),+ }),+ );+ await expect(+ connectPlane(+ { url: "https://example.com/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ ),+ ).rejects.toThrow(+ "This address does not look like a Plane server. Check the workspace URL.",+ );+ });++ it("requires a workspace slug and an API key before calling Plane", async () => {+ const plane = fakePlane(baseRoutes());+ await expect(+ connectPlane(+ { url: "https://app.plane.so", apiKey: API_KEY },+ { fetch: plane.fetch },+ ),+ ).rejects.toThrow(+ "Add your Plane workspace URL, for example https://app.plane.so/your-workspace",+ );+ await expect(+ connectPlane(+ { url: "https://app.plane.so/acme", apiKey: " " },+ { fetch: plane.fetch },+ ),+ ).rejects.toThrow("personal access token");+ expect(plane.calls).toHaveLength(0);+ });+});++describe("listProjects", () => {+ it("reuses the connect request, skips archived projects and shows the identifier", async () => {+ const plane = fakePlane(baseRoutes());+ const source = await connectPlane(+ { url: "https://app.plane.so/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ );++ expect(await source.listProjects()).toEqual([+ { id: "p1", name: "Website", detail: "WEB" },+ ]);+ expect(plane.calls).toHaveLength(2);++ await source.listProjects();+ expect(plane.calls).toHaveLength(3);+ });++ it("accepts the bare project list from older Plane versions", async () => {+ const plane = fakePlane(baseRoutes({ [`${WS}/projects/`]: projects }));+ const source = await connectPlane(+ { url: "https://plane.example.com/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ );+ expect((await source.listProjects()).map((project) => project.id)).toEqual([+ "p1",+ ]);+ });+});++describe("readProject", () => {+ it("reads every page of work items and maps the project", async () => {+ const plane = fakePlane(+ baseRoutes({+ [`${PROJECT}/work-items/`]: (url: URL) => {+ const cursor = url.searchParams.get("cursor");+ if (!cursor) {+ return {+ ...page(+ [+ workItem("w-done", {+ state: "s-done",+ priority: "urgent",+ sort_order: 5,+ sequence_id: 3,+ }),+ workItem("w-parent", {+ priority: "medium",+ sort_order: 2,+ sequence_id: 1,+ assignees: ["u-jane", "u-bob"],+ labels: ["l-bug"],+ description_html:+ '<p>Spec</p><ul data-type="taskList"><li data-checked="true" data-type="taskItem"><label><input type="checkbox" checked="checked"><span></span></label><div><p>outline</p></div></li></ul>',+ target_date: "2026-04-01",+ }),+ ],+ "100:1:0",+ ),+ total_results: 3,+ };+ }+ expect(cursor).toBe("100:1:0");+ return {+ ...page([+ workItem("w-child", {+ state: "s-doing",+ parent: "w-parent",+ assignees: ["u-bob"],+ sequence_id: 2,+ }),+ ]),+ total_results: 3,+ };+ },+ }),+ );+ const source = await connectPlane(+ { url: "https://app.plane.so/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ );+ const progress: string[] = [];+ const result = await source.readProject("p1", {+ includeComments: false,+ onProgress: (message) => progress.push(message),+ });++ const itemCalls = plane.calls.filter((call) =>+ call.url.pathname.endsWith("/work-items/"),+ );+ expect(itemCalls).toHaveLength(2);+ const fields =+ itemCalls[0]?.url.searchParams.get("fields")?.split(",") ?? [];+ expect(fields).toEqual(+ expect.arrayContaining([+ "description_html",+ "assignees",+ "labels",+ "parent",+ "state",+ "sequence_id",+ ]),+ );+ expect(fields).not.toContain("description_binary");+ expect(itemCalls[0]?.url.searchParams.get("per_page")).toBe("100");+ expect(itemCalls[0]?.url.searchParams.get("expand")).toBeNull();+ expect(plane.paths()).not.toContain(`${PROJECT}/`);++ expect(progress).toEqual([+ "Reading states, labels and members",+ "Reading work items (2 of 3)",+ "Reading work items (3 of 3)",+ ]);++ expect(result.name).toBe("Website");+ expect(result.key).toBe("WEB");+ expect(result.description).toBe("Marketing site");+ expect(+ result.columns.map((column) => [column.key, column.isFinal]),+ ).toEqual([+ ["s-todo", false],+ ["s-doing", false],+ ["s-done", true],+ ]);+ expect(+ result.tasks.map((task) => [task.key, task.columnKey, task.priority]),+ ).toEqual([+ ["w-parent", "s-todo", "medium"],+ ["w-child", "s-doing", "no-priority"],+ ["w-done", "s-done", "urgent"],+ ]);+ expect(result.tasks.map((task) => task.number)).toEqual([1, 2, 3]);+ expect(result.tasks[0]).toMatchObject({+ title: "Item w-parent",+ description: "Spec\n\n- [x] outline",+ dueDate: "2026-04-01T00:00:00.000Z",+ assignee: { name: "Jane Doe", email: "[email protected]" },+ labelKeys: ["l-bug"],+ comments: [],+ });+ expect(result.labels).toEqual([+ { key: "l-bug", name: "Bug", color: "#e11d48" },+ ]);+ expect(result.relations).toEqual([+ { sourceKey: "w-parent", targetKey: "w-child", type: "subtask" },+ ]);+ expect(result.warnings).toEqual([+ "1 work item has more than one assignee. Kaneo keeps one assignee per task, so only the first was assigned.",+ ]);+ });++ it("falls back to /issues/ on older self-hosted builds and reads comments", async () => {+ const plane = fakePlane(+ baseRoutes({+ [`${PROJECT}/issues/`]: page([+ workItem("w1"),+ workItem("w2", { sort_order: 2000 }),+ workItem("w3", { sort_order: 3000 }),+ ]),+ [`${PROJECT}/issues/w1/comments/`]: (url: URL) =>+ url.searchParams.get("cursor")+ ? page([+ {+ id: "c2",+ comment_html: "<p>Later</p>",+ created_at: "2026-02-02T00:00:00Z",+ actor: {+ id: "u-jane",+ display_name: "jane",+ first_name: "Jane",+ last_name: "Doe",+ },+ },+ ])+ : page(+ [+ {+ id: "c1",+ comment_html: "<p>Looks <em>good</em></p>",+ created_at: "2026-02-01T00:00:00Z",+ actor: {+ id: "u-bob",+ display_name: "bob",+ first_name: "Bob",+ last_name: "Ray",+ },+ },+ ],+ "100:1:0",+ ),+ [`${PROJECT}/issues/w2/comments/`]: [],+ }),+ );+ const source = await connectPlane(+ { url: "https://plane.example.com/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ );+ const progress: string[] = [];+ const result = await source.readProject("p1", {+ includeComments: true,+ onProgress: (message) => progress.push(message),+ });++ expect(+ plane.paths().filter((path) => path.includes("/work-items/")),+ ).toEqual([`${PROJECT}/work-items/`]);+ const commentCalls = plane.calls.filter((call) =>+ call.url.pathname.endsWith("/comments/"),+ );+ expect(commentCalls.map((call) => call.url.pathname)).toEqual([+ `${PROJECT}/issues/w1/comments/`,+ `${PROJECT}/issues/w1/comments/`,+ `${PROJECT}/issues/w2/comments/`,+ `${PROJECT}/issues/w3/comments/`,+ ]);+ expect(commentCalls[0]?.url.searchParams.get("expand")).toBe("actor");+ expect(progress).toContain("Reading comments (3 of 3)");++ expect(result.tasks.map((task) => task.key)).toEqual(["w1", "w2", "w3"]);+ expect(result.tasks[0]?.comments).toEqual([+ {+ author: { name: "Bob Ray", email: "[email protected]" },+ body: "Looks _good_",+ createdAt: "2026-02-01T00:00:00.000Z",+ },+ {+ author: { name: "Jane Doe", email: "[email protected]" },+ body: "Later",+ createdAt: "2026-02-02T00:00:00.000Z",+ },+ ]);+ expect(result.tasks[1]?.comments).toEqual([]);+ expect(result.tasks[2]?.comments).toEqual([]);+ });++ it("continues without the member list and expands assignees instead", async () => {+ const plane = fakePlane(+ baseRoutes({+ [`${PROJECT}/members/`]: new Status(403, {+ detail: "You do not have permission",+ }),+ [`${PROJECT}/work-items/`]: page([+ workItem("w1", {+ assignees: [+ {+ id: "u-jane",+ display_name: "jane",+ first_name: "Jane",+ last_name: "Doe",+ },+ ],+ }),+ ]),+ }),+ );+ const source = await connectPlane(+ { url: "https://app.plane.so/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ );+ const result = await source.readProject("p1", { includeComments: false });++ const itemCall = plane.calls.find((call) =>+ call.url.pathname.endsWith("/work-items/"),+ );+ expect(itemCall?.url.searchParams.get("expand")).toBe("assignees");+ expect(result.tasks[0]?.assignee).toEqual({ name: "Jane Doe" });+ expect(result.warnings).toContain(+ "Plane did not share the project member list with this token, so some assignee emails may be missing.",+ );+ });++ it("fetches project details when the project was not listed", async () => {+ const plane = fakePlane(+ baseRoutes({+ [`${WS}/projects/`]: page([]),+ [`${PROJECT}/`]: { id: "p1", name: "Hidden" },+ [`${PROJECT}/work-items/`]: page([]),+ }),+ );+ const source = await connectPlane(+ { url: "https://app.plane.so/acme", apiKey: API_KEY },+ { fetch: plane.fetch },+ );+ const result = await source.readProject("p1", { includeComments: false });+ expect(result.name).toBe("Hidden");+ expect(result.tasks).toEqual([]);+ });+});diff --git a/packages/importers/src/plane/source.ts b/packages/importers/src/plane/source.tsnew file mode 100644index 000000000..6a6e3c481--- /dev/null+++ b/packages/importers/src/plane/source.ts@@ -0,0 +1,178 @@+import { SourceHttpError } from "../http.js";+import type {+ ConnectOptions,+ FetchLike,+ ImportedProject,+ ImportSource,+ ReadProjectOptions,+ SourceProject,+} from "../types.js";+import { type PlaneComment, PlaneClient, type PlaneProject } from "./client.js";+import { mapPlaneProject, uniqueById } from "./mapping.js";+import { createPacedFetch } from "./pacing.js";+import { parsePlaneUrl } from "./url.js";++export type PlaneCredentials = {+ url: string;+ apiKey: string;+ workspaceSlug?: string;+};++export const REJECTED_KEY_MESSAGE =+ "Plane rejected the API key. Create a personal access token under Profile settings > Developer > Personal Access Tokens.";++const COMMENT_PROGRESS_STEP = 10;++export async function connectPlane(+ credentials: PlaneCredentials,+ options: ConnectOptions = {},+): Promise<ImportSource> {+ const apiKey = credentials.apiKey?.trim();+ if (!apiKey) {+ throw new Error(+ "Add a Plane personal access token from Profile settings > Developer > Personal Access Tokens.",+ );+ }+ const target = parsePlaneUrl(credentials.url, credentials.workspaceSlug);+ const baseFetch: FetchLike =+ options.fetch ?? ((input, init) => fetch(input, init));+ const client = new PlaneClient({+ baseUrl: target.apiBaseUrl,+ apiKey,+ workspaceSlug: target.workspaceSlug,+ fetch: createPacedFetch(baseFetch),+ signal: options.signal,+ });++ await verifyToken(client);+ let pending: PlaneProject[] | null = await verifyWorkspace(client);+ const projectsById = new Map(pending.map((project) => [project.id, project]));++ return {+ async listProjects(): Promise<SourceProject[]> {+ const projects = pending ?? (await client.listProjects());+ pending = null;+ for (const project of projects) projectsById.set(project.id, project);+ return projects+ .filter((project) => !project.archived_at)+ .map((project) => ({+ id: project.id,+ name: project.name,+ ...(project.identifier ? { detail: project.identifier } : {}),+ }));+ },++ readProject(projectId, readOptions) {+ return readPlaneProject(+ client.withSignal(readOptions.signal),+ projectId,+ projectsById.get(projectId),+ readOptions,+ );+ },+ };+}++async function verifyToken(client: PlaneClient): Promise<void> {+ let user: Awaited<ReturnType<PlaneClient["me"]>>;+ try {+ user = await client.me();+ } catch (error) {+ if (error instanceof SourceHttpError) {+ if (error.status === 401 || error.status === 403) {+ throw new Error(REJECTED_KEY_MESSAGE);+ }+ if (error.status === 404) throw notPlaneError();+ }+ throw error;+ }+ if (!user || typeof user !== "object" || typeof user.id !== "string") {+ throw notPlaneError();+ }+}++async function verifyWorkspace(client: PlaneClient): Promise<PlaneProject[]> {+ try {+ return await client.listProjects();+ } catch (error) {+ if (error instanceof SourceHttpError) {+ if (error.status === 401) throw new Error(REJECTED_KEY_MESSAGE);+ if (error.status === 403 || error.status === 404) {+ throw new Error(+ `Plane could not find the workspace "${client.workspaceSlug}" for this token.`,+ );+ }+ }+ throw error;+ }+}++function notPlaneError(): Error {+ return new Error(+ "This address does not look like a Plane server. Check the workspace URL.",+ );+}++async function readPlaneProject(+ client: PlaneClient,+ projectId: string,+ known: PlaneProject | undefined,+ options: ReadProjectOptions,+): Promise<ImportedProject> {+ const { onProgress } = options;+ onProgress?.("Reading states, labels and members");+ const project = known ?? (await client.getProject(projectId));+ const states = await client.listStates(projectId);+ const labels = await client.listLabels(projectId);+ const members = await unlessStatus(client.listMembers(projectId), [403, 404]);++ const listed = await client.listWorkItems(projectId, {+ expandAssignees: members === null,+ onPage: (loaded, total) =>+ onProgress?.(+ total === undefined+ ? `Reading work items (${loaded})`+ : `Reading work items (${loaded} of ${total})`,+ ),+ });+ const workItems = uniqueById(listed);++ const comments = new Map<string, PlaneComment[]>();+ if (options.includeComments) {+ const total = workItems.length;+ for (const [index, item] of workItems.entries()) {+ const itemComments = await unlessStatus(+ client.listComments(projectId, item.id),+ [404],+ );+ comments.set(item.id, itemComments ?? []);+ const done = index + 1;+ if (done % COMMENT_PROGRESS_STEP === 0 || done === total) {+ onProgress?.(`Reading comments (${done} of ${total})`);+ }+ }+ }++ return mapPlaneProject({+ project,+ states,+ labels,+ members,+ workItems,+ comments,+ });+}++async function unlessStatus<T>(+ request: Promise<T>,+ statuses: number[],+): Promise<T | null> {+ try {+ return await request;+ } catch (error) {+ if (error instanceof SourceHttpError && statuses.includes(error.status)) {+ return null;+ }+ throw error;+ }+}diff --git a/packages/importers/src/plane/turndown-plugin-gfm.d.ts b/packages/importers/src/plane/turndown-plugin-gfm.d.tsnew file mode 100644index 000000000..5b121d999--- /dev/null+++ b/packages/importers/src/plane/turndown-plugin-gfm.d.ts@@ -0,0 +1,5 @@+declare module "turndown-plugin-gfm" {+ import type TurndownService from "turndown";++ export function gfm(service: TurndownService): void;+}diff --git a/packages/importers/src/plane/url.test.ts b/packages/importers/src/plane/url.test.tsnew file mode 100644index 000000000..53ff87d67--- /dev/null+++ b/packages/importers/src/plane/url.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from "vite-plus/test";+import { MISSING_WORKSPACE_MESSAGE, parsePlaneUrl } from "./url.js";++describe("parsePlaneUrl", () => {+ it.each([+ ["https://app.plane.so/acme/projects/123/issues", "acme"],+ ["https://app.plane.so/acme/", "acme"],+ ["app.plane.so/acme", "acme"],+ [" APP.PLANE.SO/acme?tab=all#top ", "acme"],+ ["http://app.plane.so/acme/settings", "acme"],+ ["https://api.plane.so/api/v1/workspaces/acme/projects/", "acme"],+ ["https://plane.so/acme", "acme"],+ ])("maps the cloud URL %s to api.plane.so", (url, slug) => {+ expect(parsePlaneUrl(url)).toEqual({+ apiBaseUrl: "https://api.plane.so",+ workspaceSlug: slug,+ });+ });++ it.each([+ [+ "https://plane.example.com/acme/projects/1/issues/",+ "https://plane.example.com",+ "acme",+ ],+ ["plane.example.com/acme", "https://plane.example.com", "acme"],+ ["http://localhost:8080/my-team/", "http://localhost:8080", "my-team"],+ [+ "https://plane.example.com:8443/acme",+ "https://plane.example.com:8443",+ "acme",+ ],+ [+ "https://plane.example.com/api/v1/workspaces/ops/projects/",+ "https://plane.example.com",+ "ops",+ ],+ [+ "https://plane.example.com/caf%C3%A9",+ "https://plane.example.com",+ "café",+ ],+ ])("keeps the self-hosted origin for %s", (url, apiBaseUrl, slug) => {+ expect(parsePlaneUrl(url)).toEqual({ apiBaseUrl, workspaceSlug: slug });+ });++ it("prefers an explicit workspace slug", () => {+ expect(parsePlaneUrl("https://api.plane.so", " acme ")).toEqual({+ apiBaseUrl: "https://api.plane.so",+ workspaceSlug: "acme",+ });+ expect(+ parsePlaneUrl("https://plane.example.com/other/projects", "/acme/"),+ ).toEqual({+ apiBaseUrl: "https://plane.example.com",+ workspaceSlug: "acme",+ });+ });++ it("assumes Plane Cloud when only a slug is given", () => {+ expect(parsePlaneUrl("", "acme")).toEqual({+ apiBaseUrl: "https://api.plane.so",+ workspaceSlug: "acme",+ });+ });++ it.each([+ "https://api.plane.so",+ "https://app.plane.so",+ "https://plane.example.com",+ "https://plane.example.com/god-mode/general",+ "https://app.plane.so/profile/activity",+ "https://app.plane.so/accounts/forgot-password",+ "https://app.plane.so/sign-in",+ "https://plane.example.com/api/v1/users/me/",+ "",+ " ",+ "ftp://plane.example.com/acme",+ "https://",+ ])("asks for a workspace URL when %j has no slug", (url) => {+ expect(() => parsePlaneUrl(url)).toThrow(MISSING_WORKSPACE_MESSAGE);+ });++ it("explains the expected URL shape", () => {+ expect(MISSING_WORKSPACE_MESSAGE).toBe(+ "Add your Plane workspace URL, for example https://app.plane.so/your-workspace",+ );+ });+});diff --git a/packages/importers/src/plane/url.ts b/packages/importers/src/plane/url.tsnew file mode 100644index 000000000..49a9ae1ec--- /dev/null+++ b/packages/importers/src/plane/url.ts@@ -0,0 +1,101 @@+export type PlaneTarget = {+ apiBaseUrl: string;+ workspaceSlug: string;+};++export const PLANE_CLOUD_API = "https://api.plane.so";++export const MISSING_WORKSPACE_MESSAGE =+ "Add your Plane workspace URL, for example https://app.plane.so/your-workspace";++const NON_WORKSPACE_SEGMENTS = new Set([+ "api",+ "god-mode",+ "profile",+ "accounts",+ "sign-in",+ "sign-up",+ "onboarding",+ "invitations",+ "workspace-invitations",+ "create-workspace",+ "installations",+ "spaces",+ "auth",+ "live",+]);++export function parsePlaneUrl(+ rawUrl: string | null | undefined,+ explicitSlug?: string | null,+): PlaneTarget {+ const slugOverride = cleanSlug(explicitSlug);+ const trimmed = rawUrl?.trim() ?? "";++ if (!trimmed) {+ if (slugOverride) {+ return { apiBaseUrl: PLANE_CLOUD_API, workspaceSlug: slugOverride };+ }+ throw new Error(MISSING_WORKSPACE_MESSAGE);+ }++ const url = toUrl(trimmed);+ if (!url) throw new Error(MISSING_WORKSPACE_MESSAGE);++ const apiBaseUrl = isPlaneCloud(url.hostname)+ ? PLANE_CLOUD_API+ : `${url.protocol}//${url.host}`;+ const workspaceSlug = slugOverride ?? slugFromPath(url.pathname);+ if (!workspaceSlug) throw new Error(MISSING_WORKSPACE_MESSAGE);++ return { apiBaseUrl, workspaceSlug };+}++function toUrl(value: string): URL | null {+ const withProtocol = /^[a-z][a-z\d+.-]*:\/\//i.test(value)+ ? value+ : `https://${value.replace(/^\/+/, "")}`;+ try {+ const url = new URL(withProtocol);+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;+ return url.hostname ? url : null;+ } catch {+ return null;+ }+}++function isPlaneCloud(hostname: string): boolean {+ const host = hostname.toLowerCase();+ return host === "plane.so" || host.endsWith(".plane.so");+}++function slugFromPath(pathname: string): string | undefined {+ const segments = pathname+ .split("/")+ .map((segment) => safeDecode(segment).trim())+ .filter(Boolean);+ const first = segments[0];+ if (!first) return undefined;++ if (first.toLowerCase() === "api") {+ const index = segments.findIndex(+ (segment) => segment.toLowerCase() === "workspaces",+ );+ return index === -1 ? undefined : segments[index + 1];+ }++ return NON_WORKSPACE_SEGMENTS.has(first.toLowerCase()) ? undefined : first;+}++function cleanSlug(value: string | null | undefined): string | undefined {+ const slug = value?.trim().replace(/^\/+|\/+$/g, "");+ return slug ? slug : undefined;+}++function safeDecode(segment: string): string {+ try {+ return decodeURIComponent(segment);+ } catch {+ return segment;+ }+}diff --git a/packages/importers/src/planka/board.ts b/packages/importers/src/planka/board.tsnew file mode 100644index 000000000..55bca0b7a--- /dev/null+++ b/packages/importers/src/planka/board.ts@@ -0,0 +1,241 @@+import { toIsoDate } from "../markdown.js";+import type {+ ImportedColumn,+ ImportedComment,+ ImportedLabel,+ ImportedPerson,+ ImportedProject,+ ImportedRelation,+ ImportedTask,+} from "../types.js";+import {+ type BoardBundle,+ MIGRATABLE_LIST_TYPES,+ type PlankaCard,+ type PlankaComment,+ type PlankaUser,+} from "./client.js";+import { labelColorToHex } from "./colors.js";+import {+ buildDescription,+ DEFAULT_PRIORITY,+ displayName,+ sortCards,+ toDueDate,+ UNTITLED_COLUMN,+} from "./mapping.js";++export type CardComments = {+ comments: PlankaComment[];+ users: PlankaUser[];+};++export function importableCards(bundle: BoardBundle): PlankaCard[] {+ const listIds = new Set(+ (bundle.included.lists ?? [])+ .filter((list) => MIGRATABLE_LIST_TYPES.includes(list.type))+ .map((list) => list.id),+ );+ return sortCards(+ (bundle.included.cards ?? []).filter((card) => listIds.has(card.listId)),+ );+}++export function mapBoard(+ bundle: BoardBundle,+ name: string,+ commentsByCardId: Map<string, CardComments>,+): ImportedProject {+ const included = bundle.included;+ const columns = mapColumns(bundle);+ const cards = importableCards(bundle);+ const cardIds = new Set(cards.map((card) => card.id));+ const taskLists = included.taskLists ?? [];+ const checklistItems = included.tasks ?? [];+ const labelIdsByCard = groupBy(+ included.cardLabels ?? [],+ (link) => link.cardId,+ (link) => link.labelId,+ );+ const memberIdsByCard = groupBy(+ included.cardMemberships ?? [],+ (membership) => membership.cardId,+ (membership) => membership.userId,+ );+ const taskListsByCard = groupBy(+ taskLists,+ (taskList) => taskList.cardId,+ (taskList) => taskList,+ );+ const boardLabelIds = new Set((included.labels ?? []).map((l) => l.id));+ const usersById = new Map<string, PlankaUser>(+ (included.users ?? []).map((user) => [user.id, user]),+ );+ for (const { users } of commentsByCardId.values()) {+ for (const user of users) {+ if (!usersById.has(user.id)) usersById.set(user.id, user);+ }+ }++ let extraMembers = 0;+ let hiddenEmails = 0;+ const usedLabelIds = new Set<string>();++ const tasks: ImportedTask[] = cards.map((card) => {+ const memberIds = memberIdsByCard.get(card.id) ?? [];+ if (memberIds.length > 1) extraMembers++;++ let assignee: ImportedPerson | undefined;+ const firstMemberId = memberIds[0];+ if (firstMemberId) {+ assignee = toPerson(usersById.get(firstMemberId));+ if (!assignee.email) hiddenEmails++;+ }++ const labelKeys = [+ ...new Set(+ (labelIdsByCard.get(card.id) ?? []).filter((labelId) =>+ boardLabelIds.has(labelId),+ ),+ ),+ ];+ for (const labelId of labelKeys) usedLabelIds.add(labelId);++ const dueDate = toDueDate(card);+ const createdAt = toIsoDate(card.createdAt);++ return {+ key: card.id,+ columnKey: card.listId,+ title: card.name,+ description: buildDescription(+ card,+ taskListsByCard.get(card.id) ?? [],+ checklistItems,+ ),+ priority: DEFAULT_PRIORITY,+ ...(dueDate ? { dueDate } : {}),+ ...(createdAt ? { createdAt } : {}),+ ...(assignee ? { assignee } : {}),+ labelKeys,+ comments: mapComments(commentsByCardId.get(card.id), usersById),+ };+ });++ const labels: ImportedLabel[] = (included.labels ?? [])+ .filter((label) => usedLabelIds.has(label.id))+ .sort((a, b) => a.position - b.position)+ .map((label) => ({+ key: label.id,+ name: label.name?.trim() || label.color,+ color: labelColorToHex(label.color),+ }));++ const relations: ImportedRelation[] = [];+ const seenRelations = new Set<string>();+ let externalLinks = 0;+ const cardIdByTaskListId = new Map(+ taskLists.map((taskList) => [taskList.id, taskList.cardId]),+ );+ for (const item of checklistItems) {+ if (!item.linkedCardId) continue;+ const parentId = cardIdByTaskListId.get(item.taskListId);+ if (!parentId || !cardIds.has(parentId)) continue;+ if (!cardIds.has(item.linkedCardId)) {+ externalLinks++;+ continue;+ }+ if (parentId === item.linkedCardId) continue;++ const id = `${parentId}:${item.linkedCardId}`;+ if (seenRelations.has(id)) continue;+ seenRelations.add(id);+ relations.push({+ sourceKey: parentId,+ targetKey: item.linkedCardId,+ type: "subtask",+ });+ }++ const attachments = (included.attachments ?? []).filter((attachment) =>+ cardIds.has(attachment.cardId),+ ).length;++ const warnings: string[] = [];+ if (attachments > 0) {+ warnings.push(+ `${count(attachments, "attachment")} ${attachments === 1 ? "was" : "were"} not imported.`,+ );+ }+ if (extraMembers > 0) {+ warnings.push(+ `${count(extraMembers, "card")} had more than one member. Kaneo keeps one assignee per task, so only the first member was assigned.`,+ );+ }+ if (hiddenEmails > 0) {+ warnings.push(+ `PLANKA hid the assignee email on ${count(hiddenEmails, "card")}. Connect with a PLANKA admin account so assignees can be matched by email.`,+ );+ }+ if (externalLinks > 0) {+ warnings.push(+ `${count(externalLinks, "checklist item")} linked to cards on other boards and ${externalLinks === 1 ? "was" : "were"} not imported.`,+ );+ }++ return { name, columns, labels, tasks, relations, warnings };+}++function mapColumns(bundle: BoardBundle): ImportedColumn[] {+ return (bundle.included.lists ?? [])+ .filter((list) => MIGRATABLE_LIST_TYPES.includes(list.type))+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))+ .map((list) => ({+ key: list.id,+ name: list.name?.trim() || UNTITLED_COLUMN,+ isFinal: list.type === "closed",+ }));+}++function mapComments(+ entry: CardComments | undefined,+ usersById: Map<string, PlankaUser>,+): ImportedComment[] {+ if (!entry) return [];+ return entry.comments.map((comment) => {+ const createdAt = toIsoDate(comment.createdAt);+ return {+ author: toPerson(+ comment.userId ? usersById.get(comment.userId) : undefined,+ ),+ body: comment.text,+ ...(createdAt ? { createdAt } : {}),+ };+ });+}++function toPerson(user: PlankaUser | undefined): ImportedPerson {+ return {+ name: displayName(user),+ ...(user?.email ? { email: user.email } : {}),+ };+}++function count(value: number, noun: string): string {+ return `${value} ${noun}${value === 1 ? "" : "s"}`;+}++function groupBy<T, V>(+ items: T[],+ keyOf: (item: T) => string,+ valueOf: (item: T) => V,+): Map<string, V[]> {+ const groups = new Map<string, V[]>();+ for (const item of items) {+ const key = keyOf(item);+ const group = groups.get(key);+ if (group) group.push(valueOf(item));+ else groups.set(key, [valueOf(item)]);+ }+ return groups;+}diff --git a/packages/importers/src/planka/client.test.ts b/packages/importers/src/planka/client.test.tsnew file mode 100644index 000000000..f3197417d--- /dev/null+++ b/packages/importers/src/planka/client.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it, vi } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import { PlankaClient } from "./client.js";++const BASE = "https://planka.example.com";++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function recorder(respond: (url: string, init?: RequestInit) => Response) {+ const calls: { url: string; init?: RequestInit; headers: Headers }[] = [];+ const fetch: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ calls.push({ url, init, headers: new Headers(init?.headers) });+ return respond(url, init);+ });+ return { calls, fetch };+}++function emptyProjects() {+ return recorder(() => json({ items: [], included: {} }));+}++describe("PlankaClient auth headers", () => {+ it("sends an API key in x-api-key, never as a bearer", async () => {+ const { calls, fetch } = emptyProjects();+ await new PlankaClient({+ baseUrl: BASE,+ apiKey: "secret-key",+ fetch,+ }).listProjects();++ expect(calls[0]?.headers.get("x-api-key")).toBe("secret-key");+ expect(calls[0]?.headers.get("authorization")).toBeNull();+ });++ it("sends a session token as a bearer", async () => {+ const { calls, fetch } = emptyProjects();+ await new PlankaClient({+ baseUrl: BASE,+ token: "jwt-token",+ fetch,+ }).listProjects();++ expect(calls[0]?.headers.get("authorization")).toBe("Bearer jwt-token");+ expect(calls[0]?.headers.get("x-api-key")).toBeNull();+ });++ it("prefers the token when both are supplied", async () => {+ const { calls, fetch } = emptyProjects();+ await new PlankaClient({+ baseUrl: BASE,+ token: "jwt-token",+ apiKey: "secret-key",+ fetch,+ }).listProjects();++ expect(calls[0]?.headers.get("authorization")).toBe("Bearer jwt-token");+ expect(calls[0]?.headers.get("x-api-key")).toBeNull();+ });++ it("keeps the credentials when scoped to another signal", async () => {+ const { calls, fetch } = emptyProjects();+ const client = new PlankaClient({ baseUrl: BASE, apiKey: "k", fetch });+ await client.withSignal(new AbortController().signal).listProjects();++ expect(calls[0]?.headers.get("x-api-key")).toBe("k");+ });+});++describe("isAuthenticated", () => {+ it("is true with either credential and false with neither", () => {+ expect(new PlankaClient({ baseUrl: BASE }).isAuthenticated).toBe(false);+ expect(+ new PlankaClient({ baseUrl: BASE, token: "t" }).isAuthenticated,+ ).toBe(true);+ expect(+ new PlankaClient({ baseUrl: BASE, apiKey: "k" }).isAuthenticated,+ ).toBe(true);+ });+});++describe("baseUrl", () => {+ it("strips trailing slashes and assumes https", () => {+ expect(new PlankaClient({ baseUrl: "planka.example.com/" }).baseUrl).toBe(+ "https://planka.example.com",+ );+ expect(+ new PlankaClient({ baseUrl: "http://localhost:3000//" }).baseUrl,+ ).toBe("http://localhost:3000");+ });+});++describe("login", () => {+ it("posts the credentials and then uses the token as a bearer", async () => {+ const { calls, fetch } = recorder((url) =>+ url.endsWith("/api/access-tokens")+ ? json({ item: "jwt-token" })+ : json({ items: [], included: {} }),+ );+ const client = new PlankaClient({ baseUrl: BASE, fetch });++ await client.login("sam", "hunter2");+ await client.listProjects();++ expect(calls[0]?.url).toBe(`${BASE}/api/access-tokens`);+ expect(calls[0]?.init?.method).toBe("POST");+ expect(JSON.parse(String(calls[0]?.init?.body))).toEqual({+ emailOrUsername: "sam",+ password: "hunter2",+ });+ expect(calls[0]?.headers.get("content-type")).toBe("application/json");+ expect(client.isAuthenticated).toBe(true);+ expect(calls[1]?.headers.get("authorization")).toBe("Bearer jwt-token");+ });++ it("explains the accept-terms step", async () => {+ const { fetch } = recorder(() =>+ json({ code: "E_FORBIDDEN", step: "accept-terms" }, 403),+ );++ await expect(+ new PlankaClient({ baseUrl: BASE, fetch }).login("sam", "pw"),+ ).rejects.toThrow(+ "This PLANKA instance requires you to accept its terms before the API will issue a token. Sign in once through the PLANKA web UI, accept the terms, then try again.",+ );+ });++ it("points two-factor accounts at an API key", async () => {+ const { fetch } = recorder(() =>+ json({ code: "E_FORBIDDEN", step: "verify-totp" }, 403),+ );++ await expect(+ new PlankaClient({ baseUrl: BASE, fetch }).login("sam", "pw"),+ ).rejects.toThrow(+ "This PLANKA account has two-factor authentication enabled, which password login cannot complete. Create a PLANKA API key for the account and use it instead.",+ );+ });++ it("reports a rejected password without echoing it", async () => {+ const { fetch } = recorder(() => json({ code: "E_UNAUTHORIZED" }, 401));++ const error = await new PlankaClient({ baseUrl: BASE, fetch })+ .login("sam", "hunter2")+ .catch((reason: unknown) => reason);++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe(+ "PLANKA /api/access-tokens: unauthorized (HTTP 401), check your PLANKA credentials or token",+ );+ expect((error as Error).message).not.toContain("hunter2");+ });++ it("fails clearly when no token comes back", async () => {+ const { fetch } = recorder(() => json({}));++ await expect(+ new PlankaClient({ baseUrl: BASE, fetch }).login("sam", "pw"),+ ).rejects.toThrow(+ "PLANKA did not return an access token. Create a PLANKA API key for the account and use it instead.",+ );+ });+});++describe("listComments", () => {+ it("pages with beforeId and returns the comments oldest first", async () => {+ const pages: Record<string, unknown> = {+ [`${BASE}/api/cards/c1/comments`]: {+ items: [+ { id: "m3", cardId: "c1", userId: "u1", text: "third" },+ { id: "m2", cardId: "c1", userId: "u2", text: "second" },+ ],+ included: { users: [{ id: "u1", name: "Sam" }] },+ },+ [`${BASE}/api/cards/c1/comments?beforeId=m2`]: {+ items: [{ id: "m1", cardId: "c1", userId: "u2", text: "first" }],+ included: { users: [{ id: "u2", name: "Ana" }] },+ },+ [`${BASE}/api/cards/c1/comments?beforeId=m1`]: { items: [] },+ };+ const { calls, fetch } = recorder((url) => json(pages[url] ?? {}, 200));++ const result = await new PlankaClient({+ baseUrl: BASE,+ apiKey: "k",+ fetch,+ }).listComments("c1");++ expect(calls.map((call) => call.url)).toEqual(Object.keys(pages));+ expect(result.comments.map((comment) => comment.text)).toEqual([+ "first",+ "second",+ "third",+ ]);+ expect(result.users.map((user) => user.id).sort()).toEqual(["u1", "u2"]);+ });+});diff --git a/packages/planka-import/src/planka.ts b/packages/importers/src/planka/client.tssimilarity index 57%rename from packages/planka-import/src/planka.tsrename to packages/importers/src/planka/client.tsindex 2e88e44e6..a28dfefae 100644--- a/packages/planka-import/src/planka.ts+++ b/packages/importers/src/planka/client.ts@@ -1,6 +1,13 @@+import {+ createJsonClient,+ type JsonClient,+ normalizeBaseUrl,+ SourceHttpError,+} from "../http.js";+import type { FetchLike } from "../types.js";+export type PlankaUser = {id: string;- // PLANKA omits email unless the caller is an admin or the user themselves.email?: string | null;name: string | null;username: string | null;@@ -18,7 +25,6 @@ export type PlankaBoard = {position: number | null;};-// archive and trash paginate separately and never arrive with GET /boards/:id.export const MIGRATABLE_LIST_TYPES = ["active", "closed"];export type PlankaList = {@@ -41,6 +47,7 @@ export type PlankaCard = {isDueCompleted: boolean | null;isClosed: boolean | null;commentsTotal: number | null;+ createdAt?: string | null;};export type PlankaLabel = {@@ -91,47 +98,74 @@ export type ProjectsBundle = {included: { boards?: PlankaBoard[]; users?: PlankaUser[] };};-export function normalizeBaseUrl(url: string): string {- const trimmed = url.trim().replace(/\/+$/, "");- if (!/^https?:\/\//i.test(trimmed)) {- return `https://${trimmed}`;- }- return trimmed;-}+export type PlankaClientOptions = {+ baseUrl: string;+ token?: string;+ apiKey?: string;+ fetch?: FetchLike;+ signal?: AbortSignal;+};export class PlankaClient {readonly baseUrl: string;private token: string | null;private readonly apiKey: string | null;+ private readonly fetchImpl: FetchLike | undefined;+ private readonly signal: AbortSignal | undefined;+ private readonly http: JsonClient;- constructor(options: { baseUrl: string; token?: string; apiKey?: string }) {+ constructor(options: PlankaClientOptions) {this.baseUrl = normalizeBaseUrl(options.baseUrl);this.token = options.token ?? null;this.apiKey = options.apiKey ?? null;+ this.fetchImpl = options.fetch;+ this.signal = options.signal;+ this.http = createJsonClient({+ service: "PLANKA",+ baseUrl: this.baseUrl,+ headers: () => this.authHeaders(),+ fetch: options.fetch,+ signal: options.signal,+ describeUnauthorized:+ "unauthorized (HTTP 401), check your PLANKA credentials or token",+ });}get isAuthenticated(): boolean {return this.token !== null || this.apiKey !== null;}+ withSignal(signal: AbortSignal | undefined): PlankaClient {+ if (!signal) return this;+ return new PlankaClient({+ baseUrl: this.baseUrl,+ ...(this.token ? { token: this.token } : {}),+ ...(this.apiKey ? { apiKey: this.apiKey } : {}),+ fetch: this.fetchImpl,+ signal: this.signal ? AbortSignal.any([this.signal, signal]) : signal,+ });+ }+async login(emailOrUsername: string, password: string): Promise<void> {- let body: { item?: string };+ let body: { item?: string } | null;try {- body = await this.request<{ item?: string }>("/api/access-tokens", {- method: "POST",- body: JSON.stringify({ emailOrUsername, password }),- headers: { "Content-Type": "application/json" },- });+ body = await this.http.request<{ item?: string } | null>(+ "/api/access-tokens",+ {+ method: "POST",+ body: JSON.stringify({ emailOrUsername, password }),+ },+ );} catch (error) {- if (error instanceof PlankaHttpError) {+ if (error instanceof SourceHttpError) {throw new Error(describeLoginFailure(error));}throw error;}- if (typeof body.item !== "string" || body.item.length === 0) {+ if (typeof body?.item !== "string" || body.item.length === 0) {throw new Error(- "PLANKA did not return an access token. Pass --planka-token instead.",+ "PLANKA did not return an access token. Create a PLANKA API key for the account and use it instead.",);}@@ -139,7 +173,7 @@ export class PlankaClient {}async listProjects(): Promise<ProjectsBundle> {- const bundle = await this.request<ProjectsBundle>("/api/projects");+ const bundle = await this.http.request<ProjectsBundle>("/api/projects");return {items: bundle.items ?? [],included: bundle.included ?? {},@@ -147,7 +181,7 @@ export class PlankaClient {}async getBoard(boardId: string): Promise<BoardBundle> {- const bundle = await this.request<BoardBundle>(+ const bundle = await this.http.request<BoardBundle>(`/api/boards/${encodeURIComponent(boardId)}`,);return { item: bundle.item, included: bundle.included ?? {} };@@ -163,7 +197,7 @@ export class PlankaClient {while (true) {const query = beforeId ? `?beforeId=${encodeURIComponent(beforeId)}` : "";- const page = await this.request<{+ const page = await this.http.request<{items: PlankaComment[];included?: { users?: PlankaUser[] };}>(`/api/cards/${encodeURIComponent(cardId)}/comments${query}`);@@ -181,96 +215,30 @@ export class PlankaClient {beforeId = oldest.id;}- // PLANKA returns newest first.comments.reverse();return { comments, users: [...users.values()] };}- private async request<T>(path: string, init?: RequestInit): Promise<T> {- const headers = new Headers(init?.headers);- // An API key is rejected as a bearer; it only works in x-api-key.- if (this.token) {- headers.set("Authorization", `Bearer ${this.token}`);- } else if (this.apiKey) {- headers.set("x-api-key", this.apiKey);- }- headers.set("Accept", "application/json");-- let res: Response;- try {- res = await fetch(`${this.baseUrl}${path}`, {- ...init,- headers,- signal: AbortSignal.timeout(30_000),- });- } catch (error) {- const reason = error instanceof Error ? error.message : String(error);- throw new Error(`PLANKA ${path}: ${reason}`);- }-- const text = await res.text();- let body: unknown = null;- if (text) {- try {- body = JSON.parse(text) as unknown;- } catch {- body = text;- }- }-- if (!res.ok) {- throw new PlankaHttpError(- `PLANKA ${path}: ${describeError(body, res.status)}`,- res.status,- body,- );- }-- return body as T;- }-}--export class PlankaHttpError extends Error {- constructor(- message: string,- readonly status: number,- readonly body: unknown,- ) {- super(message);- this.name = "PlankaHttpError";+ private authHeaders(): Record<string, string> {+ if (this.token) return { Authorization: `Bearer ${this.token}` };+ if (this.apiKey) return { "x-api-key": this.apiKey };+ return {};}}-function describeLoginFailure(error: PlankaHttpError): string {+function describeLoginFailure(error: SourceHttpError): string {const step =typeof error.body === "object" && error.body !== null? (error.body as { step?: unknown }).step: undefined;if (step === "accept-terms") {- return "This PLANKA instance requires you to accept its terms before the API will issue a token. Sign in once through the PLANKA web UI, accept the terms, then run this again.";+ return "This PLANKA instance requires you to accept its terms before the API will issue a token. Sign in once through the PLANKA web UI, accept the terms, then try again.";}if (step === "verify-totp") {- return "This PLANKA account has two-factor authentication enabled, which password login cannot complete. Create a PLANKA API key for the account and pass --planka-api-key instead.";+ return "This PLANKA account has two-factor authentication enabled, which password login cannot complete. Create a PLANKA API key for the account and use it instead.";}return error.message;}--function describeError(body: unknown, status: number): string {- if (status === 401) {- return "unauthorized (HTTP 401), check your PLANKA credentials or token";- }- if (typeof body === "object" && body !== null) {- const record = body as Record<string, unknown>;- for (const key of ["message", "problem", "error"]) {- const value = record[key];- if (typeof value === "string" && value.length > 0) return value;- }- }- if (typeof body === "string" && body.length > 0) {- return body.length > 300 ? `${body.slice(0, 300)}…` : body;- }- return `HTTP ${status}`;-}diff --git a/packages/planka-import/src/colors.ts b/packages/importers/src/planka/colors.tssimilarity index 89%rename from packages/planka-import/src/colors.tsrename to packages/importers/src/planka/colors.tsindex fd06ed92d..cbfd85d6e 100644--- a/packages/planka-import/src/colors.ts+++ b/packages/importers/src/planka/colors.ts@@ -1,4 +1,3 @@-// Hex values taken from PLANKA's own stylesheet.const LABEL_COLORS: Record<string, string> = {"muddy-grey": "#69655a","autumn-leafs": "#c9b037",@@ -18,7 +17,6 @@ const LABEL_COLORS: Record<string, string> = {"lilac-eyes": "#406cbd","apricot-red": "#fc736c","orange-peel": "#de692f",- // Gradient in PLANKA; collapsed to its dominant stop."silver-glint": "#92908d","bright-moss": "#96b352","deep-ocean": "#004c70",@@ -42,7 +40,6 @@ const LABEL_COLORS: Record<string, string> = {"french-coast": "#00b4b1","sweet-lilac": "#975298","red-burgundy": "#ad5f7d",- // Gradient in PLANKA; collapsed to its dominant stop."pirate-gold": "#b47e11",};diff --git a/packages/importers/src/planka/index.ts b/packages/importers/src/planka/index.tsnew file mode 100644index 000000000..14539d543--- /dev/null+++ b/packages/importers/src/planka/index.ts@@ -0,0 +1,42 @@+export {+ RESERVED_COLUMN_SLUGS,+ toColumnSlug,+ toProjectKey,+ uniqueKey,+} from "../keys.js";+export { type CardComments, importableCards, mapBoard } from "./board.js";+export {+ type BoardBundle,+ MIGRATABLE_LIST_TYPES,+ type PlankaAttachment,+ type PlankaBoard,+ type PlankaCard,+ type PlankaCardLabel,+ type PlankaCardMembership,+ PlankaClient,+ type PlankaClientOptions,+ type PlankaComment,+ type PlankaLabel,+ type PlankaList,+ type PlankaProject,+ type PlankaTask,+ type PlankaTaskList,+ type PlankaUser,+ type ProjectsBundle,+} from "./client.js";+export { FALLBACK_COLOR, LABEL_COLORS, labelColorToHex } from "./colors.js";+export {+ boardProjectName,+ buildDescription,+ DEFAULT_PRIORITY,+ displayName,+ formatComment,+ listBoardEntries,+ type PlankaBoardEntry,+ type PlannedColumn,+ planColumns,+ sortCards,+ toDueDate,+ UNTITLED_COLUMN,+} from "./mapping.js";+export { connectPlanka, type PlankaCredentials } from "./source.js";diff --git a/packages/planka-import/src/mapping.test.ts b/packages/importers/src/planka/mapping.test.tssimilarity index 85%rename from packages/planka-import/src/mapping.test.tsrename to packages/importers/src/planka/mapping.test.tsindex 821b60a1b..724d31260 100644--- a/packages/planka-import/src/mapping.test.ts+++ b/packages/importers/src/planka/mapping.test.ts@@ -1,13 +1,14 @@import { describe, expect, it } from "vite-plus/test";+import type { PlankaCard, PlankaList } from "./client.js";import {boardProjectName,buildDescription,formatComment,+ listBoardEntries,planColumns,sortCards,toDueDate,} from "./mapping.js";-import type { PlankaCard, PlankaList } from "./planka.js";function list(partial: Partial<PlankaList> & { id: string }): PlankaList {return {@@ -187,3 +188,33 @@ describe("boardProjectName", () => {);});});++describe("listBoardEntries", () => {+ it("lists every board under its project in position order with the board count", () => {+ const entries = listBoardEntries({+ items: [+ { id: "p1", name: "Marketing" },+ { id: "p2", name: "Ops" },+ ],+ included: {+ boards: [+ { id: "b2", projectId: "p1", name: "Campaigns", position: 2 },+ { id: "b3", projectId: "p2", name: "Main", position: 1 },+ { id: "b1", projectId: "p1", name: "Content", position: 1 },+ ],+ },+ });++ expect(+ entries.map((entry) => [+ entry.project.id,+ entry.board.id,+ entry.boardCountInProject,+ ]),+ ).toEqual([+ ["p1", "b1", 2],+ ["p1", "b2", 2],+ ["p2", "b3", 1],+ ]);+ });+});diff --git a/packages/planka-import/src/mapping.ts b/packages/importers/src/planka/mapping.tssimilarity index 68%rename from packages/planka-import/src/mapping.tsrename to packages/importers/src/planka/mapping.tsindex 753436fe4..450f03064 100644--- a/packages/planka-import/src/mapping.ts+++ b/packages/importers/src/planka/mapping.ts@@ -1,12 +1,16 @@-import { RESERVED_COLUMN_SLUGS, toColumnSlug } from "./keys.js";+import { RESERVED_COLUMN_SLUGS, toColumnSlug } from "../keys.js";+import { checklistSection, joinSections } from "../markdown.js";import type {+ PlankaBoard,PlankaCard,PlankaComment,PlankaList,+ PlankaProject,PlankaTask,PlankaTaskList,PlankaUser,-} from "./planka.js";+ ProjectsBundle,+} from "./client.js";export type PlannedColumn = {listId: string;@@ -16,10 +20,8 @@ export type PlannedColumn = {renamedFrom?: string;};-const UNTITLED_COLUMN = "Untitled";+export const UNTITLED_COLUMN = "Untitled";-// Kaneo rejects duplicate and reserved slugs, so a colliding name has to be-// adjusted before the column is created.export function planColumns(lists: PlankaList[]): PlannedColumn[] {const ordered = [...lists].sort((a, b) => (a.position ?? 0) - (b.position ?? 0),@@ -64,26 +66,27 @@ export function buildDescription(taskLists: PlankaTaskList[],tasks: PlankaTask[],): string {- const sections: string[] = [];- const description = card.description?.trim();- if (description) sections.push(description);+ const sections: string[] = [card.description ?? ""];for (const taskList of taskLists) {- // Items pointing at another card become task relations instead, so they- // are not also flattened into checkbox text.const items = tasks.filter((task) => task.taskListId === taskList.id && !task.linkedCardId).sort((a, b) => a.position - b.position);if (items.length === 0) continue;- const lines = items.map(- (item) => `- [${item.isCompleted ? "x" : " "}] ${item.name}`,+ sections.push(+ checklistSection(+ taskList.name,+ items.map((item) => ({+ name: item.name,+ done: Boolean(item.isCompleted),+ })),+ ),);- sections.push(`## ${taskList.name}\n\n${lines.join("\n")}`);}- return sections.join("\n\n");+ return joinSections(sections);}export function displayName(user: PlankaUser | undefined): string {@@ -103,7 +106,6 @@ export function formatComment(comment: PlankaComment): string {: comment.text;}-/** PLANKA has no priority field; Kaneo requires one on create. */export const DEFAULT_PRIORITY = "no-priority";export function toDueDate(card: PlankaCard): string | undefined {@@ -120,3 +122,30 @@ export function boardProjectName(if (boardCountInProject <= 1) return projectName;return `${projectName} - ${boardName}`;}++export type PlankaBoardEntry = {+ project: PlankaProject;+ board: PlankaBoard;+ boardCountInProject: number;+};++export function listBoardEntries(bundle: ProjectsBundle): PlankaBoardEntry[] {+ const boards = bundle.included.boards ?? [];+ const entries: PlankaBoardEntry[] = [];++ for (const project of bundle.items) {+ const projectBoards = boards+ .filter((board) => board.projectId === project.id)+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0));++ for (const board of projectBoards) {+ entries.push({+ project,+ board,+ boardCountInProject: projectBoards.length,+ });+ }+ }++ return entries;+}diff --git a/packages/importers/src/planka/source.test.ts b/packages/importers/src/planka/source.test.tsnew file mode 100644index 000000000..9cc286196--- /dev/null+++ b/packages/importers/src/planka/source.test.ts@@ -0,0 +1,511 @@+import { describe, expect, it, vi } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import { connectPlanka } from "./source.js";++const BASE = "https://planka.example.com";++type Call = { method: string; path: string; headers: Headers; body?: string };++function fakePlanka(routes: Record<string, unknown>) {+ const calls: Call[] = [];+ const fetch: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ init?.signal?.throwIfAborted();+ const path = url.slice(BASE.length);+ const method = init?.method ?? "GET";+ calls.push({+ method,+ path,+ headers: new Headers(init?.headers),+ ...(typeof init?.body === "string" ? { body: init.body } : {}),+ });+ const key = `${method} ${path}`;+ if (!(key in routes)) {+ return new Response(JSON.stringify({ code: "E_NOT_FOUND" }), {+ status: 404,+ });+ }+ const route = routes[key];+ if (route instanceof Response) return route;+ return new Response(JSON.stringify(route), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ });+ return { calls, fetch };+}++const projects = {+ items: [+ { id: "p1", name: "Marketing" },+ { id: "p2", name: "Ops" },+ ],+ included: {+ boards: [+ { id: "b2", projectId: "p1", name: "Campaigns", position: 2 },+ { id: "b1", projectId: "p1", name: "Content", position: 1 },+ { id: "b3", projectId: "p2", name: "Main", position: 1 },+ ],+ },+};++function card(partial: Record<string, unknown> & { id: string }) {+ return {+ boardId: "b1",+ listId: "l_todo",+ name: partial.id,+ description: null,+ position: 0,+ dueDate: null,+ isDueCompleted: null,+ isClosed: false,+ commentsTotal: 0,+ ...partial,+ };+}++const board = {+ item: { id: "b1", projectId: "p1", name: "Content", position: 1 },+ included: {+ lists: [+ {+ id: "l_trash",+ boardId: "b1",+ name: null,+ type: "trash",+ position: null,+ color: null,+ },+ {+ id: "l_done",+ boardId: "b1",+ name: "Done",+ type: "closed",+ position: 3,+ color: null,+ },+ {+ id: "l_todo",+ boardId: "b1",+ name: "To Do",+ type: "active",+ position: 1,+ color: null,+ },+ {+ id: "l_doing",+ boardId: "b1",+ name: " ",+ type: "active",+ position: 2,+ color: null,+ },+ {+ id: "l_archive",+ boardId: "b1",+ name: null,+ type: "archive",+ position: null,+ color: null,+ },+ ],+ cards: [+ card({ id: "c2", name: "Second", position: 2 }),+ card({+ id: "c1",+ name: "First",+ position: 1,+ description: "Ship it",+ dueDate: "2026-03-04T10:00:00.000Z",+ createdAt: "2026-01-02T08:00:00.000Z",+ commentsTotal: 2,+ }),+ card({ id: "c3", name: "Third", listId: "l_done", position: 3 }),+ card({ id: "c_old", listId: "l_archive", position: 0, commentsTotal: 4 }),+ ],+ labels: [+ {+ id: "lb2",+ boardId: "b1",+ name: null,+ color: "sunny-grass",+ position: 2,+ },+ {+ id: "lb1",+ boardId: "b1",+ name: "Bug",+ color: "berry-red",+ position: 1,+ },+ {+ id: "lb3",+ boardId: "b1",+ name: "Unused",+ color: "egg-yellow",+ position: 3,+ },+ ],+ cardLabels: [+ { cardId: "c1", labelId: "lb2" },+ { cardId: "c1", labelId: "lb1" },+ { cardId: "c3", labelId: "lb1" },+ { cardId: "c_old", labelId: "lb3" },+ ],+ cardMemberships: [+ { cardId: "c1", userId: "u1" },+ { cardId: "c1", userId: "u2" },+ { cardId: "c2", userId: "u2" },+ ],+ taskLists: [+ { id: "tl1", cardId: "c1", name: "Steps" },+ { id: "tl2", cardId: "c2", name: "Links" },+ ],+ tasks: [+ {+ id: "t2",+ taskListId: "tl1",+ name: "Review",+ isCompleted: false,+ position: 2,+ },+ {+ id: "t1",+ taskListId: "tl1",+ name: "Write",+ isCompleted: true,+ position: 1,+ },+ {+ id: "t3",+ taskListId: "tl2",+ name: "",+ isCompleted: false,+ position: 1,+ linkedCardId: "c3",+ },+ {+ id: "t4",+ taskListId: "tl2",+ name: "",+ isCompleted: false,+ position: 2,+ linkedCardId: "c2",+ },+ {+ id: "t5",+ taskListId: "tl2",+ name: "",+ isCompleted: false,+ position: 3,+ linkedCardId: "c_elsewhere",+ },+ {+ id: "t6",+ taskListId: "tl2",+ name: "",+ isCompleted: false,+ position: 4,+ linkedCardId: "c3",+ },+ ],+ attachments: [+ { id: "a1", cardId: "c1" },+ { id: "a2", cardId: "c2" },+ { id: "a3", cardId: "c_old" },+ ],+ users: [+ { id: "u1", name: "Sam", username: "sam" },+ { id: "u2", name: null, username: "ana", email: "[email protected]" },+ ],+ },+};++const commentRoutes = {+ "GET /api/cards/c1/comments": {+ items: [+ {+ id: "m2",+ cardId: "c1",+ userId: "u3",+ text: "Second note",+ createdAt: "2026-02-02T09:00:00.000Z",+ },+ {+ id: "m1",+ cardId: "c1",+ userId: "u2",+ text: "First note",+ createdAt: "2026-02-01T09:00:00.000Z",+ },+ ],+ included: {+ users: [+ { id: "u3", name: "Lee", username: "lee", email: "[email protected]" },+ ],+ },+ },+ "GET /api/cards/c1/comments?beforeId=m1": { items: [] },+};++const routes = {+ "GET /api/projects": projects,+ "GET /api/boards/b1": board,+ ...commentRoutes,+};++describe("connectPlanka", () => {+ it("validates an API key with one projects request sent in x-api-key", async () => {+ const { calls, fetch } = fakePlanka(routes);++ await connectPlanka(+ { url: "planka.example.com/", apiKey: " key-1 " },+ { fetch },+ );++ expect(calls).toHaveLength(1);+ expect(calls[0]?.path).toBe("/api/projects");+ expect(calls[0]?.headers.get("x-api-key")).toBe("key-1");+ expect(calls[0]?.headers.get("authorization")).toBeNull();+ });++ it("logs in with a username and password and then uses the bearer token", async () => {+ const { calls, fetch } = fakePlanka({+ ...routes,+ "POST /api/access-tokens": { item: "jwt-1" },+ });++ await connectPlanka(+ { url: BASE, username: "sam", password: "pw" },+ { fetch },+ );++ expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([+ "POST /api/access-tokens",+ "GET /api/projects",+ ]);+ expect(JSON.parse(calls[0]?.body ?? "{}")).toEqual({+ emailOrUsername: "sam",+ password: "pw",+ });+ expect(calls[1]?.headers.get("authorization")).toBe("Bearer jwt-1");+ });++ it("prefers the API key over a username and password", async () => {+ const { calls, fetch } = fakePlanka(routes);++ await connectPlanka(+ { url: BASE, apiKey: "key-1", username: "sam", password: "pw" },+ { fetch },+ );++ expect(calls.map((call) => call.path)).toEqual(["/api/projects"]);+ });++ it("rejects missing credentials without any request", async () => {+ const { calls, fetch } = fakePlanka(routes);++ await expect(+ connectPlanka({ url: BASE, username: "sam" }, { fetch }),+ ).rejects.toThrow(+ "Enter a PLANKA API key, or the username and password of a PLANKA account.",+ );+ await expect(+ connectPlanka({ url: " ", apiKey: "key-1" }, { fetch }),+ ).rejects.toThrow("Enter the URL of your PLANKA instance.");+ expect(calls).toHaveLength(0);+ });++ it("reports an invalid API key without echoing it", async () => {+ const { fetch } = fakePlanka({+ "GET /api/projects": new Response("{}", { status: 401 }),+ });++ const error: unknown = await connectPlanka(+ { url: BASE, apiKey: "bad-key" },+ { fetch },+ ).catch((reason: unknown) => reason);++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe(+ "PLANKA /api/projects: unauthorized (HTTP 401), check your PLANKA credentials or token",+ );+ expect((error as Error).message).not.toContain("bad-key");+ });+});++describe("listProjects", () => {+ it("lists one entry per board, qualified by board when a project has several", async () => {+ const { fetch } = fakePlanka(routes);+ const source = await connectPlanka({ url: BASE, apiKey: "k" }, { fetch });++ expect(await source.listProjects()).toEqual([+ { id: "b1", name: "Marketing - Content", detail: "Marketing" },+ { id: "b2", name: "Marketing - Campaigns", detail: "Marketing" },+ { id: "b3", name: "Ops", detail: "Ops" },+ ]);+ });+});++describe("readProject", () => {+ async function read(includeComments = true) {+ const { calls, fetch } = fakePlanka(routes);+ const source = await connectPlanka({ url: BASE, apiKey: "k" }, { fetch });+ const progress: string[] = [];+ const project = await source.readProject("b1", {+ includeComments,+ onProgress: (message) => progress.push(message),+ });+ return { project, progress, calls };+ }++ it("names the project like listProjects", async () => {+ const { project } = await read();+ expect(project.name).toBe("Marketing - Content");+ });++ it("maps active and closed lists to ordered columns with closed as final", async () => {+ const { project } = await read();++ expect(project.columns).toEqual([+ { key: "l_todo", name: "To Do", isFinal: false },+ { key: "l_doing", name: "Untitled", isFinal: false },+ { key: "l_done", name: "Done", isFinal: true },+ ]);+ });++ it("maps cards to tasks in board order", async () => {+ const { project } = await read();++ expect(project.tasks.map((task) => [task.key, task.columnKey])).toEqual([+ ["c1", "l_todo"],+ ["c2", "l_todo"],+ ["c3", "l_done"],+ ]);++ const first = project.tasks[0];+ expect(first).toMatchObject({+ title: "First",+ description: "Ship it\n\n## Steps\n\n- [x] Write\n- [ ] Review",+ priority: "no-priority",+ dueDate: "2026-03-04T10:00:00.000Z",+ createdAt: "2026-01-02T08:00:00.000Z",+ labelKeys: ["lb2", "lb1"],+ });+ expect(project.tasks[1]?.description).toBe("");+ });++ it("keeps only used labels with hex colors in label order", async () => {+ const { project } = await read();++ expect(project.labels).toEqual([+ { key: "lb1", name: "Bug", color: "#e83855" },+ { key: "lb2", name: "sunny-grass", color: "#beca02" },+ ]);+ });++ it("assigns the first card member and keeps the email when PLANKA shares it", async () => {+ const { project } = await read();++ expect(project.tasks[0]?.assignee).toEqual({ name: "Sam" });+ expect(project.tasks[1]?.assignee).toEqual({+ name: "ana",+ email: "[email protected]",+ });+ expect(project.tasks[2]?.assignee).toBeUndefined();+ });++ it("reads comments oldest first with their authors and original dates", async () => {+ const { project, calls } = await read();++ expect(project.tasks[0]?.comments).toEqual([+ {+ author: { name: "ana", email: "[email protected]" },+ body: "First note",+ createdAt: "2026-02-01T09:00:00.000Z",+ },+ {+ author: { name: "Lee", email: "[email protected]" },+ body: "Second note",+ createdAt: "2026-02-02T09:00:00.000Z",+ },+ ]);+ expect(project.tasks[1]?.comments).toEqual([]);+ expect(+ calls+ .filter((call) => call.path.includes("/comments"))+ .map((c) => c.path),+ ).toEqual(["/api/cards/c1/comments", "/api/cards/c1/comments?beforeId=m1"]);+ });++ it("skips comment requests when comments are not wanted", async () => {+ const { project, calls } = await read(false);++ expect(calls.some((call) => call.path.includes("/comments"))).toBe(false);+ expect(project.tasks[0]?.comments).toEqual([]);+ });++ it("turns linked checklist items into subtask relations inside the board", async () => {+ const { project } = await read();++ expect(project.relations).toEqual([+ { sourceKey: "c2", targetKey: "c3", type: "subtask" },+ ]);+ });++ it("warns about attachments, extra members, hidden emails and outside links", async () => {+ const { project } = await read();++ expect(project.warnings).toEqual([+ "2 attachments were not imported.",+ "1 card had more than one member. Kaneo keeps one assignee per task, so only the first member was assigned.",+ "PLANKA hid the assignee email on 1 card. Connect with a PLANKA admin account so assignees can be matched by email.",+ "1 checklist item linked to cards on other boards and was not imported.",+ ]);+ });++ it("reports progress while reading", async () => {+ const { progress } = await read();++ expect(progress).toEqual([+ "Reading board Marketing - Content",+ "Reading comments (1 of 1 cards)",+ ]);+ });++ it("fails clearly for a board that is not listed", async () => {+ const { calls, fetch } = fakePlanka(routes);+ const source = await connectPlanka({ url: BASE, apiKey: "k" }, { fetch });++ await expect(+ source.readProject("gone", { includeComments: false }),+ ).rejects.toThrow("This PLANKA board was not found.");+ expect(calls.map((call) => call.path)).toEqual([+ "/api/projects",+ "/api/projects",+ ]);+ });++ it("fails clearly when a listed board no longer exists", async () => {+ const { fetch } = fakePlanka({ "GET /api/projects": projects });+ const source = await connectPlanka({ url: BASE, apiKey: "k" }, { fetch });++ await expect(+ source.readProject("b2", { includeComments: false }),+ ).rejects.toThrow("This PLANKA board was not found.");+ });++ it("passes the read signal to every request", async () => {+ const { calls, fetch } = fakePlanka(routes);+ const source = await connectPlanka({ url: BASE, apiKey: "k" }, { fetch });+ const controller = new AbortController();+ controller.abort();++ await expect(+ source.readProject("b1", {+ includeComments: false,+ signal: controller.signal,+ }),+ ).rejects.toThrow();+ expect(calls.map((call) => call.path)).toEqual(["/api/projects"]);+ });+});diff --git a/packages/importers/src/planka/source.ts b/packages/importers/src/planka/source.tsnew file mode 100644index 000000000..2cb2670f9--- /dev/null+++ b/packages/importers/src/planka/source.ts@@ -0,0 +1,140 @@+import { SourceHttpError } from "../http.js";+import type {+ ConnectOptions,+ ImportedProject,+ ImportSource,+ ReadProjectOptions,+ SourceProject,+} from "../types.js";+import { type CardComments, importableCards, mapBoard } from "./board.js";+import { type BoardBundle, PlankaClient } from "./client.js";+import {+ boardProjectName,+ listBoardEntries,+ type PlankaBoardEntry,+} from "./mapping.js";++export type PlankaCredentials = {+ url: string;+ apiKey?: string;+ username?: string;+ password?: string;+};++export async function connectPlanka(+ credentials: PlankaCredentials,+ options: ConnectOptions,+): Promise<ImportSource> {+ const url = credentials.url?.trim();+ if (!url) throw new Error("Enter the URL of your PLANKA instance.");++ const apiKey = credentials.apiKey?.trim();+ const username = credentials.username?.trim();+ const password = credentials.password;+ if (!apiKey && !(username && password)) {+ throw new Error(+ "Enter a PLANKA API key, or the username and password of a PLANKA account.",+ );+ }++ const client = new PlankaClient({+ baseUrl: url,+ ...(apiKey ? { apiKey } : {}),+ fetch: options.fetch,+ signal: options.signal,+ });++ if (!apiKey && username && password) {+ await client.login(username, password);+ }++ let entries = await loadEntries(client);++ async function findEntry(boardId: string): Promise<PlankaBoardEntry> {+ const cached = entries.find((entry) => entry.board.id === boardId);+ if (cached) return cached;+ entries = await loadEntries(client);+ const fresh = entries.find((entry) => entry.board.id === boardId);+ if (!fresh) throw boardNotFound();+ return fresh;+ }++ return {+ async listProjects(): Promise<SourceProject[]> {+ entries = await loadEntries(client);+ return entries.map((entry) => ({+ id: entry.board.id,+ name: projectName(entry),+ detail: entry.project.name,+ }));+ },++ async readProject(+ boardId: string,+ readOptions: ReadProjectOptions,+ ): Promise<ImportedProject> {+ const entry = await findEntry(boardId);+ const scoped = client.withSignal(readOptions.signal);+ const name = projectName(entry);++ readOptions.onProgress?.(`Reading board ${name}`);+ const bundle = await readBoard(scoped, boardId);++ const commentsByCardId = readOptions.includeComments+ ? await readComments(scoped, bundle, readOptions.onProgress)+ : new Map<string, CardComments>();++ return mapBoard(bundle, name, commentsByCardId);+ },+ };+}++async function loadEntries(client: PlankaClient): Promise<PlankaBoardEntry[]> {+ return listBoardEntries(await client.listProjects());+}++function projectName(entry: PlankaBoardEntry): string {+ return boardProjectName(+ entry.project.name,+ entry.board.name,+ entry.boardCountInProject,+ );+}++async function readBoard(+ client: PlankaClient,+ boardId: string,+): Promise<BoardBundle> {+ try {+ return await client.getBoard(boardId);+ } catch (error) {+ if (error instanceof SourceHttpError && error.status === 404) {+ throw boardNotFound();+ }+ throw error;+ }+}++async function readComments(+ client: PlankaClient,+ bundle: BoardBundle,+ onProgress: ((message: string) => void) | undefined,+): Promise<Map<string, CardComments>> {+ const cards = importableCards(bundle).filter(+ (card) => card.commentsTotal !== 0,+ );+ const commentsByCardId = new Map<string, CardComments>();++ for (const [index, card] of cards.entries()) {+ onProgress?.(`Reading comments (${index + 1} of ${cards.length} cards)`);+ commentsByCardId.set(card.id, await client.listComments(card.id));+ }++ return commentsByCardId;+}++function boardNotFound(): Error {+ return new Error(+ "This PLANKA board was not found. It may have been deleted, or the connected account can no longer access it.",+ );+}diff --git a/packages/importers/src/trello/authorize.test.ts b/packages/importers/src/trello/authorize.test.tsnew file mode 100644index 000000000..36a936829--- /dev/null+++ b/packages/importers/src/trello/authorize.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from "vite-plus/test";+import { trelloAuthorizeUrl } from "./authorize.js";++describe("trelloAuthorizeUrl", () => {+ it("asks for a read-only, one day token for Kaneo", () => {+ expect(trelloAuthorizeUrl(" abc123 ")).toBe(+ "https://trello.com/1/authorize?expiration=1day&scope=read&response_type=token&name=Kaneo&key=abc123",+ );+ });++ it("encodes the key", () => {+ expect(trelloAuthorizeUrl("a&b")).toContain("key=a%26b");+ });+});diff --git a/packages/importers/src/trello/authorize.ts b/packages/importers/src/trello/authorize.tsnew file mode 100644index 000000000..53a8e6363--- /dev/null+++ b/packages/importers/src/trello/authorize.ts@@ -0,0 +1,10 @@+export function trelloAuthorizeUrl(apiKey: string): string {+ const params = new URLSearchParams({+ expiration: "1day",+ scope: "read",+ response_type: "token",+ name: "Kaneo",+ key: apiKey.trim(),+ });+ return `https://trello.com/1/authorize?${params.toString()}`;+}diff --git a/packages/importers/src/trello/client.ts b/packages/importers/src/trello/client.tsnew file mode 100644index 000000000..7c6958e3e--- /dev/null+++ b/packages/importers/src/trello/client.ts@@ -0,0 +1,249 @@+import { createJsonClient, SourceHttpError } from "../http.js";+import type { FetchLike } from "../types.js";+import { TOKEN_REJECTED } from "./errors.js";++export type TrelloMember = {+ id: string;+ fullName?: string | null;+ username?: string | null;+ email?: string | null;+};++export type TrelloBoardSummary = {+ id: string;+ name: string;+ url?: string;+ idOrganization?: string | null;+};++export type TrelloOrganization = {+ id: string;+ displayName?: string | null;+};++export type TrelloList = {+ id: string;+ name: string;+ pos: number;+ closed?: boolean;+};++export type TrelloCard = {+ id: string;+ idShort?: number | null;+ name: string;+ desc?: string | null;+ due?: string | null;+ dueComplete?: boolean;+ start?: string | null;+ idList: string;+ idLabels?: string[];+ idMembers?: string[];+ idChecklists?: string[];+ pos: number;+ closed?: boolean;+ dateLastActivity?: string | null;+ badges?: { attachments?: number } | null;+};++export type TrelloLabel = {+ id: string;+ name?: string | null;+ color?: string | null;+};++export type TrelloCheckItem = {+ id: string;+ name: string;+ state: "complete" | "incomplete";+ pos: number;+};++export type TrelloChecklist = {+ id: string;+ name: string;+ idCard: string;+ pos: number;+ checkItems?: TrelloCheckItem[];+};++export type TrelloBoard = {+ id: string;+ name: string;+ desc?: string | null;+ lists?: TrelloList[];+ cards?: TrelloCard[];+ labels?: TrelloLabel[];+ checklists?: TrelloChecklist[];+ members?: TrelloMember[];+};++export type TrelloCommentAction = {+ id: string;+ date?: string | null;+ idMemberCreator?: string | null;+ data?: { text?: string | null; card?: { id?: string | null } | null } | null;+ memberCreator?: TrelloMember | null;+};++export type TrelloClientOptions = {+ apiKey: string;+ token: string;+ fetch?: FetchLike;+ signal?: AbortSignal;+};++export type TrelloClient = {+ getMe(): Promise<TrelloMember>;+ listBoards(): Promise<TrelloBoardSummary[]>;+ listOrganizations(): Promise<TrelloOrganization[]>;+ getBoard(boardId: string): Promise<TrelloBoard>;+ listCommentActions(+ boardId: string,+ onPage?: (fetched: number) => void,+ ): Promise<TrelloCommentAction[]>;+ withSignal(signal: AbortSignal | undefined): TrelloClient;+};++export const TRELLO_API_URL = "https://api.trello.com/1";+export const COMMENT_PAGE_SIZE = 1000;++const CARD_FIELDS =+ "idShort,name,desc,due,dueComplete,start,idList,idLabels,idMembers,idChecklists,pos,closed,dateLastActivity,badges";++const BOARD_CONTENT_QUERY = [+ "fields=name,desc",+ "lists=all",+ "list_fields=name,pos,closed",+ "cards=all",+ `card_fields=${CARD_FIELDS}`,+ "labels=all",+ "label_fields=name,color",+ "labels_limit=1000",+ "checklists=all",+ "checklist_fields=name,idCard,pos",+ "checkItem_fields=name,state,pos",+ "members=all",+ "member_fields=fullName,username",+].join("&");++const COMMENTS_QUERY = [+ "filter=commentCard",+ `limit=${COMMENT_PAGE_SIZE}`,+ "fields=data,date,idMemberCreator",+ "memberCreator_fields=fullName,username",+].join("&");++const NOT_SPLITTABLE_STATUSES = new Set([401, 403, 404, 429]);++export function trelloAuthHeader(apiKey: string, token: string): string {+ return `OAuth oauth_consumer_key="${apiKey}", oauth_token="${token}"`;+}++export function createTrelloClient(options: TrelloClientOptions): TrelloClient {+ const http = createJsonClient({+ service: "Trello",+ baseUrl: TRELLO_API_URL,+ headers: () => ({+ Authorization: trelloAuthHeader(options.apiKey, options.token),+ }),+ fetch: options.fetch,+ signal: options.signal,+ describeUnauthorized: TOKEN_REJECTED,+ });++ async function list<T>(path: string): Promise<T[]> {+ const body = await http.request<T[] | null>(path);+ return Array.isArray(body) ? body : [];+ }++ async function getBoardInParts(boardId: string): Promise<TrelloBoard> {+ const base = `/boards/${boardId}`;+ const board = await http.request<TrelloBoard>(`${base}?fields=name,desc`);+ const lists = await list<TrelloList>(+ `${base}/lists?filter=all&fields=name,pos,closed`,+ );+ const cards = await list<TrelloCard>(+ `${base}/cards/all?fields=${CARD_FIELDS}`,+ );+ const labels = await list<TrelloLabel>(+ `${base}/labels?limit=1000&fields=name,color`,+ );+ const checklists = await list<TrelloChecklist>(+ `${base}/checklists?fields=name,idCard,pos&checkItem_fields=name,state,pos`,+ );+ const members = await list<TrelloMember>(+ `${base}/members?fields=fullName,username`,+ );+ return { ...board, lists, cards, labels, checklists, members };+ }++ const client: TrelloClient = {+ getMe: () =>+ http.request<TrelloMember>(+ "/members/me?fields=id,fullName,username,email",+ ),++ listBoards: () =>+ list<TrelloBoardSummary>(+ "/members/me/boards?filter=open&fields=name,url,idOrganization",+ ),++ listOrganizations: () =>+ list<TrelloOrganization>("/members/me/organizations?fields=displayName"),++ async getBoard(boardId) {+ const id = encodeURIComponent(boardId);+ try {+ return await http.request<TrelloBoard>(+ `/boards/${id}?${BOARD_CONTENT_QUERY}`,+ );+ } catch (error) {+ if (!isSplittable(error)) throw error;+ return getBoardInParts(id);+ }+ },++ async listCommentActions(boardId, onPage) {+ const path = `/boards/${encodeURIComponent(boardId)}/actions?${COMMENTS_QUERY}`;+ const actions: TrelloCommentAction[] = [];+ let before: string | undefined;++ while (true) {+ const page = await list<TrelloCommentAction>(+ before ? `${path}&before=${encodeURIComponent(before)}` : path,+ );+ actions.push(...page);+ onPage?.(actions.length);++ if (page.length < COMMENT_PAGE_SIZE) break;+ const oldest = page[page.length - 1];+ if (!oldest?.id || oldest.id === before) break;+ before = oldest.id;+ }++ return actions;+ },++ withSignal(signal) {+ if (!signal) return client;+ return createTrelloClient({+ ...options,+ signal: options.signal+ ? AbortSignal.any([options.signal, signal])+ : signal,+ });+ },+ };++ return client;+}++function isSplittable(error: unknown): boolean {+ return (+ error instanceof SourceHttpError &&+ error.status >= 400 &&+ error.status < 500 &&+ !NOT_SPLITTABLE_STATUSES.has(error.status)+ );+}diff --git a/packages/importers/src/trello/colors.test.ts b/packages/importers/src/trello/colors.test.tsnew file mode 100644index 000000000..93539a57b--- /dev/null+++ b/packages/importers/src/trello/colors.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vite-plus/test";+import {+ FALLBACK_LABEL_COLOR,+ TRELLO_LABEL_COLORS,+ trelloColorName,+ trelloLabelColor,+} from "./colors.js";++describe("TRELLO_LABEL_COLORS", () => {+ it("covers the 10 base colors with dark and light variants as hex", () => {+ const names = Object.keys(TRELLO_LABEL_COLORS);+ expect(names).toHaveLength(30);+ for (const base of [+ "green",+ "yellow",+ "orange",+ "red",+ "purple",+ "blue",+ "sky",+ "lime",+ "pink",+ "black",+ ]) {+ expect(names).toContain(base);+ expect(names).toContain(`${base}_dark`);+ expect(names).toContain(`${base}_light`);+ }+ for (const hex of Object.values(TRELLO_LABEL_COLORS)) {+ expect(hex).toMatch(/^#[0-9a-f]{6}$/);+ }+ });+});++describe("trelloLabelColor", () => {+ it("maps named colors to hex", () => {+ expect(trelloLabelColor("green")).toBe("#4bce97");+ expect(trelloLabelColor("sky_dark")).toBe("#227d9b");+ expect(trelloLabelColor("pink_light")).toBe("#fdd0ec");+ });++ it("falls back for missing or unknown colors", () => {+ expect(trelloLabelColor(null)).toBe(FALLBACK_LABEL_COLOR);+ expect(trelloLabelColor(undefined)).toBe(FALLBACK_LABEL_COLOR);+ expect(trelloLabelColor("ping_light")).toBe(FALLBACK_LABEL_COLOR);+ expect(trelloLabelColor("constructor")).toBe(FALLBACK_LABEL_COLOR);+ });+});++describe("trelloColorName", () => {+ it("capitalizes the color and spells out variants", () => {+ expect(trelloColorName("green")).toBe("Green");+ expect(trelloColorName("sky_light")).toBe("Sky light");+ expect(trelloColorName(null)).toBeUndefined();+ expect(trelloColorName("")).toBeUndefined();+ });+});diff --git a/packages/importers/src/trello/colors.ts b/packages/importers/src/trello/colors.tsnew file mode 100644index 000000000..2615da5ec--- /dev/null+++ b/packages/importers/src/trello/colors.ts@@ -0,0 +1,49 @@+export const TRELLO_LABEL_COLORS: Readonly<Record<string, string>> = {+ green: "#4bce97",+ yellow: "#f5cd47",+ orange: "#fea362",+ red: "#f87168",+ purple: "#9f8fef",+ blue: "#579dff",+ sky: "#6cc3e0",+ lime: "#94c748",+ pink: "#e774bb",+ black: "#8590a2",+ green_dark: "#1f845a",+ yellow_dark: "#946f00",+ orange_dark: "#c25100",+ red_dark: "#c9372c",+ purple_dark: "#6e5dc6",+ blue_dark: "#0c66e4",+ sky_dark: "#227d9b",+ lime_dark: "#5b7f24",+ pink_dark: "#ae4787",+ black_dark: "#626f86",+ green_light: "#baf3db",+ yellow_light: "#f8e6a0",+ orange_light: "#fedec8",+ red_light: "#ffd5d2",+ purple_light: "#dfd8fd",+ blue_light: "#cce0ff",+ sky_light: "#c6edfb",+ lime_light: "#d3f1a7",+ pink_light: "#fdd0ec",+ black_light: "#dcdfe4",+};++export const FALLBACK_LABEL_COLOR = "#6b7280";++export function trelloLabelColor(color: string | null | undefined): string {+ if (!color || !Object.hasOwn(TRELLO_LABEL_COLORS, color)) {+ return FALLBACK_LABEL_COLOR;+ }+ return TRELLO_LABEL_COLORS[color] ?? FALLBACK_LABEL_COLOR;+}++export function trelloColorName(+ color: string | null | undefined,+): string | undefined {+ const words = color?.trim().replace(/_/g, " ");+ if (!words) return undefined;+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;+}diff --git a/packages/importers/src/trello/comments.test.ts b/packages/importers/src/trello/comments.test.tsnew file mode 100644index 000000000..257477a19--- /dev/null+++ b/packages/importers/src/trello/comments.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "vite-plus/test";+import type { TrelloCommentAction, TrelloMember } from "./client.js";+import { mapCommentActions } from "./comments.js";++const owner: TrelloMember = {+ id: "m-owner",+ fullName: "Olive Owner",+ email: "[email protected]",+};++function action(+ id: string,+ cardId: string | null,+ text: string,+ date: string,+ creator?: TrelloMember,+): TrelloCommentAction {+ return {+ id,+ date,+ idMemberCreator: creator?.id ?? null,+ data: { text, ...(cardId ? { card: { id: cardId } } : {}) },+ ...(creator ? { memberCreator: creator } : {}),+ };+}++describe("mapCommentActions", () => {+ it("groups by card, oldest first, with the owner's email only", () => {+ const sam = { id: "m-sam", fullName: "Sam Smith", username: "sam" };+ const comments = mapCommentActions(+ [+ action("a4", "c1", "Newest", "2024-03-04T10:00:00.000Z", sam),+ action("a3", "c2", "Other card", "2024-03-03T10:00:00.000Z", owner),+ action("a2", "c1", "Middle", "2024-03-02T10:00:00.000Z", owner),+ action("a1", "c1", "**Oldest**", "2024-03-01T10:00:00.000Z", sam),+ ],+ owner,+ );++ expect(comments.get("c1")).toEqual([+ {+ author: { name: "Sam Smith" },+ body: "**Oldest**",+ createdAt: "2024-03-01T10:00:00.000Z",+ },+ {+ author: { name: "Olive Owner", email: "[email protected]" },+ body: "Middle",+ createdAt: "2024-03-02T10:00:00.000Z",+ },+ {+ author: { name: "Sam Smith" },+ body: "Newest",+ createdAt: "2024-03-04T10:00:00.000Z",+ },+ ]);+ expect(comments.get("c2")).toHaveLength(1);+ });++ it("skips comments without a card or text and tolerates unknown authors", () => {+ const comments = mapCommentActions(+ [+ action("a3", null, "Lost", "2024-03-03T10:00:00.000Z"),+ action("a2", "c1", " ", "2024-03-02T10:00:00.000Z"),+ action("a1", "c1", "Kept", "2024-03-01T10:00:00.000Z"),+ ],+ owner,+ );++ expect([...comments.keys()]).toEqual(["c1"]);+ expect(comments.get("c1")).toEqual([+ { author: {}, body: "Kept", createdAt: "2024-03-01T10:00:00.000Z" },+ ]);+ });+});diff --git a/packages/importers/src/trello/comments.ts b/packages/importers/src/trello/comments.tsnew file mode 100644index 000000000..aedcececa--- /dev/null+++ b/packages/importers/src/trello/comments.ts@@ -0,0 +1,46 @@+import { toIsoDate } from "../markdown.js";+import type { ImportedComment } from "../types.js";+import type { TrelloCommentAction, TrelloMember } from "./client.js";+import { trelloPerson } from "./people.js";++export function mapCommentActions(+ actions: TrelloCommentAction[],+ owner: TrelloMember,+): Map<string, ImportedComment[]> {+ const byCard = new Map<string, ImportedComment[]>();++ for (const action of oldestFirst(actions)) {+ const cardId = action.data?.card?.id;+ const body = action.data?.text;+ if (!cardId || !body?.trim()) continue;++ const author =+ trelloPerson(+ action.memberCreator ?? { id: action.idMemberCreator ?? undefined },+ owner,+ ) ?? {};+ const createdAt = toIsoDate(action.date);+ const comment: ImportedComment = {+ author,+ body,+ ...(createdAt ? { createdAt } : {}),+ };++ const comments = byCard.get(cardId);+ if (comments) comments.push(comment);+ else byCard.set(cardId, [comment]);+ }++ return byCard;+}++function oldestFirst(actions: TrelloCommentAction[]): TrelloCommentAction[] {+ return actions+ .map((action, index) => ({+ action,+ index,+ time: Date.parse(action.date ?? "") || 0,+ }))+ .sort((a, b) => a.time - b.time || b.index - a.index)+ .map(({ action }) => action);+}diff --git a/packages/importers/src/trello/errors.ts b/packages/importers/src/trello/errors.tsnew file mode 100644index 000000000..d0dfcf8e7--- /dev/null+++ b/packages/importers/src/trello/errors.ts@@ -0,0 +1,26 @@+import { SourceHttpError } from "../http.js";++export const TOKEN_REJECTED =+ "Trello rejected the token. Authorize Kaneo on Trello again and paste the new token.";++export const KEY_REJECTED = "Trello rejected the API key.";++export function describeAuthFailure(error: unknown): string | undefined {+ if (!(error instanceof SourceHttpError)) return undefined;+ if (error.status !== 400 && error.status !== 401) return undefined;++ const text = bodyText(error.body);+ if (/invalid key/i.test(text)) return KEY_REJECTED;+ if (error.status === 401 || /token/i.test(text)) return TOKEN_REJECTED;+ return undefined;+}++function bodyText(body: unknown): string {+ if (typeof body === "string") return body;+ if (body == null) return "";+ try {+ return JSON.stringify(body);+ } catch {+ return "";+ }+}diff --git a/packages/importers/src/trello/index.ts b/packages/importers/src/trello/index.tsnew file mode 100644index 000000000..f8cef83d0--- /dev/null+++ b/packages/importers/src/trello/index.ts@@ -0,0 +1,2 @@+export { trelloAuthorizeUrl } from "./authorize.js";+export { connectTrello, type TrelloCredentials } from "./source.js";diff --git a/packages/importers/src/trello/mapping.test.ts b/packages/importers/src/trello/mapping.test.tsnew file mode 100644index 000000000..ac8b09b0b--- /dev/null+++ b/packages/importers/src/trello/mapping.test.ts@@ -0,0 +1,372 @@+import { describe, expect, it } from "vite-plus/test";+import type {+ TrelloBoard,+ TrelloCard,+ TrelloList,+ TrelloMember,+} from "./client.js";+import { cardCreatedAt, mapBoard, mapColumns, mapLabel } from "./mapping.js";++const owner: TrelloMember = {+ id: "m-owner",+ fullName: "Olive Owner",+ username: "olive",+ email: "[email protected]",+};++function list(id: string, name: string, pos: number, closed = false) {+ return { id, name, pos, closed } satisfies TrelloList;+}++function card(+ id: string,+ idList: string,+ pos: number,+ extra: Partial<TrelloCard> = {},+): TrelloCard {+ return { id, name: `Card ${id}`, idList, pos, closed: false, ...extra };+}++function board(overrides: Partial<TrelloBoard> = {}): TrelloBoard {+ return {+ id: "b1",+ name: "Roadmap",+ desc: "",+ lists: [list("l-todo", "To Do", 100)],+ cards: [],+ labels: [],+ checklists: [],+ members: [],+ ...overrides,+ };+}++describe("mapColumns", () => {+ it("keeps open lists in order and marks a done-like last list final", () => {+ const project = mapBoard(+ board({+ lists: [+ list("l-done", "Done", 300),+ list("l-todo", "To Do", 100),+ list("l-old", "Old ideas", 150, true),+ list("l-doing", "Doing", 200),+ ],+ }),+ { owner },+ );++ expect(project.columns).toEqual([+ { key: "l-todo", name: "To Do", isFinal: false },+ { key: "l-doing", name: "Doing", isFinal: false },+ { key: "l-done", name: "Done", isFinal: true },+ ]);+ });++ it("marks nothing final when the last list is not done-like", () => {+ expect(+ mapColumns([list("l-done", "Done", 1), list("l-later", "Later", 2)]),+ ).toEqual([+ { key: "l-done", name: "Done", isFinal: false },+ { key: "l-later", name: "Later", isFinal: false },+ ]);+ });++ it("recognizes other done-like names", () => {+ for (const name of ["Completed", "closed", "Shipped 🚀", "Finished"]) {+ expect(mapColumns([list("l", name, 1)])[0]?.isFinal).toBe(true);+ }+ expect(mapColumns([list("l", "Not done", 1)])[0]?.isFinal).toBe(false);+ });+});++describe("mapBoard tasks", () => {+ it("orders cards by list position, then card position", () => {+ const project = mapBoard(+ board({+ lists: [list("l-b", "B", 200), list("l-a", "A", 100)],+ cards: [+ card("c-b2", "l-b", 20),+ card("c-a2", "l-a", 50),+ card("c-b1", "l-b", 10),+ card("c-a1", "l-a", 5),+ ],+ }),+ { owner },+ );++ expect(project.tasks.map((task) => [task.key, task.columnKey])).toEqual([+ ["c-a1", "l-a"],+ ["c-a2", "l-a"],+ ["c-b1", "l-b"],+ ["c-b2", "l-b"],+ ]);+ });++ it("keeps the card's short number and no project key", () => {+ const project = mapBoard(+ board({+ cards: [+ card("c1", "l-todo", 1, { idShort: 14 }),+ card("c2", "l-todo", 2),+ ],+ }),+ { owner },+ );++ expect(project.tasks.map((task) => task.number)).toEqual([14, undefined]);+ expect(project).not.toHaveProperty("key");+ });++ it("archives closed cards and cards in closed lists", () => {+ const project = mapBoard(+ board({+ lists: [+ list("l-old", "Old", 50, true),+ list("l-todo", "To Do", 100),+ list("l-doing", "Doing", 200),+ ],+ cards: [+ card("c-open", "l-doing", 1),+ card("c-closed", "l-doing", 2, { closed: true }),+ card("c-in-closed-list", "l-old", 1),+ ],+ }),+ { owner },+ );++ const byKey = new Map(project.tasks.map((task) => [task.key, task]));+ expect(byKey.get("c-open")).toMatchObject({ columnKey: "l-doing" });+ expect(byKey.get("c-open")?.archived).toBeUndefined();+ expect(byKey.get("c-closed")).toMatchObject({+ columnKey: "l-doing",+ archived: true,+ });+ expect(byKey.get("c-in-closed-list")).toMatchObject({+ columnKey: "l-todo",+ archived: true,+ });+ expect(project.columns.map((column) => column.key)).toEqual([+ "l-todo",+ "l-doing",+ ]);+ });++ it("uses no column when the board has no open lists", () => {+ const project = mapBoard(+ board({+ lists: [list("l-old", "Old", 1, true)],+ cards: [card("c1", "l-old", 1)],+ }),+ { owner },+ );++ expect(project.columns).toEqual([]);+ expect(project.tasks[0]).toMatchObject({ columnKey: null, archived: true });+ });++ it("folds checklists into the description in position order", () => {+ const project = mapBoard(+ board({+ cards: [+ card("c1", "l-todo", 1, { desc: "Ship it\n\n- with **care**" }),+ ],+ checklists: [+ {+ id: "cl-2",+ name: "Launch",+ idCard: "c1",+ pos: 200,+ checkItems: [+ { id: "i3", name: "Announce", state: "incomplete", pos: 2 },+ ],+ },+ {+ id: "cl-1",+ name: "Prep",+ idCard: "c1",+ pos: 100,+ checkItems: [+ { id: "i2", name: "Test", state: "incomplete", pos: 20 },+ { id: "i1", name: "Build", state: "complete", pos: 10 },+ ],+ },+ { id: "cl-empty", name: "Empty", idCard: "c1", pos: 300 },+ {+ id: "cl-other",+ name: "Other",+ idCard: "c-other",+ pos: 1,+ checkItems: [{ id: "i9", name: "x", state: "complete", pos: 1 }],+ },+ ],+ }),+ { owner },+ );++ expect(project.tasks[0]?.description).toBe(+ [+ "Ship it\n\n- with **care**",+ "## Prep\n\n- [x] Build\n- [ ] Test",+ "## Launch\n\n- [ ] Announce",+ ].join("\n\n"),+ );+ });++ it("maps dates, a fixed priority, and the creation time from the card id", () => {+ const project = mapBoard(+ board({+ cards: [+ card("5f0000000000000000000001", "l-todo", 1, {+ due: "2024-05-01T12:00:00.000Z",+ start: "2024-04-01T00:00:00.000Z",+ }),+ ],+ }),+ { owner },+ );++ expect(project.tasks[0]).toMatchObject({+ priority: "no-priority",+ startDate: "2024-04-01T00:00:00.000Z",+ dueDate: "2024-05-01T12:00:00.000Z",+ createdAt: "2020-07-04T04:05:20.000Z",+ });+ });++ it("passes comments through by card id", () => {+ const comment = { author: { name: "Sam" }, body: "Hi" };+ const project = mapBoard(board({ cards: [card("c1", "l-todo", 1)] }), {+ owner,+ comments: new Map([["c1", [comment]]]),+ });++ expect(project.tasks[0]?.comments).toEqual([comment]);+ });++ it("keeps the board description", () => {+ expect(mapBoard(board({ desc: " About this board " }), { owner })).toEqual(+ expect.objectContaining({+ name: "Roadmap",+ description: "About this board",+ }),+ );+ expect(mapBoard(board(), { owner }).description).toBeUndefined();+ });+});++describe("mapBoard labels", () => {+ it("returns only used labels with names and hex colors", () => {+ const project = mapBoard(+ board({+ labels: [+ { id: "lb-bug", name: "Bug", color: "red" },+ { id: "lb-green", name: "", color: "green_dark" },+ { id: "lb-plain", name: "Plain", color: null },+ { id: "lb-high", name: "High", color: "orange" },+ { id: "lb-unused", name: "Unused", color: "blue" },+ ],+ cards: [+ card("c1", "l-todo", 1, {+ idLabels: ["lb-bug", "lb-green", "lb-missing", "lb-bug"],+ }),+ card("c2", "l-todo", 2, { idLabels: ["lb-plain", "lb-high"] }),+ ],+ }),+ { owner },+ );++ expect(project.labels).toEqual([+ { key: "lb-bug", name: "Bug", color: "#f87168" },+ { key: "lb-green", name: "Green dark", color: "#1f845a" },+ { key: "lb-plain", name: "Plain", color: "#6b7280" },+ { key: "lb-high", name: "High", color: "#fea362" },+ ]);+ expect(project.tasks.map((task) => task.labelKeys)).toEqual([+ ["lb-bug", "lb-green"],+ ["lb-plain", "lb-high"],+ ]);+ expect(project.tasks[1]?.priority).toBe("no-priority");+ });++ it("names a label without name or color", () => {+ expect(mapLabel({ id: "x", name: " ", color: null })).toEqual({+ key: "x",+ name: "Label",+ color: "#6b7280",+ });+ });+});++describe("mapBoard assignees and warnings", () => {+ const members: TrelloMember[] = [+ { id: "m-sam", fullName: "Sam Smith", username: "sam" },+ { id: "m-owner", fullName: "Olive Owner", username: "olive" },+ { id: "m-nameless", fullName: "", username: "ghost" },+ ];++ it("assigns the first member and only fills the owner's email", () => {+ const project = mapBoard(+ board({+ members,+ cards: [+ card("c1", "l-todo", 1, { idMembers: ["m-sam", "m-owner"] }),+ card("c2", "l-todo", 2, { idMembers: ["m-owner"] }),+ card("c3", "l-todo", 3, { idMembers: ["m-nameless"] }),+ card("c4", "l-todo", 4, { idMembers: ["m-gone", "m-sam"] }),+ card("c5", "l-todo", 5),+ ],+ }),+ { owner },+ );++ expect(project.tasks.map((task) => task.assignee)).toEqual([+ { name: "Sam Smith" },+ { name: "Olive Owner", email: "[email protected]" },+ { name: "ghost" },+ { name: "Sam Smith" },+ undefined,+ ]);+ expect(project.warnings).toEqual([+ "2 cards had more than one member. Kaneo keeps one assignee per task, so only the first member was kept.",+ "Trello does not share members' email addresses, so assignees are matched to Kaneo members by full name.",+ ]);+ });++ it("skips the email warning when only the token owner is assigned", () => {+ const project = mapBoard(+ board({+ members,+ cards: [card("c1", "l-todo", 1, { idMembers: ["m-owner"] })],+ }),+ { owner },+ );++ expect(project.warnings).toEqual([]);+ });++ it("warns about attachments and other Trello-only data", () => {+ const project = mapBoard(+ board({+ cards: [+ card("c1", "l-todo", 1, { badges: { attachments: 2 } }),+ card("c2", "l-todo", 2, { badges: { attachments: 0 } }),+ ],+ }),+ { owner },+ );++ expect(project.warnings).toEqual([+ "Attachments on 1 card, custom fields, Power-Up data, and stickers are not imported.",+ ]);+ expect(project.relations).toEqual([]);+ });+});++describe("cardCreatedAt", () => {+ it("reads the timestamp from a Trello id and ignores other ids", () => {+ expect(cardCreatedAt("600000000000000000000000")).toBe(+ "2021-01-14T08:25:36.000Z",+ );+ expect(cardCreatedAt("c1")).toBeUndefined();+ });+});diff --git a/packages/importers/src/trello/mapping.ts b/packages/importers/src/trello/mapping.tsnew file mode 100644index 000000000..62c665562--- /dev/null+++ b/packages/importers/src/trello/mapping.ts@@ -0,0 +1,231 @@+import { checklistSection, joinSections, toIsoDate } from "../markdown.js";+import type {+ ImportedColumn,+ ImportedComment,+ ImportedLabel,+ ImportedPerson,+ ImportedProject,+ ImportedTask,+} from "../types.js";+import type {+ TrelloBoard,+ TrelloCard,+ TrelloChecklist,+ TrelloLabel,+ TrelloList,+ TrelloMember,+} from "./client.js";+import { trelloColorName, trelloLabelColor } from "./colors.js";+import { trelloPerson } from "./people.js";++const FINAL_LIST_NAME =+ /^(done|complete|completed|closed|finished|shipped|archive)/i;++const TRELLO_ID = /^[0-9a-f]{24}$/i;++export type BoardContext = {+ owner: TrelloMember;+ comments?: Map<string, ImportedComment[]>;+};++type CardContext = BoardContext & {+ openListIds: Set<string>;+ fallbackColumnKey: string | null;+ labels: Map<string, TrelloLabel>;+ members: Map<string, TrelloMember>;+ checklists: Map<string, TrelloChecklist[]>;+};++export function mapBoard(+ board: TrelloBoard,+ context: BoardContext,+): ImportedProject {+ const lists = byPosition(board.lists ?? []);+ const openLists = lists.filter((list) => !list.closed);+ const listOrder = new Map(lists.map((list, index) => [list.id, index]));+ const cards = sortCards(board.cards ?? [], listOrder);++ const cardContext: CardContext = {+ ...context,+ openListIds: new Set(openLists.map((list) => list.id)),+ fallbackColumnKey: openLists[0]?.id ?? null,+ labels: new Map((board.labels ?? []).map((label) => [label.id, label])),+ members: new Map(+ (board.members ?? []).map((member) => [member.id, member]),+ ),+ checklists: groupChecklists(board.checklists ?? []),+ };++ const tasks = cards.map((card) => mapCard(card, cardContext));+ const description = board.desc?.trim();++ return {+ name: board.name,+ ...(description ? { description } : {}),+ columns: mapColumns(openLists),+ labels: mapUsedLabels(board.labels ?? [], tasks),+ tasks,+ relations: [],+ warnings: boardWarnings(cards, tasks),+ };+}++export function mapColumns(openLists: TrelloList[]): ImportedColumn[] {+ const last = openLists[openLists.length - 1];+ return openLists.map((list) => {+ const name = list.name.trim() || "Untitled list";+ return {+ key: list.id,+ name,+ isFinal: list === last && FINAL_LIST_NAME.test(name),+ };+ });+}++export function mapLabel(label: TrelloLabel): ImportedLabel {+ return {+ key: label.id,+ name: label.name?.trim() || trelloColorName(label.color) || "Label",+ color: trelloLabelColor(label.color),+ };+}++export function cardCreatedAt(cardId: string): string | undefined {+ if (!TRELLO_ID.test(cardId)) return undefined;+ const seconds = Number.parseInt(cardId.slice(0, 8), 16);+ return seconds > 0 ? new Date(seconds * 1000).toISOString() : undefined;+}++function mapCard(card: TrelloCard, context: CardContext): ImportedTask {+ const listIsOpen = context.openListIds.has(card.idList);+ const archived = Boolean(card.closed) || !listIsOpen;+ const startDate = toIsoDate(card.start);+ const dueDate = toIsoDate(card.due);+ const createdAt = cardCreatedAt(card.id);+ const assignee = mapAssignee(card.idMembers ?? [], context);++ return {+ key: card.id,+ ...(typeof card.idShort === "number" ? { number: card.idShort } : {}),+ columnKey: listIsOpen ? card.idList : context.fallbackColumnKey,+ ...(archived ? { archived: true } : {}),+ title: card.name.trim() || "Untitled card",+ description: cardDescription(card, context.checklists.get(card.id) ?? []),+ priority: "no-priority",+ ...(startDate ? { startDate } : {}),+ ...(dueDate ? { dueDate } : {}),+ ...(createdAt ? { createdAt } : {}),+ ...(assignee ? { assignee } : {}),+ labelKeys: [...new Set(card.idLabels ?? [])].filter((id) =>+ context.labels.has(id),+ ),+ comments: context.comments?.get(card.id) ?? [],+ };+}++function cardDescription(+ card: TrelloCard,+ checklists: TrelloChecklist[],+): string {+ return joinSections([+ card.desc,+ ...checklists+ .filter((checklist) => (checklist.checkItems ?? []).length > 0)+ .map((checklist) =>+ checklistSection(+ checklist.name,+ byPosition(checklist.checkItems ?? []).map((item) => ({+ name: item.name,+ done: item.state === "complete",+ })),+ ),+ ),+ ]);+}++function mapAssignee(+ memberIds: string[],+ context: CardContext,+): ImportedPerson | undefined {+ for (const id of memberIds) {+ const member =+ context.members.get(id) ??+ (id === context.owner.id ? context.owner : undefined);+ const person = trelloPerson(member, context.owner);+ if (person) return person;+ }+ return undefined;+}++function mapUsedLabels(+ labels: TrelloLabel[],+ tasks: ImportedTask[],+): ImportedLabel[] {+ const used = new Set(tasks.flatMap((task) => task.labelKeys));+ return labels.filter((label) => used.has(label.id)).map(mapLabel);+}++function boardWarnings(cards: TrelloCard[], tasks: ImportedTask[]): string[] {+ const warnings: string[] = [];++ const sharedCards = cards.filter(+ (card) => (card.idMembers?.length ?? 0) > 1,+ ).length;+ if (sharedCards > 0) {+ warnings.push(+ `${cardCount(sharedCards)} had more than one member. Kaneo keeps one assignee per task, so only the first member was kept.`,+ );+ }++ if (tasks.some((task) => task.assignee && !task.assignee.email)) {+ warnings.push(+ "Trello does not share members' email addresses, so assignees are matched to Kaneo members by full name.",+ );+ }++ const cardsWithAttachments = cards.filter(+ (card) => (card.badges?.attachments ?? 0) > 0,+ ).length;+ if (cardsWithAttachments > 0) {+ warnings.push(+ `Attachments on ${cardCount(cardsWithAttachments)}, custom fields, Power-Up data, and stickers are not imported.`,+ );+ }++ return warnings;+}++function groupChecklists(+ checklists: TrelloChecklist[],+): Map<string, TrelloChecklist[]> {+ const byCard = new Map<string, TrelloChecklist[]>();+ for (const checklist of byPosition(checklists)) {+ const group = byCard.get(checklist.idCard);+ if (group) group.push(checklist);+ else byCard.set(checklist.idCard, [checklist]);+ }+ return byCard;+}++function sortCards(+ cards: TrelloCard[],+ listOrder: Map<string, number>,+): TrelloCard[] {+ const listIndex = (card: TrelloCard) =>+ listOrder.get(card.idList) ?? Number.MAX_SAFE_INTEGER;+ return [...cards].sort(+ (a, b) => listIndex(a) - listIndex(b) || position(a) - position(b),+ );+}++function byPosition<T extends { pos: number }>(items: T[]): T[] {+ return [...items].sort((a, b) => position(a) - position(b));+}++function position(item: { pos: number }): number {+ return Number.isFinite(item.pos) ? item.pos : 0;+}++function cardCount(count: number): string {+ return `${count} ${count === 1 ? "card" : "cards"}`;+}diff --git a/packages/importers/src/trello/people.ts b/packages/importers/src/trello/people.tsnew file mode 100644index 000000000..9edcd5344--- /dev/null+++ b/packages/importers/src/trello/people.ts@@ -0,0 +1,14 @@+import type { ImportedPerson } from "../types.js";+import type { TrelloMember } from "./client.js";++export function trelloPerson(+ member: Partial<TrelloMember> | null | undefined,+ owner: TrelloMember,+): ImportedPerson | undefined {+ if (!member) return undefined;+ const name = member.fullName?.trim() || member.username?.trim();+ const email =+ member.id && member.id === owner.id ? owner.email?.trim() : undefined;+ if (!name && !email) return undefined;+ return { ...(name ? { name } : {}), ...(email ? { email } : {}) };+}diff --git a/packages/importers/src/trello/projects.test.ts b/packages/importers/src/trello/projects.test.tsnew file mode 100644index 000000000..0a8ad4662--- /dev/null+++ b/packages/importers/src/trello/projects.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vite-plus/test";+import { mapBoardSummaries } from "./projects.js";++describe("mapBoardSummaries", () => {+ it("names the workspace or Personal and sorts by board name", () => {+ expect(+ mapBoardSummaries(+ [+ { id: "b2", name: "Zeta", idOrganization: "o1" },+ { id: "b1", name: "alpha", idOrganization: null },+ { id: "b3", name: "Mid", idOrganization: "o-guest" },+ ],+ [{ id: "o1", displayName: "Acme" }],+ ),+ ).toEqual([+ { id: "b1", name: "alpha", detail: "Personal" },+ { id: "b3", name: "Mid" },+ { id: "b2", name: "Zeta", detail: "Acme" },+ ]);+ });+});diff --git a/packages/importers/src/trello/projects.ts b/packages/importers/src/trello/projects.tsnew file mode 100644index 000000000..766cda460--- /dev/null+++ b/packages/importers/src/trello/projects.ts@@ -0,0 +1,29 @@+import type { SourceProject } from "../types.js";+import type { TrelloBoardSummary, TrelloOrganization } from "./client.js";++export function mapBoardSummaries(+ boards: TrelloBoardSummary[],+ organizations: TrelloOrganization[],+): SourceProject[] {+ const workspaceNames = new Map(+ organizations.map((organization) => [+ organization.id,+ organization.displayName?.trim(),+ ]),+ );++ return boards+ .map((board) => {+ const detail = board.idOrganization+ ? workspaceNames.get(board.idOrganization)+ : "Personal";+ return {+ id: board.id,+ name: board.name.trim() || "Untitled board",+ ...(detail ? { detail } : {}),+ };+ })+ .sort((a, b) =>+ a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),+ );+}diff --git a/packages/importers/src/trello/source.test.ts b/packages/importers/src/trello/source.test.tsnew file mode 100644index 000000000..ceb8586ca--- /dev/null+++ b/packages/importers/src/trello/source.test.ts@@ -0,0 +1,461 @@+import { describe, expect, it } from "vite-plus/test";+import type { FetchLike } from "../types.js";+import type { TrelloBoard, TrelloCommentAction } from "./client.js";+import { KEY_REJECTED, TOKEN_REJECTED } from "./errors.js";+import { connectTrello } from "./index.js";++const API_KEY = "0123456789abcdef0123456789abcdef";+const TOKEN = "ATTAsecrettoken0123456789";++type Route = (url: URL) => unknown;++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function fakeTrello(routes: Record<string, Route>) {+ const calls: Array<{ url: URL; headers: Headers }> = [];+ const fetch: FetchLike = async (input, init) => {+ if (init?.signal?.aborted) throw init.signal.reason;+ const url = new URL(input);+ calls.push({ url, headers: new Headers(init?.headers) });+ const route = routes[url.pathname];+ if (!route)+ return new Response("The requested resource was not found.", {+ status: 404,+ });+ const result = route(url);+ return result instanceof Response ? result : json(result);+ };+ return { fetch, calls, paths: () => calls.map((call) => call.url.pathname) };+}++const me = {+ id: "m-owner",+ fullName: "Olive Owner",+ username: "olive",+ email: "[email protected]",+};++const boardContent: TrelloBoard = {+ id: "b1",+ name: "Roadmap",+ desc: "Board notes",+ lists: [+ { id: "l-done", name: "Done", pos: 300, closed: false },+ { id: "l-todo", name: "To Do", pos: 100, closed: false },+ { id: "l-old", name: "Old", pos: 50, closed: true },+ ],+ cards: [+ {+ id: "c2",+ idShort: 2,+ name: "Second",+ idList: "l-done",+ pos: 1,+ idMembers: ["m-sam", "m-owner"],+ idLabels: ["lb-1"],+ },+ {+ id: "c1",+ idShort: 1,+ name: "First",+ desc: "Hello",+ idList: "l-todo",+ pos: 1,+ idMembers: ["m-owner"],+ },+ { id: "c0", name: "Old card", idList: "l-old", pos: 1 },+ ],+ labels: [+ { id: "lb-1", name: "", color: "purple" },+ { id: "lb-2", name: "Unused", color: "blue" },+ ],+ checklists: [+ {+ id: "cl-1",+ name: "Steps",+ idCard: "c1",+ pos: 1,+ checkItems: [{ id: "i1", name: "Do it", state: "complete", pos: 1 }],+ },+ ],+ members: [+ { id: "m-owner", fullName: "Olive Owner", username: "olive" },+ { id: "m-sam", fullName: "Sam Smith", username: "sam" },+ ],+};++function boardRoutes(extra: Record<string, Route> = {}) {+ return {+ "/1/members/me": () => me,+ "/1/boards/b1": () => boardContent,+ ...extra,+ };+}++function commentAction(index: number, cardId: string): TrelloCommentAction {+ return {+ id: `act-${String(index).padStart(5, "0")}`,+ date: new Date(Date.UTC(2024, 0, 1) + index * 60_000).toISOString(),+ idMemberCreator: "m-sam",+ data: { text: `Comment ${index}`, card: { id: cardId } },+ memberCreator: { id: "m-sam", fullName: "Sam Smith", username: "sam" },+ };+}++describe("connectTrello auth", () => {+ it("sends OAuth header auth and never puts credentials in the URL", async () => {+ const trello = fakeTrello(+ boardRoutes({+ "/1/members/me/boards": () => [],+ "/1/members/me/organizations": () => [],+ "/1/boards/b1/actions": () => [],+ }),+ );++ const source = await connectTrello(+ { apiKey: ` ${API_KEY} `, token: `${TOKEN}\n` },+ { fetch: trello.fetch },+ );+ await source.listProjects();+ await source.readProject("b1", { includeComments: true });++ expect(trello.calls.length).toBeGreaterThanOrEqual(5);+ for (const call of trello.calls) {+ expect(call.headers.get("authorization")).toBe(+ `OAuth oauth_consumer_key="${API_KEY}", oauth_token="${TOKEN}"`,+ );+ expect(call.url.origin).toBe("https://api.trello.com");+ expect(call.url.href).not.toContain(API_KEY);+ expect(call.url.href).not.toContain(TOKEN);+ expect(call.url.searchParams.has("key")).toBe(false);+ expect(call.url.searchParams.has("token")).toBe(false);+ }+ expect(trello.calls[0]?.url.pathname).toBe("/1/members/me");+ expect(trello.calls[0]?.url.searchParams.get("fields")).toBe(+ "id,fullName,username,email",+ );+ });++ it("explains a rejected token without echoing it", async () => {+ const trello = fakeTrello({+ "/1/members/me": () => new Response("invalid token", { status: 401 }),+ });++ const error = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ ).catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe(TOKEN_REJECTED);+ expect((error as Error).message).not.toContain(TOKEN);+ });++ it("explains a rejected API key", async () => {+ const trello = fakeTrello({+ "/1/members/me": () => new Response("invalid key", { status: 401 }),+ });++ await expect(+ connectTrello({ apiKey: API_KEY, token: TOKEN }, { fetch: trello.fetch }),+ ).rejects.toThrow(KEY_REJECTED);+ });++ it("rejects malformed or missing credentials before calling Trello", async () => {+ const trello = fakeTrello(boardRoutes());++ await expect(+ connectTrello({ apiKey: "", token: TOKEN }, { fetch: trello.fetch }),+ ).rejects.toThrow("A Trello API key is required.");+ await expect(+ connectTrello({ apiKey: API_KEY, token: " " }, { fetch: trello.fetch }),+ ).rejects.toThrow(+ "Paste the token Trello shows after you authorize Kaneo.",+ );+ const error = await connectTrello(+ { apiKey: API_KEY, token: 'ATTA"bad token' },+ { fetch: trello.fetch },+ ).then(+ () => undefined,+ (caught: unknown) => caught as Error,+ );+ expect(error?.message).toMatch(/does not look like a Trello token/);+ expect(error?.message).not.toContain("bad token");+ expect(trello.calls).toHaveLength(0);+ });++ it("reports a token that expires later on", async () => {+ let expired = false;+ const trello = fakeTrello({+ "/1/members/me": () => me,+ "/1/boards/b1": () =>+ expired ? new Response("invalid token", { status: 401 }) : boardContent,+ });+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );+ expired = true;++ await expect(+ source.readProject("b1", { includeComments: false }),+ ).rejects.toThrow(TOKEN_REJECTED);+ expect(trello.paths()).not.toContain("/1/boards/b1/lists");+ });+});++describe("listProjects", () => {+ it("lists open boards with their workspace names", async () => {+ const trello = fakeTrello({+ "/1/members/me": () => me,+ "/1/members/me/boards": () => [+ {+ id: "b2",+ name: "Website",+ url: "https://trello.com/b/2",+ idOrganization: "o1",+ },+ {+ id: "b1",+ name: "Errands",+ url: "https://trello.com/b/1",+ idOrganization: null,+ },+ ],+ "/1/members/me/organizations": () => [{ id: "o1", displayName: "Acme" }],+ });+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );++ expect(await source.listProjects()).toEqual([+ { id: "b1", name: "Errands", detail: "Personal" },+ { id: "b2", name: "Website", detail: "Acme" },+ ]);+ const boardsCall = trello.calls.find(+ (call) => call.url.pathname === "/1/members/me/boards",+ );+ expect(boardsCall?.url.searchParams.get("filter")).toBe("open");+ expect(boardsCall?.url.searchParams.get("fields")).toBe(+ "name,url,idOrganization",+ );+ });+});++describe("readProject", () => {+ it("reads the whole board in one call", async () => {+ const trello = fakeTrello(boardRoutes());+ const progress: string[] = [];+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );++ const project = await source.readProject("b1", {+ includeComments: false,+ onProgress: (message) => progress.push(message),+ });++ expect(progress).toEqual(["Reading board"]);+ expect(trello.paths()).toEqual(["/1/members/me", "/1/boards/b1"]);+ const query = trello.calls[1]?.url.searchParams;+ expect(query?.get("cards")).toBe("all");+ expect(query?.get("lists")).toBe("all");+ expect(query?.get("checklists")).toBe("all");+ expect(query?.get("card_fields")).toContain("badges");+ expect(query?.get("card_fields")?.split(",")).toContain("idShort");++ expect(project).toEqual({+ name: "Roadmap",+ description: "Board notes",+ columns: [+ { key: "l-todo", name: "To Do", isFinal: false },+ { key: "l-done", name: "Done", isFinal: true },+ ],+ labels: [{ key: "lb-1", name: "Purple", color: "#9f8fef" }],+ tasks: [+ {+ key: "c0",+ columnKey: "l-todo",+ archived: true,+ title: "Old card",+ description: "",+ priority: "no-priority",+ labelKeys: [],+ comments: [],+ },+ {+ key: "c1",+ number: 1,+ columnKey: "l-todo",+ title: "First",+ description: "Hello\n\n## Steps\n\n- [x] Do it",+ priority: "no-priority",+ assignee: { name: "Olive Owner", email: "[email protected]" },+ labelKeys: [],+ comments: [],+ },+ {+ key: "c2",+ number: 2,+ columnKey: "l-done",+ title: "Second",+ description: "",+ priority: "no-priority",+ assignee: { name: "Sam Smith" },+ labelKeys: ["lb-1"],+ comments: [],+ },+ ],+ relations: [],+ warnings: [+ "1 card had more than one member. Kaneo keeps one assignee per task, so only the first member was kept.",+ "Trello does not share members' email addresses, so assignees are matched to Kaneo members by full name.",+ ],+ });+ });++ it("pages comments backwards with before until a short page", async () => {+ const firstPage = Array.from({ length: 1000 }, (_, offset) =>+ commentAction(2000 - offset, offset % 2 === 0 ? "c1" : "c2"),+ );+ const secondPage = [commentAction(5, "c1"), commentAction(3, "c1")];+ const trello = fakeTrello(+ boardRoutes({+ "/1/boards/b1/actions": (url) =>+ url.searchParams.get("before") ? secondPage : firstPage,+ }),+ );+ const progress: string[] = [];+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );++ const project = await source.readProject("b1", {+ includeComments: true,+ onProgress: (message) => progress.push(message),+ });++ const actionCalls = trello.calls.filter(+ (call) => call.url.pathname === "/1/boards/b1/actions",+ );+ expect(actionCalls).toHaveLength(2);+ expect(actionCalls[0]?.url.searchParams.get("filter")).toBe("commentCard");+ expect(actionCalls[0]?.url.searchParams.get("limit")).toBe("1000");+ expect(actionCalls[0]?.url.searchParams.has("before")).toBe(false);+ expect(actionCalls[1]?.url.searchParams.get("before")).toBe("act-01001");+ expect(progress).toEqual([+ "Reading board",+ "Reading comments (1000 so far)",+ "Reading comments (1002 so far)",+ ]);++ const first = project.tasks.find((task) => task.key === "c1");+ const second = project.tasks.find((task) => task.key === "c2");+ expect(first?.comments).toHaveLength(502);+ expect(second?.comments).toHaveLength(500);+ expect(first?.comments.slice(0, 2)).toEqual([+ {+ author: { name: "Sam Smith" },+ body: "Comment 3",+ createdAt: "2024-01-01T00:03:00.000Z",+ },+ {+ author: { name: "Sam Smith" },+ body: "Comment 5",+ createdAt: "2024-01-01T00:05:00.000Z",+ },+ ]);+ expect(first?.comments.at(-1)?.body).toBe("Comment 2000");+ });++ it("splits the board into separate requests when Trello refuses the card count", async () => {+ const { lists, cards, labels, checklists, members, ...summary } =+ boardContent;+ const trello = fakeTrello({+ "/1/members/me": () => me,+ "/1/boards/b1": (url) =>+ url.searchParams.has("cards")+ ? json(+ {+ message: "API_TOO_MANY_CARDS_REQUESTED",+ error: "API_TOO_MANY_CARDS_REQUESTED",+ },+ 400,+ )+ : summary,+ "/1/boards/b1/lists": () => lists,+ "/1/boards/b1/cards/all": () => cards,+ "/1/boards/b1/labels": () => labels,+ "/1/boards/b1/checklists": () => checklists,+ "/1/boards/b1/members": () => members,+ });+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );++ const project = await source.readProject("b1", { includeComments: false });++ expect(trello.paths()).toEqual([+ "/1/members/me",+ "/1/boards/b1",+ "/1/boards/b1",+ "/1/boards/b1/lists",+ "/1/boards/b1/cards/all",+ "/1/boards/b1/labels",+ "/1/boards/b1/checklists",+ "/1/boards/b1/members",+ ]);+ const listsCall = trello.calls[3]?.url.searchParams;+ expect(listsCall?.get("filter")).toBe("all");+ expect(+ trello.calls[4]?.url.searchParams.get("fields")?.split(","),+ ).toContain("idShort");+ expect(trello.calls[5]?.url.searchParams.get("limit")).toBe("1000");++ const reference = await (+ await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: fakeTrello(boardRoutes()).fetch },+ )+ ).readProject("b1", { includeComments: false });+ expect(project).toEqual(reference);+ });++ it("skips comment requests when comments are not wanted", async () => {+ const trello = fakeTrello(boardRoutes());+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );++ await source.readProject("b1", { includeComments: false });++ expect(trello.paths()).not.toContain("/1/boards/b1/actions");+ });++ it("stops when the read is aborted", async () => {+ const trello = fakeTrello(boardRoutes());+ const source = await connectTrello(+ { apiKey: API_KEY, token: TOKEN },+ { fetch: trello.fetch },+ );+ const controller = new AbortController();+ controller.abort(new Error("cancelled"));++ await expect(+ source.readProject("b1", {+ includeComments: false,+ signal: controller.signal,+ }),+ ).rejects.toThrow("cancelled");+ });+});diff --git a/packages/importers/src/trello/source.ts b/packages/importers/src/trello/source.tsnew file mode 100644index 000000000..c34f60902--- /dev/null+++ b/packages/importers/src/trello/source.ts@@ -0,0 +1,106 @@+import type {+ ConnectOptions,+ ImportedProject,+ ImportSource,+ ReadProjectOptions,+} from "../types.js";+import {+ createTrelloClient,+ type TrelloClient,+ type TrelloMember,+} from "./client.js";+import { mapCommentActions } from "./comments.js";+import { describeAuthFailure } from "./errors.js";+import { mapBoard } from "./mapping.js";+import { mapBoardSummaries } from "./projects.js";++export type TrelloCredentials = { apiKey: string; token: string };++const CREDENTIAL_FORMAT = /^[A-Za-z0-9_-]+$/;++export async function connectTrello(+ credentials: TrelloCredentials,+ options: ConnectOptions = {},+): Promise<ImportSource> {+ const { apiKey, token } = normalizeCredentials(credentials);+ const client = createTrelloClient({+ apiKey,+ token,+ fetch: options.fetch,+ signal: options.signal,+ });+ const owner = await fetchOwner(client);++ return {+ async listProjects() {+ const boards = await client.listBoards();+ const organizations = await client.listOrganizations();+ return mapBoardSummaries(boards, organizations);+ },+ readProject: (boardId, readOptions) =>+ readBoard(+ client.withSignal(readOptions.signal),+ owner,+ boardId,+ readOptions,+ ),+ };+}++async function readBoard(+ client: TrelloClient,+ owner: TrelloMember,+ boardId: string,+ options: ReadProjectOptions,+): Promise<ImportedProject> {+ options.onProgress?.("Reading board");+ const board = await client.getBoard(boardId);++ if (!options.includeComments) return mapBoard(board, { owner });++ const actions = await client.listCommentActions(boardId, (fetched) =>+ options.onProgress?.(`Reading comments (${fetched} so far)`),+ );+ return mapBoard(board, {+ owner,+ comments: mapCommentActions(actions, owner),+ });+}++async function fetchOwner(client: TrelloClient): Promise<TrelloMember> {+ let me: TrelloMember | null;+ try {+ me = await client.getMe();+ } catch (error) {+ const message = describeAuthFailure(error);+ if (message) throw new Error(message, { cause: error });+ throw error;+ }++ if (!me || typeof me.id !== "string" || me.id.length === 0) {+ throw new Error("Trello did not return the account for this token.");+ }+ return me;+}++function normalizeCredentials(+ credentials: TrelloCredentials,+): TrelloCredentials {+ const apiKey = credentials.apiKey?.trim() ?? "";+ const token = credentials.token?.trim() ?? "";++ if (!apiKey) throw new Error("A Trello API key is required.");+ if (!CREDENTIAL_FORMAT.test(apiKey)) {+ throw new Error("That does not look like a Trello API key.");+ }+ if (!token) {+ throw new Error("Paste the token Trello shows after you authorize Kaneo.");+ }+ if (!CREDENTIAL_FORMAT.test(token)) {+ throw new Error(+ "That does not look like a Trello token. Copy the whole token Trello shows after you click Allow.",+ );+ }++ return { apiKey, token };+}diff --git a/packages/importers/src/types.ts b/packages/importers/src/types.tsnew file mode 100644index 000000000..64ebcbc16--- /dev/null+++ b/packages/importers/src/types.ts@@ -0,0 +1,94 @@+export type FetchLike = (+ input: string,+ init?: RequestInit,+) => Promise<Response>;++export type ImportedPriority =+ | "no-priority"+ | "low"+ | "medium"+ | "high"+ | "urgent";++export type ImportedColumn = {+ key: string;+ name: string;+ isFinal: boolean;+};++export type ImportedLabel = {+ key: string;+ name: string;+ color: string;+};++export type ImportedPerson = {+ name?: string;+ email?: string;+};++export type ImportedComment = {+ author: ImportedPerson;+ body: string;+ createdAt?: string;+};++export type ImportedTask = {+ key: string;+ number?: number;+ columnKey: string | null;+ archived?: boolean;+ title: string;+ description: string;+ priority: ImportedPriority;+ startDate?: string;+ dueDate?: string;+ createdAt?: string;+ assignee?: ImportedPerson;+ labelKeys: string[];+ comments: ImportedComment[];+};++export type ImportedRelationType = "subtask" | "blocks" | "related";++export type ImportedRelation = {+ sourceKey: string;+ targetKey: string;+ type: ImportedRelationType;+};++export type ImportedProject = {+ name: string;+ key?: string;+ description?: string;+ columns: ImportedColumn[];+ labels: ImportedLabel[];+ tasks: ImportedTask[];+ relations: ImportedRelation[];+ warnings: string[];+};++export type SourceProject = {+ id: string;+ name: string;+ detail?: string;+};++export type ReadProjectOptions = {+ includeComments: boolean;+ onProgress?: (message: string) => void;+ signal?: AbortSignal;+};++export type ImportSource = {+ listProjects(): Promise<SourceProject[]>;+ readProject(+ projectId: string,+ options: ReadProjectOptions,+ ): Promise<ImportedProject>;+};++export type ConnectOptions = {+ fetch?: FetchLike;+ signal?: AbortSignal;+};diff --git a/packages/importers/tsconfig.json b/packages/importers/tsconfig.jsonnew file mode 100644index 000000000..561a22631--- /dev/null+++ b/packages/importers/tsconfig.json@@ -0,0 +1,12 @@+{+ "extends": "../typescript-config/base.json",+ "compilerOptions": {+ "outDir": "dist",+ "rootDir": "src",+ "noEmit": false,+ "declaration": true,+ "declarationMap": false+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist", "src/**/*.test.ts"]+}diff --git a/packages/importers/vite.config.ts b/packages/importers/vite.config.tsnew file mode 100644index 000000000..97474e3c1--- /dev/null+++ b/packages/importers/vite.config.ts@@ -0,0 +1,39 @@+import { defineConfig } from "vite-plus";++export default defineConfig({+ run: {+ tasks: {+ compile: {+ command: "tsc -p tsconfig.json",+ dependsOn: [+ { task: "build", from: ["dependencies", "devDependencies"] },+ ],+ cache: {+ // `auto` can't see what native tools (tsc 7, esbuild) read, so list+ // the sources explicitly or edits replay a stale build.+ input: [+ { auto: true },+ "src/**",+ "tsconfig.json",+ {+ pattern: "packages/typescript-config/base.json",+ base: "workspace",+ },+ "package.json",+ ".env*",+ { pattern: ".env*", base: "workspace" },+ { pattern: "pnpm-lock.yaml", base: "workspace" },+ ],+ output: ["dist/**"],+ },+ },+ "test:run": {+ command: "vp test run --config vitest.config.ts",+ dependsOn: [+ { task: "build", from: ["dependencies", "devDependencies"] },+ ],+ cache: false,+ },+ },+ },+});diff --git a/packages/importers/vitest.config.ts b/packages/importers/vitest.config.tsnew file mode 100644index 000000000..685015850--- /dev/null+++ b/packages/importers/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from "vite-plus";++export default defineConfig({+ test: {+ globals: false,+ environment: "node",+ include: ["src/**/*.test.ts"],+ },+});diff --git a/packages/planka-import/package.json b/packages/planka-import/package.jsonindex 00adfd102..614cfe6cb 100644--- a/packages/planka-import/package.json+++ b/packages/planka-import/package.json@@ -40,12 +40,14 @@"lint": "vp check .","start": "node dist/index.js","test": "vp run test:run",- "test:watch": "vp test --config vitest.config.ts"+ "test:watch": "vp test --config vitest.config.ts",+ "typecheck": "vp run check:types"},"dependencies": {"prompts": "^2.4.2"},"devDependencies": {+ "@kaneo/importers": "workspace:*","@kaneo/typescript-config": "workspace:*","@types/node": "^26.6.2","@types/prompts": "^2.4.9",diff --git a/packages/planka-import/src/index.ts b/packages/planka-import/src/index.tsindex 37f2ee219..d1791d8d1 100644--- a/packages/planka-import/src/index.ts+++ b/packages/planka-import/src/index.ts@@ -1,11 +1,11 @@#!/usr/bin/env nodeimport { writeFile } from "node:fs/promises";import { createRequire } from "node:module";+import { PlankaClient } from "@kaneo/importers/planka";import prompts from "prompts";import { DEFAULT_KANEO_URL, HELP_TEXT, parseArgs } from "./args.js";import { KaneoClient } from "./kaneo.js";import { type BoardReport, type BoardTarget, migrate } from "./migrate.js";-import { PlankaClient } from "./planka.js";const require = createRequire(import.meta.url);const { version } = require("../package.json") as { version: string };diff --git a/packages/planka-import/src/keys.test.ts b/packages/planka-import/src/keys.test.tsdeleted file mode 100644index 2a8173b61..000000000--- a/packages/planka-import/src/keys.test.ts+++ /dev/null@@ -1,59 +0,0 @@-import { describe, expect, it } from "vite-plus/test";-import { toColumnSlug, toProjectKey, uniqueKey } from "./keys.js";--describe("toColumnSlug", () => {- it("lowercases and hyphenates", () => {- expect(toColumnSlug("In Progress")).toBe("in-progress");- expect(toColumnSlug("To Do")).toBe("to-do");- });-- it("strips punctuation and edge hyphens", () => {- expect(toColumnSlug(" Ready?! for review ")).toBe("ready-for-review");- expect(toColumnSlug("--Done--")).toBe("done");- });-- it("keeps non-latin letters", () => {- expect(toColumnSlug("Готово")).toBe("готово");- });-- it("returns empty for names with no alphanumerics", () => {- expect(toColumnSlug("???")).toBe("");- expect(toColumnSlug(" ")).toBe("");- });-});--describe("toProjectKey", () => {- it("uses initials for multi-word names", () => {- expect(toProjectKey("Marketing Website Redesign")).toBe("MWR");- });-- it("uses a prefix for single-word names", () => {- expect(toProjectKey("Engineering")).toBe("ENGINEER");- });-- it("caps at 8 characters", () => {- expect(toProjectKey("a b c d e f g h i j k").length).toBeLessThanOrEqual(8);- });-- it("falls back when the name has nothing usable", () => {- expect(toProjectKey("???")).toBe("PROJ");- expect(toProjectKey("")).toBe("PROJ");- });-});--describe("uniqueKey", () => {- it("returns the candidate when free", () => {- expect(uniqueKey("ENG", new Set())).toBe("ENG");- });-- it("suffixes on collision", () => {- expect(uniqueKey("ENG", new Set(["ENG"]))).toBe("ENG-2");- expect(uniqueKey("ENG", new Set(["ENG", "ENG-2"]))).toBe("ENG-3");- });-- it("stays within the length cap when suffixing", () => {- const result = uniqueKey("ENGINEER", new Set(["ENGINEER"]));- expect(result.length).toBeLessThanOrEqual(8);- expect(result).toBe("ENGINE-2");- });-});diff --git a/packages/planka-import/src/migrate.test.ts b/packages/planka-import/src/migrate.test.tsindex 2193d3825..4a3279048 100644--- a/packages/planka-import/src/migrate.test.ts+++ b/packages/planka-import/src/migrate.test.ts@@ -1,7 +1,7 @@+import type { BoardBundle, PlankaClient } from "@kaneo/importers/planka";import { describe, expect, it } from "vite-plus/test";import type { KaneoClient } from "./kaneo.js";import { migrate } from "./migrate.js";-import type { BoardBundle, PlankaClient } from "./planka.js";type Call = { method: string; args: unknown[] };diff --git a/packages/planka-import/src/migrate.ts b/packages/planka-import/src/migrate.tsindex 05f273513..a20e60e68 100644--- a/packages/planka-import/src/migrate.ts+++ b/packages/planka-import/src/migrate.ts@@ -1,23 +1,22 @@-import { labelColorToHex } from "./colors.js";-import type { KaneoClient } from "./kaneo.js";-import { toProjectKey, uniqueKey } from "./keys.js";import {boardProjectName,buildDescription,DEFAULT_PRIORITY,displayName,formatComment,- planColumns,- sortCards,- toDueDate,-} from "./mapping.js";-import {+ labelColorToHex,MIGRATABLE_LIST_TYPES,type PlankaBoard,type PlankaClient,type PlankaProject,type PlankaUser,-} from "./planka.js";+ planColumns,+ sortCards,+ toDueDate,+ toProjectKey,+ uniqueKey,+} from "@kaneo/importers/planka";+import type { KaneoClient } from "./kaneo.js";export type BoardTarget = {project: PlankaProject;diff --git a/packages/planka-import/src/planka.test.ts b/packages/planka-import/src/planka.test.tsdeleted file mode 100644index 5b06a489d..000000000--- a/packages/planka-import/src/planka.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vite-plus/test";-import { normalizeBaseUrl, PlankaClient } from "./planka.js";--const realFetch = globalThis.fetch;--afterEach(() => {- globalThis.fetch = realFetch;-});--function captureHeaders() {- const calls: Headers[] = [];- globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {- calls.push(new Headers(init?.headers));- return new Response(JSON.stringify({ items: [], included: {} }), {- status: 200,- headers: { "Content-Type": "application/json" },- });- }) as unknown as typeof fetch;- return calls;-}--describe("PlankaClient auth headers", () => {- it("sends an API key in x-api-key, never as a bearer", async () => {- const calls = captureHeaders();- await new PlankaClient({- baseUrl: "https://planka.example.com",- apiKey: "secret-key",- }).listProjects();-- expect(calls[0]?.get("x-api-key")).toBe("secret-key");- expect(calls[0]?.get("authorization")).toBeNull();- });-- it("sends a session token as a bearer", async () => {- const calls = captureHeaders();- await new PlankaClient({- baseUrl: "https://planka.example.com",- token: "jwt-token",- }).listProjects();-- expect(calls[0]?.get("authorization")).toBe("Bearer jwt-token");- expect(calls[0]?.get("x-api-key")).toBeNull();- });-- it("prefers the token when both are supplied", async () => {- const calls = captureHeaders();- await new PlankaClient({- baseUrl: "https://planka.example.com",- token: "jwt-token",- apiKey: "secret-key",- }).listProjects();-- expect(calls[0]?.get("authorization")).toBe("Bearer jwt-token");- expect(calls[0]?.get("x-api-key")).toBeNull();- });-});--describe("isAuthenticated", () => {- it("is true with either credential and false with neither", () => {- const base = "https://planka.example.com";- expect(new PlankaClient({ baseUrl: base }).isAuthenticated).toBe(false);- expect(- new PlankaClient({ baseUrl: base, token: "t" }).isAuthenticated,- ).toBe(true);- expect(- new PlankaClient({ baseUrl: base, apiKey: "k" }).isAuthenticated,- ).toBe(true);- });-});--describe("normalizeBaseUrl", () => {- it("strips trailing slashes and assumes https", () => {- expect(normalizeBaseUrl("planka.example.com/")).toBe(- "https://planka.example.com",- );- expect(normalizeBaseUrl("http://localhost:3000//")).toBe(- "http://localhost:3000",- );- });-});diff --git a/packages/planka-import/tsconfig.json b/packages/planka-import/tsconfig.jsonindex 561a22631..522708597 100644--- a/packages/planka-import/tsconfig.json+++ b/packages/planka-import/tsconfig.json@@ -1,12 +1,10 @@{"extends": "../typescript-config/base.json","compilerOptions": {- "outDir": "dist",- "rootDir": "src",- "noEmit": false,- "declaration": true,- "declarationMap": false+ "noEmit": true,+ "declaration": false,+ "declarationMap": false,+ "types": ["node"]},- "include": ["src/**/*.ts"],- "exclude": ["node_modules", "dist", "src/**/*.test.ts"]+ "include": ["src/**/*.ts", "vite.config.ts", "vitest.config.ts"]}diff --git a/packages/planka-import/vite.config.ts b/packages/planka-import/vite.config.tsindex 97474e3c1..911b19775 100644--- a/packages/planka-import/vite.config.ts+++ b/packages/planka-import/vite.config.ts@@ -1,10 +1,24 @@import { defineConfig } from "vite-plus";export default defineConfig({+ pack: {+ entry: { index: "src/index.ts" },+ format: "esm",+ platform: "node",+ target: "node20",+ outDir: "dist",+ clean: true,+ dts: false,+ fixedExtension: false,+ report: false,+ deps: {+ onlyBundle: [],+ },+ },run: {tasks: {compile: {- command: "tsc -p tsconfig.json",+ command: "vp pack",dependsOn: [{ task: "build", from: ["dependencies", "devDependencies"] },],@@ -20,6 +34,7 @@ export default defineConfig({base: "workspace",},"package.json",+ { pattern: "packages/importers/dist/**", base: "workspace" },".env*",{ pattern: ".env*", base: "workspace" },{ pattern: "pnpm-lock.yaml", base: "workspace" },@@ -27,6 +42,13 @@ export default defineConfig({output: ["dist/**"],},},+ "check:types": {+ command: "tsc -p tsconfig.json",+ dependsOn: [+ { task: "build", from: ["dependencies", "devDependencies"] },+ ],+ cache: false,+ },"test:run": {command: "vp test run --config vitest.config.ts",dependsOn: [diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3b39b8498..be746f1f3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -133,6 +133,9 @@ importers:'@kaneo/email':specifier: workspace:*version: link:../../packages/email+ '@kaneo/importers':+ specifier: workspace:*+ version: link:../../packages/importers'@kaneo/mcp':specifier: workspace:*version: link:../../packages/mcp@@ -711,6 +714,31 @@ importers:specifier: 'catalog:'version: 1.0.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])+ packages/importers:+ dependencies:+ turndown:+ specifier: ^7.2.4+ version: 7.2.4+ turndown-plugin-gfm:+ specifier: ^1.0.2+ version: 1.0.2+ devDependencies:+ '@kaneo/typescript-config':+ specifier: workspace:*+ version: link:../typescript-config+ '@types/node':+ specifier: ^26.6.2+ version: 26.6.3+ '@types/turndown':+ specifier: ^5.0.5+ version: 5.0.6+ typescript:+ specifier: ^7.0.2+ version: 7.0.2+ vite-plus:+ specifier: 'catalog:'+ version: 1.0.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])+packages/libs:devDependencies:'@kaneo/api':@@ -800,6 +828,9 @@ importers:specifier: ^2.4.2version: 2.4.2devDependencies:+ '@kaneo/importers':+ specifier: workspace:*+ version: link:../importers'@kaneo/typescript-config':specifier: workspace:*version: link:../typescript-config@@ -4957,6 +4988,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg==}+'@types/[email protected]':resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}@@ -13808,6 +13842,8 @@ snapshots:'@types/[email protected]':optional: true+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}