@narumitw/pi-firecrawl 0.50.3 → 0.50.5

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.
@@ -2,194 +2,178 @@ import { randomUUID } from "node:crypto";
2
2
  import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import {
6
- DEFAULT_MAX_BYTES,
7
- DEFAULT_MAX_LINES,
8
- formatSize,
9
- truncateHead,
10
- } from "@earendil-works/pi-coding-agent";
5
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
11
6
 
12
7
  export interface FirecrawlResultDetails {
13
- truncated: boolean;
14
- truncatedBy?: "lines" | "bytes";
15
- totalLines: number;
16
- totalBytes: number;
17
- outputLines: number;
18
- outputBytes: number;
19
- fullResponsePath?: string;
8
+ truncated: boolean;
9
+ truncatedBy?: "lines" | "bytes";
10
+ totalLines: number;
11
+ totalBytes: number;
12
+ outputLines: number;
13
+ outputBytes: number;
14
+ fullResponsePath?: string;
20
15
  }
21
16
 
22
17
  interface BoundTextOptions {
23
- maxBytes?: number;
24
- maxLines?: number;
25
- artifactText?: string;
26
- artifactExtension?: "json" | "txt";
18
+ maxBytes?: number;
19
+ maxLines?: number;
20
+ artifactText?: string;
21
+ artifactExtension?: "json" | "txt";
27
22
  }
28
23
 
29
24
  interface BoundTextResult {
30
- text: string;
31
- details: FirecrawlResultDetails;
25
+ text: string;
26
+ details: FirecrawlResultDetails;
32
27
  }
33
28
 
34
29
  interface ResponseArtifactStore {
35
- directoryPromise: Promise<string>;
36
- pendingWrites: Set<Promise<unknown>>;
30
+ directoryPromise: Promise<string>;
31
+ pendingWrites: Set<Promise<unknown>>;
37
32
  }
38
33
 
39
34
  const responseArtifactStores = new WeakMap<object, ResponseArtifactStore>();
40
35
  const closedArtifactOwners = new WeakSet<object>();
41
36
 
42
37
  export async function formatJsonResult(payload: unknown, artifactOwner: object) {
43
- const serialized = JSON.stringify(payload, null, 2) ?? String(payload);
44
- const bounded = await boundResponseText(serialized, artifactOwner);
45
- return {
46
- content: [{ type: "text" as const, text: bounded.text }],
47
- details: bounded.details,
48
- };
38
+ const serialized = JSON.stringify(payload, null, 2) ?? String(payload);
39
+ const bounded = await boundResponseText(serialized, artifactOwner);
40
+ return {
41
+ content: [{ type: "text" as const, text: bounded.text }],
42
+ details: bounded.details,
43
+ };
49
44
  }
50
45
 
