sanity-plugin-seo-copilot 0.2.5 → 0.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1310 -625
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1332 -647
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -2
- package/src/components/ChatPanel.tsx +5 -3
- package/src/components/FeedbackButton.tsx +6 -1
- package/src/components/KeywordPanel.tsx +179 -6
- package/src/components/OnboardingPopup.tsx +108 -0
- package/src/components/SEOCopilotPanel.tsx +160 -9
- package/src/components/ShimmerLoader.tsx +4 -0
- package/src/components/TabBar.tsx +3 -0
- package/src/components/styles.ts +8 -0
- package/src/components/tabs/AEOTab.tsx +4 -2
- package/src/components/tabs/LinkingTab.tsx +85 -8
- package/src/components/tabs/MetaTab.tsx +32 -119
- package/src/components/tabs/SummaryTab.tsx +19 -4
- package/src/components/tabs/TechnicalTab.tsx +118 -8
- package/src/hooks/useDocumentContent.ts +48 -47
- package/src/hooks/useKeywordAnalysis.ts +81 -48
- package/src/hooks/useSEOChat.ts +49 -9
- package/src/inspector.ts +0 -1
- package/src/lib/api.ts +30 -10
- package/src/lib/documentExtract.ts +268 -257
- package/src/lib/scoring.ts +42 -15
- package/src/lib/summary.ts +121 -41
- package/src/lib/utils.ts +35 -0
|
@@ -80,6 +80,10 @@ export function useKeywordAnalysis(
|
|
|
80
80
|
return;
|
|
81
81
|
}
|
|
82
82
|
docVersionRef.current += 1;
|
|
83
|
+
volumeAbortRef.current?.abort();
|
|
84
|
+
volumeAbortRef.current = null;
|
|
85
|
+
deepAbortRef.current?.abort();
|
|
86
|
+
deepAbortRef.current = null;
|
|
83
87
|
const fresh = loadCached();
|
|
84
88
|
cached.current = fresh;
|
|
85
89
|
setAnalysisRaw(fresh.analysis);
|
|
@@ -126,6 +130,69 @@ export function useKeywordAnalysis(
|
|
|
126
130
|
// previous document can't write its result onto the document the editor
|
|
127
131
|
// switched to (the regular analysis effect already guards this via `cancelled`).
|
|
128
132
|
const docVersionRef = useRef(0);
|
|
133
|
+
// AbortController for the in-flight volume lookup. Cancelled on doc switch and
|
|
134
|
+
// before each new lookup so only one lookup is ever outstanding at a time.
|
|
135
|
+
const volumeAbortRef = useRef<AbortController | null>(null);
|
|
136
|
+
const deepAbortRef = useRef<AbortController | null>(null);
|
|
137
|
+
|
|
138
|
+
// Abort any in-flight volume lookup or deep analysis when the hook unmounts so a late
|
|
139
|
+
// resolver can't run after teardown and we don't waste backend (Claude/SEMrush) spend.
|
|
140
|
+
useEffect(() => () => {
|
|
141
|
+
volumeAbortRef.current?.abort();
|
|
142
|
+
deepAbortRef.current?.abort();
|
|
143
|
+
}, []);
|
|
144
|
+
|
|
145
|
+
const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
|
|
146
|
+
setIsVolumesLoading(true);
|
|
147
|
+
const myVersion = docVersionRef.current;
|
|
148
|
+
|
|
149
|
+
const lookupTerms = terms || (() => {
|
|
150
|
+
const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
|
|
151
|
+
return [
|
|
152
|
+
...new Set([
|
|
153
|
+
...candidateTerms,
|
|
154
|
+
analysisResult.primaryKeyword.term,
|
|
155
|
+
...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
|
|
156
|
+
...analysisResult.missingKeywords.map((kw) => kw.term),
|
|
157
|
+
]),
|
|
158
|
+
];
|
|
159
|
+
})();
|
|
160
|
+
|
|
161
|
+
if (lookupTerms.length === 0) {
|
|
162
|
+
setIsVolumesLoading(false);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Cancel any previous in-flight lookup before starting a new one
|
|
167
|
+
volumeAbortRef.current?.abort();
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
volumeAbortRef.current = controller;
|
|
170
|
+
|
|
171
|
+
lookupKeywords(apiUrl, lookupTerms, controller.signal)
|
|
172
|
+
.then(({ results }) => {
|
|
173
|
+
if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
|
|
174
|
+
// Add new results to persistent cache
|
|
175
|
+
results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
|
|
176
|
+
// Re-apply all cached volumes to current analysis
|
|
177
|
+
const current = lastAnalysisRef.current || analysisResult;
|
|
178
|
+
const merged = mergeVolumes(current, volumeMapRef.current);
|
|
179
|
+
lastAnalysisRef.current = merged;
|
|
180
|
+
setAnalysisRaw(merged);
|
|
181
|
+
try {
|
|
182
|
+
const prev = loadCached();
|
|
183
|
+
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
|
|
184
|
+
} catch { /* ignore */ }
|
|
185
|
+
setIsVolumesLoading(false);
|
|
186
|
+
})
|
|
187
|
+
.catch((err) => {
|
|
188
|
+
if (err instanceof Error && err.name === "AbortError") return;
|
|
189
|
+
if (docVersionRef.current !== myVersion) return;
|
|
190
|
+
setIsVolumesLoading(false);
|
|
191
|
+
});
|
|
192
|
+
}, [apiUrl, cacheKey]);
|
|
193
|
+
|
|
194
|
+
const doVolumeLookupRef = useRef(doVolumeLookup);
|
|
195
|
+
useEffect(() => { doVolumeLookupRef.current = doVolumeLookup; }, [doVolumeLookup]);
|
|
129
196
|
|
|
130
197
|
useEffect(() => {
|
|
131
198
|
if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
|
|
@@ -134,10 +201,11 @@ export function useKeywordAnalysis(
|
|
|
134
201
|
}
|
|
135
202
|
|
|
136
203
|
let cancelled = false;
|
|
204
|
+
const controller = new AbortController();
|
|
137
205
|
setIsLoading(true);
|
|
138
206
|
setError(null);
|
|
139
207
|
|
|
140
|
-
fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary)
|
|
208
|
+
fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal)
|
|
141
209
|
.then((result) => {
|
|
142
210
|
if (cancelled) return;
|
|
143
211
|
const analysisResult = result as SEOAnalysis;
|
|
@@ -158,10 +226,11 @@ export function useKeywordAnalysis(
|
|
|
158
226
|
const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
|
|
159
227
|
|
|
160
228
|
if (uncachedTerms.length > 0) {
|
|
161
|
-
|
|
229
|
+
doVolumeLookupRef.current(analysisResult, uncachedTerms);
|
|
162
230
|
}
|
|
163
231
|
})
|
|
164
232
|
.catch((err) => {
|
|
233
|
+
if (err instanceof Error && err.name === "AbortError") return;
|
|
165
234
|
if (!cancelled) {
|
|
166
235
|
setError(err.message);
|
|
167
236
|
setIsLoading(false);
|
|
@@ -170,51 +239,12 @@ export function useKeywordAnalysis(
|
|
|
170
239
|
|
|
171
240
|
return () => {
|
|
172
241
|
cancelled = true;
|
|
242
|
+
controller.abort();
|
|
173
243
|
};
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const myVersion = docVersionRef.current;
|
|
179
|
-
|
|
180
|
-
const lookupTerms = terms || (() => {
|
|
181
|
-
const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
|
|
182
|
-
return [
|
|
183
|
-
...new Set([
|
|
184
|
-
...candidateTerms,
|
|
185
|
-
analysisResult.primaryKeyword.term,
|
|
186
|
-
...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
|
|
187
|
-
...analysisResult.missingKeywords.map((kw) => kw.term),
|
|
188
|
-
]),
|
|
189
|
-
];
|
|
190
|
-
})();
|
|
191
|
-
|
|
192
|
-
if (lookupTerms.length === 0) {
|
|
193
|
-
setIsVolumesLoading(false);
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
lookupKeywords(apiUrl, lookupTerms)
|
|
198
|
-
.then(({ results }) => {
|
|
199
|
-
if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
|
|
200
|
-
// Add new results to persistent cache
|
|
201
|
-
results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
|
|
202
|
-
// Re-apply all cached volumes to current analysis
|
|
203
|
-
const current = lastAnalysisRef.current || analysisResult;
|
|
204
|
-
const merged = mergeVolumes(current, volumeMapRef.current);
|
|
205
|
-
lastAnalysisRef.current = merged;
|
|
206
|
-
setAnalysisRaw(merged);
|
|
207
|
-
try {
|
|
208
|
-
const prev = loadCached();
|
|
209
|
-
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
|
|
210
|
-
} catch { /* ignore */ }
|
|
211
|
-
setIsVolumesLoading(false);
|
|
212
|
-
})
|
|
213
|
-
.catch(() => {
|
|
214
|
-
if (docVersionRef.current !== myVersion) return;
|
|
215
|
-
setIsVolumesLoading(false);
|
|
216
|
-
});
|
|
217
|
-
}, [apiUrl, cacheKey]);
|
|
244
|
+
// JSON.stringify(documentFields) used instead of documentFields directly to avoid
|
|
245
|
+
// re-running when the caller creates a new object reference with identical contents.
|
|
246
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
247
|
+
}, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
|
|
218
248
|
|
|
219
249
|
const refreshVolumes = useCallback(() => {
|
|
220
250
|
const current = lastAnalysisRef.current || analysis;
|
|
@@ -231,18 +261,21 @@ export function useKeywordAnalysis(
|
|
|
231
261
|
setAeoTextSnapshot(text);
|
|
232
262
|
|
|
233
263
|
const myVersion = docVersionRef.current;
|
|
234
|
-
|
|
264
|
+
deepAbortRef.current?.abort(); const deepController = new AbortController(); deepAbortRef.current = deepController;
|
|
265
|
+
fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, deepController.signal)
|
|
235
266
|
.then((result) => {
|
|
236
267
|
if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
|
|
237
268
|
setDeepAnalysis(result as DeepAnalysis);
|
|
238
269
|
setIsDeepLoading(false);
|
|
239
270
|
})
|
|
240
271
|
.catch((err) => {
|
|
272
|
+
// Aborted (doc switch or unmount) is normal teardown, not an error to surface.
|
|
273
|
+
if (deepController.signal.aborted || err?.name === "AbortError") return;
|
|
241
274
|
if (docVersionRef.current !== myVersion) return;
|
|
242
275
|
setError(err.message);
|
|
243
276
|
setIsDeepLoading(false);
|
|
244
277
|
});
|
|
245
|
-
}, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
|
|
278
|
+
}, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary]);
|
|
246
279
|
|
|
247
280
|
return {
|
|
248
281
|
analysis,
|
package/src/hooks/useSEOChat.ts
CHANGED
|
@@ -15,6 +15,7 @@ interface KeywordPanelData {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
function getLocalUserId(): string {
|
|
18
|
+
if (typeof window === 'undefined') return 'anonymous';
|
|
18
19
|
const key = "seo-copilot-user-id";
|
|
19
20
|
try {
|
|
20
21
|
let id = localStorage.getItem(key);
|
|
@@ -46,13 +47,15 @@ export function useSEOChat(
|
|
|
46
47
|
}, [chatCacheKey]);
|
|
47
48
|
|
|
48
49
|
const [messages, setMessagesRaw] = useState<ChatMessage[]>(loadCachedMessages);
|
|
50
|
+
// Ref always mirrors messages state so sendMessage doesn't need messages in its
|
|
51
|
+
// dependency array (avoiding a re-creation on every streamed token).
|
|
52
|
+
const messagesRef = useRef<ChatMessage[]>([]);
|
|
53
|
+
|
|
54
|
+
// Simplified wrapper - localStorage persistence moved to a debounced useEffect
|
|
55
|
+
// below so it doesn't fire on every individual token during streaming.
|
|
49
56
|
const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
|
|
50
|
-
setMessagesRaw(
|
|
51
|
-
|
|
52
|
-
try { localStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
|
|
53
|
-
return next;
|
|
54
|
-
});
|
|
55
|
-
}, [chatCacheKey]);
|
|
57
|
+
setMessagesRaw(msgs);
|
|
58
|
+
}, []);
|
|
56
59
|
|
|
57
60
|
const [isStreaming, setIsStreaming] = useState(false);
|
|
58
61
|
const [historyLoaded, setHistoryLoaded] = useState(false);
|
|
@@ -65,6 +68,33 @@ export function useSEOChat(
|
|
|
65
68
|
userId.current = sanityUser.id;
|
|
66
69
|
}
|
|
67
70
|
}, [sanityUser?.id]);
|
|
71
|
+
|
|
72
|
+
// Keep messagesRef in sync with state so sendMessage can read current messages
|
|
73
|
+
// without capturing a stale closure value.
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
messagesRef.current = messages;
|
|
76
|
+
}, [messages]);
|
|
77
|
+
|
|
78
|
+
// Persist chat history to localStorage, debounced so we don't write on every
|
|
79
|
+
// individual token during streaming (only once the stream settles).
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
const timer = setTimeout(() => {
|
|
82
|
+
try { localStorage.setItem(chatCacheKey, JSON.stringify(messages)); } catch {}
|
|
83
|
+
}, 500);
|
|
84
|
+
return () => clearTimeout(timer);
|
|
85
|
+
}, [messages, chatCacheKey]);
|
|
86
|
+
|
|
87
|
+
// AbortController for the in-flight chat stream. Aborted on doc switch and unmount.
|
|
88
|
+
const streamAbortRef = useRef<AbortController | null>(null);
|
|
89
|
+
|
|
90
|
+
// Abort any in-flight stream on unmount to prevent state updates on a dead component.
|
|
91
|
+
useEffect(() => {
|
|
92
|
+
return () => {
|
|
93
|
+
streamAbortRef.current?.abort();
|
|
94
|
+
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
|
|
95
|
+
};
|
|
96
|
+
}, []);
|
|
97
|
+
|
|
68
98
|
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
69
99
|
|
|
70
100
|
// Per-document operation version to invalidate stale in-flight loads
|
|
@@ -79,6 +109,8 @@ export function useSEOChat(
|
|
|
79
109
|
return;
|
|
80
110
|
}
|
|
81
111
|
opVersionRef.current += 1;
|
|
112
|
+
streamAbortRef.current?.abort();
|
|
113
|
+
streamAbortRef.current = null;
|
|
82
114
|
setMessagesRaw(loadCachedMessages());
|
|
83
115
|
setIsStreaming(false);
|
|
84
116
|
setHistoryLoaded(false);
|
|
@@ -118,17 +150,23 @@ export function useSEOChat(
|
|
|
118
150
|
async (text: string) => {
|
|
119
151
|
const myVersion = opVersionRef.current;
|
|
120
152
|
const userMessage: ChatMessage = { role: "user", content: text };
|
|
121
|
-
|
|
153
|
+
// Read from ref so messages is not needed in the dep array - prevents
|
|
154
|
+
// sendMessage from being recreated on every streamed token.
|
|
155
|
+
const updatedMessages = [...messagesRef.current, userMessage];
|
|
122
156
|
setMessages(updatedMessages);
|
|
123
157
|
setIsStreaming(true);
|
|
124
158
|
|
|
159
|
+
const controller = new AbortController();
|
|
160
|
+
streamAbortRef.current = controller;
|
|
161
|
+
|
|
125
162
|
try {
|
|
126
163
|
const stream = await fetchChatStream(
|
|
127
164
|
apiUrl,
|
|
128
165
|
updatedMessages,
|
|
129
166
|
documentText,
|
|
130
167
|
publication,
|
|
131
|
-
keywordPanelData
|
|
168
|
+
keywordPanelData,
|
|
169
|
+
controller.signal
|
|
132
170
|
);
|
|
133
171
|
|
|
134
172
|
if (!stream) {
|
|
@@ -189,6 +227,8 @@ export function useSEOChat(
|
|
|
189
227
|
scheduleSave(finalMessages);
|
|
190
228
|
}
|
|
191
229
|
} catch (err) {
|
|
230
|
+
// Abort is silent - happens on doc switch or unmount, not an error for the editor.
|
|
231
|
+
if (err instanceof Error && err.name === "AbortError") { setIsStreaming(false); return; }
|
|
192
232
|
if (opVersionRef.current !== myVersion) { setIsStreaming(false); return; }
|
|
193
233
|
const errorMsg = err instanceof Error ? err.message : "Chat failed";
|
|
194
234
|
setMessages((prev) => [
|
|
@@ -199,7 +239,7 @@ export function useSEOChat(
|
|
|
199
239
|
|
|
200
240
|
if (opVersionRef.current === myVersion) setIsStreaming(false);
|
|
201
241
|
},
|
|
202
|
-
[
|
|
242
|
+
[apiUrl, documentText, publication, keywordPanelData, scheduleSave]
|
|
203
243
|
);
|
|
204
244
|
|
|
205
245
|
const clearChat = useCallback(() => {
|
package/src/inspector.ts
CHANGED
|
@@ -42,7 +42,6 @@ export function seoCopilotInspector(config: SEOCopilotConfig): DocumentInspector
|
|
|
42
42
|
useMenuItem: () => ({
|
|
43
43
|
title: "SEO Copilot",
|
|
44
44
|
icon: SEOIcon,
|
|
45
|
-
showAsAction: true,
|
|
46
45
|
}),
|
|
47
46
|
component: function SEOCopilotInspector(props: DocumentInspectorProps) {
|
|
48
47
|
return createElement(SEOCopilotPanel, { ...props, config });
|
package/src/lib/api.ts
CHANGED
|
@@ -29,19 +29,23 @@ export async function fetchAnalysis(
|
|
|
29
29
|
publication?: string,
|
|
30
30
|
seedKeywords?: string[],
|
|
31
31
|
documentFields?: DocumentFields,
|
|
32
|
-
focusKeyword?: string
|
|
32
|
+
focusKeyword?: string,
|
|
33
|
+
signal?: AbortSignal
|
|
33
34
|
): Promise<SEOAnalysis | DeepAnalysis> {
|
|
34
35
|
const response = await fetch(`${apiUrl}/api/seo-copilot/analyze`, {
|
|
35
36
|
method: "POST",
|
|
36
37
|
headers: { "Content-Type": "application/json" },
|
|
37
38
|
body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword }),
|
|
39
|
+
signal,
|
|
38
40
|
});
|
|
39
41
|
|
|
40
42
|
const text = await response.text();
|
|
41
43
|
|
|
42
44
|
if (!response.ok) {
|
|
43
45
|
const err = safeParseJson<{ error?: string }>(text);
|
|
44
|
-
throw new Error(
|
|
46
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
47
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
48
|
+
throw new Error("Something went wrong analyzing this document.");
|
|
45
49
|
}
|
|
46
50
|
|
|
47
51
|
return safeParseJson<SEOAnalysis | DeepAnalysis>(text);
|
|
@@ -59,17 +63,21 @@ export async function fetchChatStream(
|
|
|
59
63
|
aeoData?: {
|
|
60
64
|
questionHeadings: { suggestedHeading: string; rationale: string }[];
|
|
61
65
|
};
|
|
62
|
-
}
|
|
66
|
+
},
|
|
67
|
+
signal?: AbortSignal
|
|
63
68
|
): Promise<ReadableStream<Uint8Array> | null> {
|
|
64
69
|
const response = await fetch(`${apiUrl}/api/seo-copilot/chat`, {
|
|
65
70
|
method: "POST",
|
|
66
71
|
headers: { "Content-Type": "application/json" },
|
|
67
72
|
body: JSON.stringify({ messages, documentContext, publication, keywordPanelData }),
|
|
73
|
+
signal,
|
|
68
74
|
});
|
|
69
75
|
|
|
70
76
|
if (!response.ok) {
|
|
71
77
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
72
|
-
throw new Error(
|
|
78
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
79
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
80
|
+
throw new Error("Something went wrong. Please try again.");
|
|
73
81
|
}
|
|
74
82
|
|
|
75
83
|
return response.body;
|
|
@@ -77,17 +85,21 @@ export async function fetchChatStream(
|
|
|
77
85
|
|
|
78
86
|
export async function fetchQuestions(
|
|
79
87
|
apiUrl: string,
|
|
80
|
-
keyword: string
|
|
88
|
+
keyword: string,
|
|
89
|
+
signal?: AbortSignal
|
|
81
90
|
): Promise<{ questions: { question: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
|
|
82
91
|
const response = await fetch(`${apiUrl}/api/seo-copilot/questions`, {
|
|
83
92
|
method: "POST",
|
|
84
93
|
headers: { "Content-Type": "application/json" },
|
|
85
94
|
body: JSON.stringify({ keyword }),
|
|
95
|
+
signal,
|
|
86
96
|
});
|
|
87
97
|
|
|
88
98
|
if (!response.ok) {
|
|
89
99
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
90
|
-
throw new Error(
|
|
100
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
101
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
102
|
+
throw new Error("Something went wrong. Please try again.");
|
|
91
103
|
}
|
|
92
104
|
|
|
93
105
|
return response.json();
|
|
@@ -106,17 +118,21 @@ export async function submitFeedback(
|
|
|
106
118
|
|
|
107
119
|
export async function lookupKeywords(
|
|
108
120
|
apiUrl: string,
|
|
109
|
-
keywords: string[]
|
|
121
|
+
keywords: string[],
|
|
122
|
+
signal?: AbortSignal
|
|
110
123
|
): Promise<{ results: { keyword: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
|
|
111
124
|
const response = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
|
|
112
125
|
method: "POST",
|
|
113
126
|
headers: { "Content-Type": "application/json" },
|
|
114
127
|
body: JSON.stringify({ keywords }),
|
|
128
|
+
signal,
|
|
115
129
|
});
|
|
116
130
|
|
|
117
131
|
if (!response.ok) {
|
|
118
132
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
119
|
-
throw new Error(
|
|
133
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
134
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
135
|
+
throw new Error("Something went wrong. Please try again.");
|
|
120
136
|
}
|
|
121
137
|
|
|
122
138
|
return response.json();
|
|
@@ -143,7 +159,8 @@ export async function fetchContentSuggestions(
|
|
|
143
159
|
apiUrl: string,
|
|
144
160
|
content: string,
|
|
145
161
|
primaryKeyword: string,
|
|
146
|
-
publication?: string
|
|
162
|
+
publication?: string,
|
|
163
|
+
signal?: AbortSignal
|
|
147
164
|
): Promise<ContentSuggestions> {
|
|
148
165
|
const empty: ContentSuggestions = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
|
|
149
166
|
try {
|
|
@@ -151,6 +168,7 @@ export async function fetchContentSuggestions(
|
|
|
151
168
|
method: "POST",
|
|
152
169
|
headers: { "Content-Type": "application/json" },
|
|
153
170
|
body: JSON.stringify({ content, primaryKeyword, publication }),
|
|
171
|
+
signal,
|
|
154
172
|
});
|
|
155
173
|
if (!res.ok) return empty;
|
|
156
174
|
const data = await res.json().catch(() => null);
|
|
@@ -215,7 +233,8 @@ export async function fetchLinkingSuggestions(
|
|
|
215
233
|
primaryKeyword: string,
|
|
216
234
|
supportingKeywords: string[],
|
|
217
235
|
currentDocumentId?: string,
|
|
218
|
-
publication?: string
|
|
236
|
+
publication?: string,
|
|
237
|
+
signal?: AbortSignal
|
|
219
238
|
): Promise<LinkingSuggestion[]> {
|
|
220
239
|
if (!content || content.trim().length < 50) return [];
|
|
221
240
|
try {
|
|
@@ -223,6 +242,7 @@ export async function fetchLinkingSuggestions(
|
|
|
223
242
|
method: "POST",
|
|
224
243
|
headers: { "Content-Type": "application/json" },
|
|
225
244
|
body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
|
|
245
|
+
signal,
|
|
226
246
|
});
|
|
227
247
|
if (!res.ok) return [];
|
|
228
248
|
const data = await res.json().catch(() => null);
|