@ship-cli/opencode 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.ts ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Pure utility functions for the Ship OpenCode Plugin.
3
+ * These are separated from the main plugin for testability.
4
+ */
5
+
6
+ import * as Schema from "effect/Schema";
7
+
8
+ // =============================================================================
9
+ // Types (exported for testing)
10
+ // =============================================================================
11
+
12
+ export interface ShipTask {
13
+ identifier: string;
14
+ title: string;
15
+ description?: string;
16
+ priority: string;
17
+ status: string;
18
+ state?: string;
19
+ labels: string[];
20
+ url: string;
21
+ branchName?: string;
22
+ subtasks?: ShipSubtask[];
23
+ milestoneId?: string | null;
24
+ milestoneName?: string | null;
25
+ }
26
+
27
+ export interface ShipSubtask {
28
+ id: string;
29
+ identifier: string;
30
+ title: string;
31
+ state: string;
32
+ stateType: string;
33
+ isDone: boolean;
34
+ }
35
+
36
+ // =============================================================================
37
+ // JSON Extraction
38
+ // =============================================================================
39
+
40
+ /**
41
+ * Schema for validating that a string is valid JSON.
42
+ */
43
+ const JsonString = Schema.parseJson();
44
+ const validateJson = Schema.decodeUnknownOption(JsonString);
45
+
46
+ /**
47
+ * Extract JSON from CLI output by finding valid JSON object or array.
48
+ *
49
+ * The CLI may output non-JSON content before the actual JSON response (e.g., spinner
50
+ * output, progress messages). Additionally, task descriptions may contain JSON code
51
+ * blocks which could be incorrectly matched if we search from the start.
52
+ *
53
+ * This function finds all potential JSON start positions and validates each candidate
54
+ * using Schema.parseJson(). We prioritize top-level JSON (no leading whitespace) to
55
+ * avoid matching nested objects inside arrays.
56
+ *
57
+ * @param output - Raw CLI output that may contain JSON
58
+ * @returns Extracted JSON string, or original output if no valid JSON found
59
+ */
60
+ export const extractJson = (output: string): string => {
61
+ // Find all potential JSON start positions (lines starting with { or [)
62
+ // The regex captures leading whitespace to distinguish top-level vs nested JSON
63
+ const matches = [...output.matchAll(/^(\s*)([[{])/gm)];
64
+ if (matches.length === 0) {
65
+ return output;
66
+ }
67
+
68
+ // Separate top-level matches (no leading whitespace) from nested ones
69
+ const topLevelMatches: Array<{ index: number }> = [];
70
+ const nestedMatches: Array<{ index: number }> = [];
71
+
72
+ for (const match of matches) {
73
+ if (match.index === undefined) continue;
74
+ const leadingWhitespace = match[1];
75
+ // Top-level JSON starts at column 0 (no leading whitespace)
76
+ if (leadingWhitespace === "") {
77
+ topLevelMatches.push({ index: match.index });
78
+ } else {
79
+ nestedMatches.push({ index: match.index });
80
+ }
81
+ }
82
+
83
+ // Try top-level matches first (most likely to be the actual response)
84
+ // Then fall back to nested matches if needed
85
+ const orderedMatches = [...topLevelMatches, ...nestedMatches];
86
+
87
+ for (const match of orderedMatches) {
88
+ const candidate = output.slice(match.index).trim();
89
+ // Validate using Schema.parseJson() - returns Option.some if valid
90
+ if (validateJson(candidate)._tag === "Some") {
91
+ return candidate;
92
+ }
93
+ }
94
+
95
+ // Fallback to original output if no valid JSON found
96
+ return output;
97
+ };
98
+
99
+ // =============================================================================
100
+ // Formatters
101
+ // =============================================================================
102
+
103
+ /**
104
+ * Format a list of tasks for display.
105
+ *
106
+ * @param tasks - Array of tasks to format
107
+ * @returns Formatted string with priority indicators and aligned columns
108
+ */
109
+ export const formatTaskList = (tasks: ShipTask[]): string =>
110
+ tasks
111
+ .map((t) => {
112
+ const priority = t.priority === "urgent" ? "[!]" : t.priority === "high" ? "[^]" : " ";
113
+ return `${priority} ${t.identifier.padEnd(10)} ${(t.state || t.status).padEnd(12)} ${t.title}`;
114
+ })
115
+ .join("\n");
116
+
117
+ /**
118
+ * Format task details for display.
119
+ *
120
+ * @param task - Task to format
121
+ * @returns Formatted markdown string with task details
122
+ */
123
+ export const formatTaskDetails = (task: ShipTask): string => {
124
+ let output = `# ${task.identifier}: ${task.title}
125
+
126
+ **Status:** ${task.state || task.status}
127
+ **Priority:** ${task.priority}
128
+ **Labels:** ${task.labels.length > 0 ? task.labels.join(", ") : "none"}
129
+ **URL:** ${task.url}`;
130
+
131
+ if (task.branchName) {
132
+ output += `\n**Branch:** ${task.branchName}`;
133
+ }
134
+
135
+ if (task.description) {
136
+ output += `\n\n## Description\n\n${task.description}`;
137
+ }
138
+
139
+ if (task.subtasks && task.subtasks.length > 0) {
140
+ output += `\n\n## Subtasks\n`;
141
+ for (const subtask of task.subtasks) {
142
+ const statusIndicator = subtask.isDone ? "[x]" : "[ ]";
143
+ output += `\n${statusIndicator} ${subtask.identifier}: ${subtask.title} (${subtask.state})`;
144
+ }
145
+ }
146
+
147
+ return output;
148
+ };
149
+
150
+ // =============================================================================
151
+ // Guidance Helper
152
+ // =============================================================================
153
+
154
+ /**
155
+ * Options for the addGuidance helper function.
156
+ */
157
+ export interface GuidanceOptions {
158
+ /** Explicit working directory path (shown when workspace changes) */
159
+ workdir?: string;
160
+ /** Whether to show skill reminder */
161
+ skill?: boolean;
162
+ /** Contextual note/message */
163
+ note?: string;
164
+ }
165
+
166
+ /**
167
+ * Helper function to format guidance blocks consistently.
168
+ * Reduces repetition and ensures consistent format across all actions.
169
+ *
170
+ * @param next - Suggested next actions (e.g., "action=done | action=ready")
171
+ * @param opts - Optional workdir, skill reminder, and note
172
+ * @returns Formatted guidance string to append to command output
173
+ */
174
+ export const addGuidance = (next: string, opts?: GuidanceOptions): string => {
175
+ let g = `\n---\nNext: ${next}`;
176
+ if (opts?.workdir) g += `\nWorkdir: ${opts.workdir}`;
177
+ if (opts?.skill) g += `\nIMPORTANT: Load skill first → skill(name="ship-cli")`;
178
+ if (opts?.note) g += `\nNote: ${opts.note}`;
179
+ return g;
180
+ };
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024-present <PLACEHOLDER>
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.