51
46
  export async function boundResponseText(
52
- text: string,
53
- artifactOwner: object,
54
- options: BoundTextOptions = {},
47
+ text: string,
48
+ artifactOwner: object,
49
+ options: BoundTextOptions = {},
55
50
  ): Promise<BoundTextResult> {
56
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
57
- const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
58
- const initial = truncateHead(text, { maxBytes, maxLines });
59
- if (!initial.truncated) {
60
- return {
61
- text: initial.content,
62
- details: {
63
- truncated: false,
64
- totalLines: initial.totalLines,
65
- totalBytes: initial.totalBytes,
66
- outputLines: initial.outputLines,
67
- outputBytes: initial.outputBytes,
68
- },
69
- };
70
- }
71
-
72
- const fullResponsePath = await writeResponseArtifact(
73
- options.artifactText ?? text,
74
- options.artifactExtension ?? "json",
75
- artifactOwner,
76
- );
77
- let footer = truncationFooter(initial, fullResponsePath);
78
- let excerptByteBudget = Math.max(0, maxBytes - Buffer.byteLength(footer, "utf8") - 2);
79
- let excerptLineBudget = Math.max(0, maxLines - countLines(footer) - 1);
80
- for (;;) {
81
- const excerpt = truncateHead(text, {
82
- maxBytes: excerptByteBudget,
83
- maxLines: excerptLineBudget,
84
- });
85
- footer = truncationFooter(excerpt, fullResponsePath);
86
- const separator = excerpt.content ? "\n\n" : "";
87
- const content = `${excerpt.content}${separator}${footer}`;
88
- if (Buffer.byteLength(content, "utf8") <= maxBytes && countLines(content) <= maxLines) {
89
- return {
90
- text: content,
91
- details: {
92
- truncated: true,
93
- truncatedBy: initial.truncatedBy ?? undefined,
94
- totalLines: initial.totalLines,
95
- totalBytes: initial.totalBytes,
96
- outputLines: excerpt.outputLines,
97
- outputBytes: excerpt.outputBytes,
98
- fullResponsePath,
99
- },
100
- };
101
- }
102
-
103
- const nextByteBudget = Math.max(
104
- 0,
105
- Math.min(excerptByteBudget, maxBytes - Buffer.byteLength(footer, "utf8") - 2),
106
- );
107
- const nextLineBudget = Math.max(
108
- 0,
109
- Math.min(excerptLineBudget, maxLines - countLines(footer) - 1),
110
- );
111
- if (nextByteBudget === excerptByteBudget && nextLineBudget === excerptLineBudget) {
112
- throw new Error("Firecrawl could not fit its truncation notice within Pi's output limits");
113
- }
114
- excerptByteBudget = nextByteBudget;
115
- excerptLineBudget = nextLineBudget;
116
- }
51
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
52
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
53
+ const initial = truncateHead(text, { maxBytes, maxLines });
54
+ if (!initial.truncated) {
55
+ return {
56
+ text: initial.content,
57
+ details: {
58
+ truncated: false,
59
+ totalLines: initial.totalLines,
60
+ totalBytes: initial.totalBytes,
61
+ outputLines: initial.outputLines,
62
+ outputBytes: initial.outputBytes,
63
+ },
64
+ };
65
+ }
66
+
67
+ const fullResponsePath = await writeResponseArtifact(
68
+ options.artifactText ?? text,
69
+ options.artifactExtension ?? "json",
70
+ artifactOwner,
71
+ );
72
+ let footer = truncationFooter(initial, fullResponsePath);
73
+ let excerptByteBudget = Math.max(0, maxBytes - Buffer.byteLength(footer, "utf8") - 2);
74
+ let excerptLineBudget = Math.max(0, maxLines - countLines(footer) - 1);
75
+ for (;;) {
76
+ const excerpt = truncateHead(text, {
77
+ maxBytes: excerptByteBudget,
78
+ maxLines: excerptLineBudget,
79
+ });
80
+ footer = truncationFooter(excerpt, fullResponsePath);
81
+ const separator = excerpt.content ? "\n\n" : "";
82
+ const content = `${excerpt.content}${separator}${footer}`;
83
+ if (Buffer.byteLength(content, "utf8") <= maxBytes && countLines(content) <= maxLines) {
84
+ return {
85
+ text: content,
86
+ details: {
87
+ truncated: true,
88
+ truncatedBy: initial.truncatedBy ?? undefined,
89
+ totalLines: initial.totalLines,
90
+ totalBytes: initial.totalBytes,
91
+ outputLines: excerpt.outputLines,
92
+ outputBytes: excerpt.outputBytes,
93
+ fullResponsePath,
94
+ },
95
+ };
96
+ }
97
+
98
+ const nextByteBudget = Math.max(0, Math.min(excerptByteBudget, maxBytes - Buffer.byteLength(footer, "utf8") - 2));
99
+ const nextLineBudget = Math.max(0, Math.min(excerptLineBudget, maxLines - countLines(footer) - 1));
100
+ if (nextByteBudget === excerptByteBudget && nextLineBudget === excerptLineBudget) {
101
+ throw new Error("Firecrawl could not fit its truncation notice within Pi's output limits");
102
+ }
103
+ excerptByteBudget = nextByteBudget;
104
+ excerptLineBudget = nextLineBudget;
105
+ }
117
106
  }
118
107
 
119
108
  function truncationFooter(
120
- truncation: Pick<
121
- FirecrawlResultDetails,
122
- "outputLines" | "totalLines" | "outputBytes" | "totalBytes"
123
- >,
124
- fullResponsePath: string,
109
+ truncation: Pick<FirecrawlResultDetails, "outputLines" | "totalLines" | "outputBytes" | "totalBytes">,
110
+ fullResponsePath: string,
125
111
  ) {
126
- return `[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}). Full response saved to: ${fullResponsePath}]`;
112
+ return `[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}). Full response saved to: ${fullResponsePath}]`;
127
113
  }
128
114
 
129
115
  function countLines(content: string) {
130
- if (!content) return 0;
131
- const lines = content.split("\n");
132
- if (content.endsWith("\n")) lines.pop();
133
- return lines.length;
116
+ if (!content) return 0;
117
+ const lines = content.split("\n");
118
+ if (content.endsWith("\n")) lines.pop();
119
+ return lines.length;
134
120
  }
135
121
 
136
122
  function writeResponseArtifact(text: string, extension: "json" | "txt", artifactOwner: object) {
137
- const store = responseArtifactStore(artifactOwner);
138
- const operation = store.directoryPromise.then(async (directory) => {
139
- const path = join(directory, `response-${Date.now()}-${randomUUID()}.${extension}`);
140
- await writeFile(path, text, { mode: 0o600 });
141
- await chmod(path, 0o600);
142
- return path;
143
- });
144
- store.pendingWrites.add(operation);
145
- operation.then(
146
- () => store.pendingWrites.delete(operation),
147
- () => store.pendingWrites.delete(operation),
148
- );
149
- return operation;
123
+ const store = responseArtifactStore(artifactOwner);
124
+ const operation = store.directoryPromise.then(async (directory) => {
125
+ const path = join(directory, `response-${Date.now()}-${randomUUID()}.${extension}`);
126
+ await writeFile(path, text, { mode: 0o600 });
127
+ await chmod(path, 0o600);
128
+ return path;
129
+ });
130
+ store.pendingWrites.add(operation);
131
+ operation.then(
132
+ () => store.pendingWrites.delete(operation),
133
+ () => store.pendingWrites.delete(operation),
134
+ );
135
+ return operation;
150
136
  }
151
137
 
152
138
  function responseArtifactStore(artifactOwner: object) {
153
- if (closedArtifactOwners.has(artifactOwner)) {
154
- throw new Error(
155
- "Firecrawl response arrived after session shutdown; full response was discarded",
156
- );
157
- }
158
- const existing = responseArtifactStores.get(artifactOwner);
159
- if (existing) return existing;
160
-
161
- const store: ResponseArtifactStore = {
162
- directoryPromise: Promise.resolve(""),
163
- pendingWrites: new Set(),
164
- };
165
- store.directoryPromise = mkdtemp(join(tmpdir(), "pi-firecrawl-"))
166
- .then(async (directory) => {
167
- await chmod(directory, 0o700);
168
- return directory;
169
- })
170
- .catch((error) => {
171
- if (responseArtifactStores.get(artifactOwner) === store) {
172
- responseArtifactStores.delete(artifactOwner);
173
- }
174
- throw error;
175
- });
176
- responseArtifactStores.set(artifactOwner, store);
177
- return store;
139
+ if (closedArtifactOwners.has(artifactOwner)) {
140
+ throw new Error("Firecrawl response arrived after session shutdown; full response was discarded");
141
+ }
142
+ const existing = responseArtifactStores.get(artifactOwner);
143
+ if (existing) return existing;
144
+
145
+ const store: ResponseArtifactStore = {
146
+ directoryPromise: Promise.resolve(""),
147
+ pendingWrites: new Set(),
148
+ };
149
+ store.directoryPromise = mkdtemp(join(tmpdir(), "pi-firecrawl-"))
150
+ .then(async (directory) => {
151
+ await chmod(directory, 0o700);
152
+ return directory;
153
+ })
154
+ .catch((error) => {
155
+ if (responseArtifactStores.get(artifactOwner) === store) {
156
+ responseArtifactStores.delete(artifactOwner);
157
+ }
158
+ throw error;
159
+ });
160
+ responseArtifactStores.set(artifactOwner, store);
161
+ return store;
178
162
  }
179
163
 
180
164
  export function openResponseArtifacts(artifactOwner: object) {
181
- closedArtifactOwners.delete(artifactOwner);
165
+ closedArtifactOwners.delete(artifactOwner);
182
166
  }
183
167
 
184
168
  export async function cleanupResponseArtifacts(artifactOwner: object) {
185
- closedArtifactOwners.add(artifactOwner);
186
- const store = responseArtifactStores.get(artifactOwner);
187
- if (!store) return;
188
- responseArtifactStores.delete(artifactOwner);
189
- await Promise.allSettled([...store.pendingWrites]);
190
- try {
191
- await rm(await store.directoryPromise, { recursive: true, force: true });
192
- } catch {
193
- // Best-effort cleanup must not make session shutdown fail.
194
- }
169
+ closedArtifactOwners.add(artifactOwner);
170
+ const store = responseArtifactStores.get(artifactOwner);
171
+ if (!store) return;
172
+ responseArtifactStores.delete(artifactOwner);
173
+ await Promise.allSettled([...store.pendingWrites]);
174
+ try {
175
+ await rm(await store.directoryPromise, { recursive: true, force: true });
176
+ } catch {
177
+ // Best-effort cleanup must not make session shutdown fail.
178
+ }
195
179
  }
package/src/settings.ts CHANGED
@@ -9,197 +9,194 @@ const NEW_SETTINGS_FILE = "pi-firecrawl.json";
9
9
  const LEGACY_SETTINGS_FILE = "pi-firecrawl-settings.json";
10
10
 
11
11
  export interface FirecrawlSettings {
12
- tools: FirecrawlToolName[];
13
- updatedAt: number;
12
+ tools: FirecrawlToolName[];
13
+ updatedAt: number;
14
14
  }
15
15
 
16
16
  export interface SettingsFileOperations {
17
- write(path: string, data: string): Promise<void>;
18
- rename(source: string, destination: string): Promise<void>;
17
+ write(path: string, data: string): Promise<void>;
18
+ rename(source: string, destination: string): Promise<void>;
19
19
  }
20
20
 
21
21
  const DEFAULT_FILE_OPERATIONS: SettingsFileOperations = {
22
- write: (path, data) => writeFile(path, data, "utf8").then(() => undefined),
23
- rename,
22
+ write: (path, data) => writeFile(path, data, "utf8").then(() => undefined),
23
+ rename,
24
24
  };
25
25
 
26
26
  export type SettingsLoadResult =
27
- | { kind: "missing"; notice?: string }
28
- | { kind: "invalid"; reason: string; notice?: string }
29
- | { kind: "loaded"; settings: FirecrawlSettings; notice?: string };
27
+ | { kind: "missing"; notice?: string }
28
+ | { kind: "invalid"; reason: string; notice?: string }
29
+ | { kind: "loaded"; settings: FirecrawlSettings; notice?: string };
30
30
 
31
31
  export async function loadSettings(): Promise<SettingsLoadResult> {
32
- await settingsSaveQueue;
33
- const newPath = settingsFilePath();
34
- const newSettings = await readSettingsFile(newPath);
35
- if (newSettings.kind !== "missing") {
36
- return withLegacyIgnoredNotice(newSettings);
37
- }
38
-
39
- const legacyPath = legacySettingsFilePath();
40
- const legacySettings = await readSettingsFile(legacyPath);
41
- const concurrentlyCreatedSettings = await readSettingsFile(newPath);
42
- if (concurrentlyCreatedSettings.kind !== "missing") {
43
- return withLegacyIgnoredNotice(concurrentlyCreatedSettings);
44
- }
45
- if (legacySettings.kind === "missing") return { kind: "missing" };
46
- if (legacySettings.kind === "invalid") return legacySettings;
47
-
48
- return {
49
- ...legacySettings,
50
- notice: `Using legacy ${LEGACY_SETTINGS_FILE}; rename it to ${NEW_SETTINGS_FILE}. Future saves write ${NEW_SETTINGS_FILE} without modifying the legacy file.`,
51
- };
32
+ await settingsSaveQueue;
33
+ const newPath = settingsFilePath();
34
+ const newSettings = await readSettingsFile(newPath);
35
+ if (newSettings.kind !== "missing") {
36
+ return withLegacyIgnoredNotice(newSettings);
37
+ }
38
+
39
+ const legacyPath = legacySettingsFilePath();
40
+ const legacySettings = await readSettingsFile(legacyPath);
41
+ const concurrentlyCreatedSettings = await readSettingsFile(newPath);
42
+ if (concurrentlyCreatedSettings.kind !== "missing") {
43
+ return withLegacyIgnoredNotice(concurrentlyCreatedSettings);
44
+ }
45
+ if (legacySettings.kind === "missing") return { kind: "missing" };
46
+ if (legacySettings.kind === "invalid") return legacySettings;
47
+
48
+ return {
49
+ ...legacySettings,
50
+ notice: `Using legacy ${LEGACY_SETTINGS_FILE}; rename it to ${NEW_SETTINGS_FILE}. Future saves write ${NEW_SETTINGS_FILE} without modifying the legacy file.`,
51
+ };
52
52
  }
53
53
 
54
54
  interface SettingsDocumentResult {
55
- result: SettingsLoadResult;
56
- document?: Record<string, unknown>;
55
+ result: SettingsLoadResult;
56
+ document?: Record<string, unknown>;
57
57
  }
58
58
 
59
59
  async function readSettingsDocument(filePath: string): Promise<SettingsDocumentResult> {
60
- let text: string;
61
- try {
62
- text = await readFile(filePath, "utf8");
63
- } catch (error) {
64
- if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
65
- return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
66
- }
67
-
68
- try {
69
- const parsed = JSON.parse(text) as unknown;
70
- const settings = normalizeFirecrawlSettings(parsed);
71
- if (settings) {
72
- return {
73
- result: { kind: "loaded", settings },
74
- document: { ...(parsed as Record<string, unknown>) },
75
- };
76
- }
77
- return {
78
- result: {
79
- kind: "invalid",
80
- reason: `${filePath}: expected tools to be an array of Firecrawl tool names`,
81
- },
82
- };
83
- } catch (error) {
84
- return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
85
- }
60
+ let text: string;
61
+ try {
62
+ text = await readFile(filePath, "utf8");
63
+ } catch (error) {
64
+ if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
65
+ return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
66
+ }
67
+
68
+ try {
69
+ const parsed = JSON.parse(text) as unknown;
70
+ const settings = normalizeFirecrawlSettings(parsed);
71
+ if (settings) {
72
+ return {
73
+ result: { kind: "loaded", settings },
74
+ document: { ...(parsed as Record<string, unknown>) },
75
+ };
76
+ }
77
+ return {
78
+ result: {
79
+ kind: "invalid",
80
+ reason: `${filePath}: expected tools to be an array of Firecrawl tool names`,
81
+ },
82
+ };
83
+ } catch (error) {
84
+ return { result: { kind: "invalid", reason: `${filePath}: ${formatError(error)}` } };
85
+ }
86
86
  }
87
87
 
88
88
  async function readSettingsFile(filePath: string): Promise<SettingsLoadResult> {
89
- return (await readSettingsDocument(filePath)).result;
89
+ return (await readSettingsDocument(filePath)).result;
90
90
  }
91
91
 
92
92
  async function withLegacyIgnoredNotice(settings: SettingsLoadResult): Promise<SettingsLoadResult> {
93
- if (!(await fileExists(legacySettingsFilePath()))) return settings;
94
- return {
95
- ...settings,
96
- notice: `Firecrawl legacy settings ignored: ${legacySettingsFilePath()} exists, but ${settingsFilePath()} takes precedence. Delete ${LEGACY_SETTINGS_FILE} after confirming your settings.`,
97
- };
93
+ if (!(await fileExists(legacySettingsFilePath()))) return settings;
94
+ return {
95
+ ...settings,
96
+ notice: `Firecrawl legacy settings ignored: ${legacySettingsFilePath()} exists, but ${settingsFilePath()} takes precedence. Delete ${LEGACY_SETTINGS_FILE} after confirming your settings.`,
97
+ };
98
98
  }
99
99
 
100
100
  async function fileExists(filePath: string) {
101
- try {
102
- await access(filePath, constants.F_OK);
103
- return true;
104
- } catch {
105
- return false;
106
- }
101
+ try {
102
+ await access(filePath, constants.F_OK);
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
107
107
  }
108
108
 
109
109
  async function pathEntryExists(filePath: string) {
110
- try {
111
- await lstat(filePath);
112
- return true;
113
- } catch (error) {
114
- if (isNodeError(error) && error.code === "ENOENT") return false;
115
- throw error;
116
- }
110
+ try {
111
+ await lstat(filePath);
112
+ return true;
113
+ } catch (error) {
114
+ if (isNodeError(error) && error.code === "ENOENT") return false;
115
+ throw error;
116
+ }
117
117
  }
118
118
 
119
119
  export function normalizeFirecrawlSettings(value: unknown): FirecrawlSettings | undefined {
120
- if (!value || typeof value !== "object") return undefined;
121
- const settings = value as { tools?: unknown; updatedAt?: unknown };
122
- if (typeof settings.updatedAt !== "number" || !Number.isFinite(settings.updatedAt)) {
123
- return undefined;
124
- }
125
- if (!Array.isArray(settings.tools)) return undefined;
126
- if (!settings.tools.every(isFirecrawlToolName)) return undefined;
127
- return { tools: orderedUniqueFirecrawlTools(settings.tools), updatedAt: settings.updatedAt };
120
+ if (!value || typeof value !== "object") return undefined;
121
+ const settings = value as { tools?: unknown; updatedAt?: unknown };
122
+ if (typeof settings.updatedAt !== "number" || !Number.isFinite(settings.updatedAt)) {
123
+ return undefined;
124
+ }
125
+ if (!Array.isArray(settings.tools)) return undefined;
126
+ if (!settings.tools.every(isFirecrawlToolName)) return undefined;
127
+ return { tools: orderedUniqueFirecrawlTools(settings.tools), updatedAt: settings.updatedAt };
128
128
  }
129
129
 
130
130
  function isFirecrawlToolName(value: unknown): value is FirecrawlToolName {
131
- return typeof value === "string" && FIRECRAWL_TOOL_NAMES.includes(value as never);
131
+ return typeof value === "string" && FIRECRAWL_TOOL_NAMES.includes(value as never);
132
132
  }
133
133
 
134
134
  function orderedUniqueFirecrawlTools(tools: readonly FirecrawlToolName[]) {
135
- const selectedTools = new Set(tools);
136
- return FIRECRAWL_TOOL_NAMES.filter((toolName) => selectedTools.has(toolName));
135
+ const selectedTools = new Set(tools);
136
+ return FIRECRAWL_TOOL_NAMES.filter((toolName) => selectedTools.has(toolName));
137
137
  }
138
138
 
139
139
  let settingsSaveQueue = Promise.resolve();
140
140
 
141
141
  export function saveSettings(
142
- settings: FirecrawlSettings,
143
- operations: Partial<SettingsFileOperations> = {},
142
+ settings: FirecrawlSettings,
143
+ operations: Partial<SettingsFileOperations> = {},
144
144
  ): Promise<void> {
145
- const normalizedSettings = normalizeFirecrawlSettings(settings);
146
- if (!normalizedSettings) {
147
- return Promise.reject(new Error("Cannot save invalid Firecrawl settings"));
148
- }
149
- const operation = settingsSaveQueue.then(() => saveSettingsNow(normalizedSettings, operations));
150
- settingsSaveQueue = operation.catch(() => undefined);
151
- return operation;
145
+ const normalizedSettings = normalizeFirecrawlSettings(settings);
146
+ if (!normalizedSettings) {
147
+ return Promise.reject(new Error("Cannot save invalid Firecrawl settings"));
148
+ }
149
+ const operation = settingsSaveQueue.then(() => saveSettingsNow(normalizedSettings, operations));
150
+ settingsSaveQueue = operation.catch(() => undefined);
151
+ return operation;
152
152
  }
153
153
 
154
154
  async function saveSettingsNow(
155
- settings: FirecrawlSettings,
156
- operations: Partial<SettingsFileOperations>,
155
+ settings: FirecrawlSettings,
156
+ operations: Partial<SettingsFileOperations>,
157
157
  ): Promise<void> {
158
- const filePath = settingsFilePath();
159
- let current = await readSettingsDocument(filePath);
160
- const replaceCanonical = current.result.kind !== "missing";
161
- if (!replaceCanonical) current = await readSettingsDocument(legacySettingsFilePath());
162
- if (current.result.kind === "invalid") {
163
- throw new Error(`Cannot save Firecrawl settings until you repair ${current.result.reason}`);
164
- }
165
- const nextDocument = {
166
- ...(current.document ?? {}),
167
- tools: [...settings.tools],
168
- updatedAt: settings.updatedAt,
169
- };
170
- await mkdir(dirname(filePath), { recursive: true });
171
- const tempFile = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
172
- try {
173
- await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
174
- tempFile,
175
- `${JSON.stringify(nextDocument, null, 2)}\n`,
176
- );
177
- if (!replaceCanonical && (await pathEntryExists(filePath))) {
178
- throw new Error(`${NEW_SETTINGS_FILE} was created concurrently; reopen settings and retry.`);
179
- }
180
- await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(tempFile, filePath);
181
- } catch (error) {
182
- await rm(tempFile, { force: true }).catch(() => undefined);
183
- throw error;
184
- }
158
+ const filePath = settingsFilePath();
159
+ let current = await readSettingsDocument(filePath);
160
+ const replaceCanonical = current.result.kind !== "missing";
161
+ if (!replaceCanonical) current = await readSettingsDocument(legacySettingsFilePath());
162
+ if (current.result.kind === "invalid") {
163
+ throw new Error(`Cannot save Firecrawl settings until you repair ${current.result.reason}`);
164
+ }
165
+ const nextDocument = {
166
+ ...(current.document ?? {}),
167
+ tools: [...settings.tools],
168
+ updatedAt: settings.updatedAt,
169
+ };
170
+ await mkdir(dirname(filePath), { recursive: true });
171
+ const tempFile = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
172
+ try {
173
+ await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(tempFile, `${JSON.stringify(nextDocument, null, 2)}\n`);
174
+ if (!replaceCanonical && (await pathEntryExists(filePath))) {
175
+ throw new Error(`${NEW_SETTINGS_FILE} was created concurrently; reopen settings and retry.`);
176
+ }
177
+ await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(tempFile, filePath);
178
+ } catch (error) {
179
+ await rm(tempFile, { force: true }).catch(() => undefined);
180
+ throw error;
181
+ }
185
182
  }
186
183
 
187
184
  export function settingsFilePath() {
188
- return join(agentDir(), NEW_SETTINGS_FILE);
185
+ return join(agentDir(), NEW_SETTINGS_FILE);
189
186
  }
190
187
 
191
188
  function legacySettingsFilePath() {
192
- return join(agentDir(), LEGACY_SETTINGS_FILE);
189
+ return join(agentDir(), LEGACY_SETTINGS_FILE);
193
190
  }
194
191
 
195
192
  function agentDir() {
196
- return getAgentDir();
193
+ return getAgentDir();
197
194
  }
198
195
 
199
196
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
200
- return error instanceof Error && "code" in error;
197
+ return error instanceof Error && "code" in error;
201
198
  }
202
199
 
203
200
  function formatError(error: unknown) {
204
- return error instanceof Error ? error.message : String(error);
201
+ return error instanceof Error ? error.message : String(error);
205
202
  }