@initiativesolutions/crm-mcp-server 0.0.0-stage → 0.5.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.
Files changed (79) hide show
  1. package/README.md +192 -2
  2. package/dist/config.d.ts +36 -0
  3. package/dist/config.js +125 -0
  4. package/dist/constants.d.ts +51 -0
  5. package/dist/constants.js +68 -0
  6. package/dist/errors.d.ts +60 -0
  7. package/dist/errors.js +399 -0
  8. package/dist/field-sets.d.ts +37 -0
  9. package/dist/field-sets.js +97 -0
  10. package/dist/fold.d.ts +2 -0
  11. package/dist/fold.js +5 -0
  12. package/dist/guides.d.ts +37 -0
  13. package/dist/guides.js +80 -0
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +28 -0
  16. package/dist/render.d.ts +53 -0
  17. package/dist/render.js +237 -0
  18. package/dist/server.d.ts +25 -0
  19. package/dist/server.js +89 -0
  20. package/dist/services/api-client.d.ts +42 -0
  21. package/dist/services/api-client.js +40 -0
  22. package/dist/services/path.d.ts +9 -0
  23. package/dist/services/path.js +33 -0
  24. package/dist/services/query.d.ts +7 -0
  25. package/dist/services/query.js +56 -0
  26. package/dist/services/transport.d.ts +48 -0
  27. package/dist/services/transport.js +264 -0
  28. package/dist/services/upload-source.d.ts +26 -0
  29. package/dist/services/upload-source.js +206 -0
  30. package/dist/services/write-client.d.ts +34 -0
  31. package/dist/services/write-client.js +57 -0
  32. package/dist/token-source.d.ts +21 -0
  33. package/dist/token-source.js +11 -0
  34. package/dist/tools/deletes.d.ts +3 -0
  35. package/dist/tools/deletes.js +54 -0
  36. package/dist/tools/discovery.d.ts +4 -0
  37. package/dist/tools/discovery.js +165 -0
  38. package/dist/tools/help.d.ts +3 -0
  39. package/dist/tools/help.js +96 -0
  40. package/dist/tools/lines.d.ts +33 -0
  41. package/dist/tools/lines.js +285 -0
  42. package/dist/tools/records.d.ts +14 -0
  43. package/dist/tools/records.js +141 -0
  44. package/dist/tools/relations.d.ts +4 -0
  45. package/dist/tools/relations.js +97 -0
  46. package/dist/tools/schemas.d.ts +76 -0
  47. package/dist/tools/schemas.js +59 -0
  48. package/dist/tools/sync.d.ts +4 -0
  49. package/dist/tools/sync.js +107 -0
  50. package/dist/tools/writes.d.ts +4 -0
  51. package/dist/tools/writes.js +353 -0
  52. package/dist/validation.d.ts +15 -0
  53. package/dist/validation.js +80 -0
  54. package/dist/write-wiring.d.ts +4 -0
  55. package/dist/write-wiring.js +5 -0
  56. package/docs/partners/en/install.md +206 -0
  57. package/docs/partners/fr/install.md +206 -0
  58. package/guides/en/best-practices.md +134 -0
  59. package/guides/en/converting-leads.md +189 -0
  60. package/guides/en/fields-and-formats.md +365 -0
  61. package/guides/en/inventory-documents.md +252 -0
  62. package/guides/en/linking-records.md +266 -0
  63. package/guides/en/price-books.md +233 -0
  64. package/guides/en/querying-records.md +197 -0
  65. package/guides/en/syncing-data.md +276 -0
  66. package/guides/en/uploading-documents.md +194 -0
  67. package/guides/en/writing-records.md +239 -0
  68. package/guides/fr/best-practices.md +134 -0
  69. package/guides/fr/converting-leads.md +189 -0
  70. package/guides/fr/fields-and-formats.md +365 -0
  71. package/guides/fr/inventory-documents.md +252 -0
  72. package/guides/fr/linking-records.md +266 -0
  73. package/guides/fr/price-books.md +233 -0
  74. package/guides/fr/querying-records.md +197 -0
  75. package/guides/fr/syncing-data.md +277 -0
  76. package/guides/fr/uploading-documents.md +194 -0
  77. package/guides/fr/writing-records.md +239 -0
  78. package/guides/manifest.json +174 -0
  79. package/package.json +54 -4
@@ -0,0 +1,48 @@
1
+ import { type ErrorContext } from '../errors.js';
2
+ import type { TokenSource } from '../token-source.js';
3
+ /** What the API told us about the token's remaining quota on this response. */
4
+ export interface RateLimitSnapshot {
5
+ readonly limit: number | null;
6
+ readonly remaining: number | null;
7
+ /** Unix timestamp at which the bucket refills, from X-RateLimit-Reset. */
8
+ readonly resetAt: number | null;
9
+ }
10
+ /** Clock and sleep, injectable so tests never wait in real time. */
11
+ export interface Timing {
12
+ now(): number;
13
+ sleep(ms: number): Promise<void>;
14
+ }
15
+ export declare const REAL_TIMING: Timing;
16
+ export interface ApiResponse<T> {
17
+ readonly body: T;
18
+ /** The HTTP status of the answer, e.g. 201 for a new link and 200 for an existing one. */
19
+ readonly status: number;
20
+ /** From meta.request_id. Quoted back to the assistant on every failure. */
21
+ readonly requestId: string | null;
22
+ readonly rateLimit: RateLimitSnapshot;
23
+ }
24
+ /** What a request carries: a JSON string, a multipart form (no Content-Type set), or nothing. */
25
+ export type RequestPayload = {
26
+ readonly json: string;
27
+ readonly form?: undefined;
28
+ } | {
29
+ readonly form: FormData;
30
+ readonly json?: undefined;
31
+ };
32
+ export declare const OUTCOME_UNKNOWN_STEP = "The change may have been applied. Read the record (or list the most recent records) before you try again.";
33
+ /**
34
+ * The one HTTP implementation both clients use: token retrieval, pacing, the single 429 retry,
35
+ * timeout, body reading and error mapping. With unknownOutcome set (every write) a failure after
36
+ * the request left is WRITE_OUTCOME_UNKNOWN and is never retried.
37
+ */
38
+ export declare class Transport {
39
+ readonly baseUrl: string;
40
+ private readonly tokenSource;
41
+ private readonly fetchImpl;
42
+ private readonly timeoutMs;
43
+ private readonly timing;
44
+ private readonly rate;
45
+ constructor(baseUrl: string, tokenSource: TokenSource, fetchImpl?: typeof fetch, timeoutMs?: number, timing?: Timing);
46
+ send<T>(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', url: string, payload: RequestPayload | undefined, context?: ErrorContext, unknownOutcome?: boolean): Promise<ApiResponse<T>>;
47
+ private attempt;
48
+ }
@@ -0,0 +1,264 @@
1
+ import { PACING_MAX_WAIT_MS, REQUEST_TIMEOUT_MS, SERVER_NAME, SERVER_VERSION } from '../constants.js';
2
+ import { InitiativeApiError, mapHttpFailure, networkFailure, } from '../errors.js';
3
+ export const REAL_TIMING = {
4
+ now: () => Date.now(),
5
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
6
+ };
7
+ function readNumericHeader(headers, name) {
8
+ const raw = headers.get(name);
9
+ if (raw === null || !/^\d+$/.test(raw.trim())) {
10
+ return null;
11
+ }
12
+ return Number.parseInt(raw.trim(), 10);
13
+ }
14
+ function readRateLimit(headers) {
15
+ return {
16
+ limit: readNumericHeader(headers, 'X-RateLimit-Limit'),
17
+ remaining: readNumericHeader(headers, 'X-RateLimit-Remaining'),
18
+ resetAt: readNumericHeader(headers, 'X-RateLimit-Reset'),
19
+ };
20
+ }
21
+ function readRequestId(body) {
22
+ if (typeof body !== 'object' || body === null || !('meta' in body)) {
23
+ return null;
24
+ }
25
+ const meta = body.meta;
26
+ if (typeof meta !== 'object' || meta === null) {
27
+ return null;
28
+ }
29
+ const requestId = meta.request_id;
30
+ return typeof requestId === 'string' ? requestId : null;
31
+ }
32
+ const RATE_STATES = new WeakMap();
33
+ function rateStateFor(tokenSource) {
34
+ let state = RATE_STATES.get(tokenSource);
35
+ if (state === undefined) {
36
+ state = { last: null };
37
+ RATE_STATES.set(tokenSource, state);
38
+ }
39
+ return state;
40
+ }
41
+ export const OUTCOME_UNKNOWN_STEP = 'The change may have been applied. Read the record (or list the most recent records) before you try again.';
42
+ /**
43
+ * The one HTTP implementation both clients use: token retrieval, pacing, the single 429 retry,
44
+ * timeout, body reading and error mapping. With unknownOutcome set (every write) a failure after
45
+ * the request left is WRITE_OUTCOME_UNKNOWN and is never retried.
46
+ */
47
+ export class Transport {
48
+ baseUrl;
49
+ tokenSource;
50
+ fetchImpl;
51
+ timeoutMs;
52
+ timing;
53
+ rate;
54
+ constructor(baseUrl, tokenSource, fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS, timing = REAL_TIMING) {
55
+ this.baseUrl = baseUrl;
56
+ this.tokenSource = tokenSource;
57
+ this.fetchImpl = fetchImpl;
58
+ this.timeoutMs = timeoutMs;
59
+ this.timing = timing;
60
+ this.rate = rateStateFor(tokenSource);
61
+ }
62
+ async send(method, url, payload, context = {}, unknownOutcome = false) {
63
+ let token;
64
+ try {
65
+ token = await this.tokenSource.getToken();
66
+ }
67
+ catch (cause) {
68
+ throw new InitiativeApiError({
69
+ status: null,
70
+ requestSent: false,
71
+ code: 'TOKEN_UNAVAILABLE',
72
+ message: `Could not obtain an API token: ${cause instanceof Error ? cause.message : String(cause)}`,
73
+ requestId: null,
74
+ retryable: false,
75
+ nextStep: 'The connector could not get a credential to authenticate with, so no request was made ' +
76
+ 'and nothing was changed. Check that INITIATIVE_API_TOKEN is set and valid.',
77
+ });
78
+ }
79
+ // Absorb a short wait silently; a long one is not waited out, the request is sent and the
80
+ // API's own answer decides.
81
+ let sleptMs = 0;
82
+ const last = this.rate.last;
83
+ if (last !== null && last.remaining === 0 && last.resetAt !== null) {
84
+ const waitMs = last.resetAt * 1000 - this.timing.now();
85
+ if (waitMs > 0 && waitMs <= PACING_MAX_WAIT_MS) {
86
+ await this.timing.sleep(waitMs);
87
+ sleptMs += waitMs;
88
+ }
89
+ }
90
+ let retried = false;
91
+ for (;;) {
92
+ try {
93
+ return await this.attempt(method, url, payload, token, context, unknownOutcome);
94
+ }
95
+ catch (error) {
96
+ // A 429 means the API did not process the request, so one retry is safe for any method.
97
+ if (!retried &&
98
+ error instanceof InitiativeApiError &&
99
+ error.status === 429 &&
100
+ error.retryAfterSeconds !== null &&
101
+ sleptMs + error.retryAfterSeconds * 1000 <= PACING_MAX_WAIT_MS) {
102
+ retried = true;
103
+ await this.timing.sleep(error.retryAfterSeconds * 1000);
104
+ sleptMs += error.retryAfterSeconds * 1000;
105
+ continue;
106
+ }
107
+ throw error;
108
+ }
109
+ }
110
+ }
111
+ async attempt(method, url, payload, token, context, unknownOutcome) {
112
+ let response;
113
+ try {
114
+ response = await this.fetchImpl(url, {
115
+ method,
116
+ headers: {
117
+ Authorization: `Bearer ${token}`,
118
+ Accept: 'application/json',
119
+ 'User-Agent': `${SERVER_NAME}/${SERVER_VERSION}`,
120
+ // A FormData body gets no Content-Type from us: fetch adds the multipart boundary.
121
+ ...(payload?.json === undefined ? {} : { 'Content-Type': 'application/json' }),
122
+ },
123
+ ...(payload === undefined ? {} : { body: payload.json ?? payload.form }),
124
+ // fetch turns a 301 or 302 on a POST into a GET, so a request that is not a GET never
125
+ // follows a redirect. With 'manual', Node returns the real 3xx response and we check its
126
+ // status below, instead of matching an error message.
127
+ ...(method === 'GET' ? {} : { redirect: 'manual' }),
128
+ signal: AbortSignal.timeout(this.timeoutMs),
129
+ });
130
+ }
131
+ catch (cause) {
132
+ const failure = networkFailure(cause, url);
133
+ if (unknownOutcome && failure.requestSent) {
134
+ throw writeOutcomeUnknown(`The request to ${url} failed after it may have been sent: ${failure.message}`, null, null);
135
+ }
136
+ throw failure;
137
+ }
138
+ if (method !== 'GET' && response.status >= 300 && response.status < 400 && response.status !== 304) {
139
+ throw refusedRedirect(method, url, unknownOutcome, response.headers.get('Location'));
140
+ }
141
+ // Read the body as text first: an error body has to reach the mapper intact even when it is
142
+ // not JSON at all, which is exactly the case a proxy or a sign-in page produces. fetch resolves
143
+ // once the headers arrive; the body streams afterwards, so reading it can fail on its own.
144
+ let rawBody;
145
+ try {
146
+ rawBody = await response.text();
147
+ }
148
+ catch (cause) {
149
+ const detail = cause instanceof Error ? cause.message : String(cause);
150
+ if (unknownOutcome) {
151
+ throw writeOutcomeUnknown(`Initiative answered ${response.status} but the response body could not be read: ${detail}`, response.status, null);
152
+ }
153
+ throw new InitiativeApiError({
154
+ status: response.status,
155
+ code: 'NETWORK_ERROR',
156
+ message: `Initiative answered ${response.status} but the response body could not be read: ${detail}`,
157
+ requestId: null,
158
+ retryable: true,
159
+ nextStep: 'The request reached Initiative and it began replying, but the reply was cut short. ' +
160
+ 'Nothing was changed by a read. Try once more.',
161
+ });
162
+ }
163
+ const rateLimit = readRateLimit(response.headers);
164
+ if (rateLimit.limit !== null || rateLimit.remaining !== null || rateLimit.resetAt !== null) {
165
+ this.rate.last = rateLimit;
166
+ }
167
+ if (!response.ok) {
168
+ const failure = mapHttpFailure(response.status, rawBody, response.headers, context);
169
+ throw unknownOutcome ? adjustWriteFailure(failure) : failure;
170
+ }
171
+ // A 204 (a delete) has no body: that is a success, not a parse failure. A write may also answer
172
+ // an empty 2xx; the tool then says the change was accepted without a record. A read (a GET or
173
+ // a search) with an empty 200 is not a CRM answer, and falls through to INVALID_RESPONSE.
174
+ if (rawBody.trim() === '' && (response.status === 204 || unknownOutcome)) {
175
+ return { body: null, status: response.status, requestId: null, rateLimit };
176
+ }
177
+ let body;
178
+ try {
179
+ body = JSON.parse(rawBody);
180
+ }
181
+ catch {
182
+ if (unknownOutcome) {
183
+ throw writeOutcomeUnknown(`Initiative answered ${response.status} but the body was not JSON.`, response.status, null);
184
+ }
185
+ throw new InitiativeApiError({
186
+ status: response.status,
187
+ code: 'INVALID_RESPONSE',
188
+ message: `Initiative answered ${response.status} but the body was not JSON.`,
189
+ requestId: null,
190
+ retryable: false,
191
+ nextStep: 'The API always answers with JSON, so something else answered instead — check the ' +
192
+ 'server address setting points at an Initiative CRM API and not at a proxy or a ' +
193
+ 'sign-in page.',
194
+ });
195
+ }
196
+ return { body, status: response.status, requestId: readRequestId(body), rateLimit };
197
+ }
198
+ }
199
+ /** Only the host of a redirect target is shown: the path and query may carry values we should not echo. */
200
+ function locationHost(location, base) {
201
+ if (location === null)
202
+ return null;
203
+ try {
204
+ return new URL(location, base).host;
205
+ }
206
+ catch {
207
+ return null;
208
+ }
209
+ }
210
+ function refusedRedirect(method, url, unknownOutcome, location) {
211
+ const host = locationHost(location, url);
212
+ return new InitiativeApiError({
213
+ status: null,
214
+ requestSent: true,
215
+ code: 'UNEXPECTED_REDIRECT',
216
+ message: `The server at ${url} answered the ${method} with a redirect. The connector does not follow a redirect ` +
217
+ 'for this request, because fetch would turn it into a GET.',
218
+ requestId: null,
219
+ retryable: false,
220
+ nextStep: (host === null ? '' : `The server answered with a redirect to ${host}. `) +
221
+ 'Check that INITIATIVE_BASE_URL is the exact API address: https, the right host, and ending in /api/v1. ' +
222
+ (unknownOutcome
223
+ ? 'A redirect usually means the change did not reach the API, but read the record before you try again.'
224
+ : 'Nothing was changed by this request.'),
225
+ });
226
+ }
227
+ function writeOutcomeUnknown(message, status, requestId) {
228
+ return new InitiativeApiError({
229
+ status,
230
+ requestSent: true,
231
+ code: 'WRITE_OUTCOME_UNKNOWN',
232
+ message,
233
+ requestId,
234
+ retryable: false,
235
+ nextStep: OUTCOME_UNKNOWN_STEP,
236
+ });
237
+ }
238
+ /**
239
+ * A 5xx on a write does not mean Initiative did nothing. 502 and 504 come from a gateway that
240
+ * gave up waiting; a 5xx that is not the API's own error envelope is a proxy page. Both are
241
+ * unknown outcomes. A 500 with the envelope keeps its code and request id, but its advice must
242
+ * not say "retry". 503 (the Public API is not enabled) is rejected before any processing and
243
+ * stays as mapped.
244
+ */
245
+ function adjustWriteFailure(failure) {
246
+ const status = failure.status;
247
+ if (status === null || status < 500 || status === 503) {
248
+ return failure;
249
+ }
250
+ if (status === 502 || status === 504 || failure.code === 'INVALID_RESPONSE') {
251
+ return writeOutcomeUnknown(`Initiative answered HTTP ${status}, which does not say whether the change was applied.`, status, failure.requestId);
252
+ }
253
+ return new InitiativeApiError({
254
+ status,
255
+ requestSent: true,
256
+ code: failure.code,
257
+ message: failure.message,
258
+ requestId: failure.requestId,
259
+ retryable: false,
260
+ nextStep: OUTCOME_UNKNOWN_STEP,
261
+ details: failure.details,
262
+ });
263
+ }
264
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1,26 @@
1
+ export interface UploadSource {
2
+ name: string;
3
+ type: string;
4
+ bytes: Uint8Array;
5
+ }
6
+ export declare function mimeTypeFor(filename: string): string;
7
+ /** Exactly one source: file_path, or content_base64 with filename. Anything else is refused. */
8
+ export declare function resolveUploadSource(args: {
9
+ file_path?: string | undefined;
10
+ content_base64?: string | undefined;
11
+ filename?: string | undefined;
12
+ }, uploadDir: string | null, uploadDirAsGiven?: string | null): Promise<UploadSource>;
13
+ export declare function procFdExists(): Promise<boolean>;
14
+ /** Test seam: runs after the containment checks and the lstat, right before the open. */
15
+ export interface ReadHooks {
16
+ beforeOpen?: (realPath: string) => Promise<void>;
17
+ }
18
+ /**
19
+ * Reads a file only from inside uploadDir.
20
+ *
21
+ * Every failure before containment is confirmed answers the same PATH_NOT_ALLOWED text, so the
22
+ * answer cannot tell the assistant whether a file outside the folder exists. A hard link placed
23
+ * inside the folder counts as a file in the folder: only someone who can write to that folder can
24
+ * create one.
25
+ */
26
+ export declare function readLocalFile(path: string, uploadDir: string | null, hooks?: ReadHooks, uploadDirAsGiven?: string | null): Promise<UploadSource>;
@@ -0,0 +1,206 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { MAX_UPLOAD_BYTES } from '../constants.js';
4
+ import { InitiativeApiError } from '../errors.js';
5
+ const MIME_BY_EXTENSION = {
6
+ pdf: 'application/pdf',
7
+ txt: 'text/plain',
8
+ csv: 'text/csv',
9
+ html: 'text/html',
10
+ json: 'application/json',
11
+ xml: 'application/xml',
12
+ zip: 'application/zip',
13
+ png: 'image/png',
14
+ jpg: 'image/jpeg',
15
+ jpeg: 'image/jpeg',
16
+ gif: 'image/gif',
17
+ webp: 'image/webp',
18
+ svg: 'image/svg+xml',
19
+ doc: 'application/msword',
20
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
21
+ xls: 'application/vnd.ms-excel',
22
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
23
+ ppt: 'application/vnd.ms-powerpoint',
24
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
25
+ odt: 'application/vnd.oasis.opendocument.text',
26
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
27
+ md: 'text/markdown',
28
+ };
29
+ export function mimeTypeFor(filename) {
30
+ const dot = filename.lastIndexOf('.');
31
+ if (dot < 0)
32
+ return 'application/octet-stream';
33
+ return MIME_BY_EXTENSION[filename.slice(dot + 1).toLowerCase()] ?? 'application/octet-stream';
34
+ }
35
+ function refuse(code, message, advice) {
36
+ return new InitiativeApiError({
37
+ status: null,
38
+ requestSent: false,
39
+ code,
40
+ message,
41
+ requestId: null,
42
+ retryable: false,
43
+ nextStep: `No request was made. ${advice}`,
44
+ });
45
+ }
46
+ const CAP_TEXT = `${MAX_UPLOAD_BYTES / (1024 * 1024)} MB`;
47
+ function tooLarge(what) {
48
+ return refuse('FILE_TOO_LARGE', `${what} is larger than the ${CAP_TEXT} limit.`, `Send a smaller file, below ${CAP_TEXT}.`);
49
+ }
50
+ const SOURCE_ADVICE = 'Give either file_path (an absolute path on this computer), or content_base64 together with filename, and not both.';
51
+ /** Exactly one source: file_path, or content_base64 with filename. Anything else is refused. */
52
+ export async function resolveUploadSource(args, uploadDir, uploadDirAsGiven = null) {
53
+ const hasPath = args.file_path !== undefined;
54
+ const hasContent = args.content_base64 !== undefined;
55
+ if (hasPath === hasContent) {
56
+ throw refuse('INVALID_ARGUMENT', hasPath ? 'Both file_path and content_base64 were given.' : 'Neither file_path nor content_base64 was given.', SOURCE_ADVICE);
57
+ }
58
+ if (hasPath) {
59
+ if (args.filename !== undefined) {
60
+ throw refuse('INVALID_ARGUMENT', 'filename goes with content_base64, not with file_path.', 'Remove filename; the file keeps its own name.');
61
+ }
62
+ return readLocalFile(args.file_path, uploadDir, {}, uploadDirAsGiven);
63
+ }
64
+ if (args.filename === undefined) {
65
+ throw refuse('INVALID_ARGUMENT', 'content_base64 needs a filename.', 'Add filename, for example "report.pdf".');
66
+ }
67
+ return decodeInline(args.content_base64, args.filename);
68
+ }
69
+ function outside(name) {
70
+ return refuse('PATH_NOT_ALLOWED', `"${name}" is not inside the folder files may be uploaded from, or it is a hidden file.`, 'Put the file in the upload folder (INITIATIVE_UPLOAD_DIR) under a name that does not start with a dot, or send it as content_base64 with a filename.');
71
+ }
72
+ /** True when `target` lies strictly inside `dir` and no segment between them is hidden or a '..'. */
73
+ function insideAndVisible(dir, target) {
74
+ const rel = relative(dir, target);
75
+ if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
76
+ return false;
77
+ return !rel.split(sep).some((part) => part.startsWith('.'));
78
+ }
79
+ export async function procFdExists() {
80
+ try {
81
+ await fs.access('/proc/self/fd');
82
+ return true;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ /**
89
+ * Reads a file only from inside uploadDir.
90
+ *
91
+ * Every failure before containment is confirmed answers the same PATH_NOT_ALLOWED text, so the
92
+ * answer cannot tell the assistant whether a file outside the folder exists. A hard link placed
93
+ * inside the folder counts as a file in the folder: only someone who can write to that folder can
94
+ * create one.
95
+ */
96
+ export async function readLocalFile(path, uploadDir, hooks = {}, uploadDirAsGiven = null) {
97
+ const name = basename(path);
98
+ if (uploadDir === null) {
99
+ throw refuse('UPLOAD_FROM_PATH_OFF', 'Uploading from a file path is switched off.', 'Send the file as content_base64 with a filename, or ask the person who installed the connector to set INITIATIVE_UPLOAD_DIR to the folder files may be uploaded from.');
100
+ }
101
+ if (!isAbsolute(path)) {
102
+ throw refuse('INVALID_ARGUMENT', `file_path "${name}" is not an absolute path.`, 'Give the full path, starting with /.');
103
+ }
104
+ // Lexical check first, before any filesystem call. The folder may be named by its real path or
105
+ // by the name it was configured under (macOS: /tmp/x is /private/tmp/x). The real-path check
106
+ // below is always against the real folder.
107
+ const lexical = resolve(path);
108
+ const underFolder = insideAndVisible(uploadDir, lexical) || (uploadDirAsGiven !== null && insideAndVisible(uploadDirAsGiven, lexical));
109
+ if (path.endsWith(sep) || path.split(sep).includes('..') || !underFolder) {
110
+ throw outside(name);
111
+ }
112
+ let real;
113
+ try {
114
+ real = await fs.realpath(path);
115
+ }
116
+ catch {
117
+ // Not yet known to be inside the folder: do not say whether the file exists.
118
+ throw outside(name);
119
+ }
120
+ if (!insideAndVisible(uploadDir, real))
121
+ throw outside(name);
122
+ let handle;
123
+ try {
124
+ let before;
125
+ try {
126
+ before = await fs.lstat(real);
127
+ }
128
+ catch (error) {
129
+ const missing = error.code === 'ENOENT';
130
+ throw refuse(missing ? 'FILE_NOT_FOUND' : 'FILE_UNREADABLE', missing ? `No file named "${name}" was found at the path given.` : `"${name}" could not be read.`, missing ? 'Check the path, then call again.' : 'Check that this process may read the file, then call again.');
131
+ }
132
+ await hooks.beforeOpen?.(real);
133
+ try {
134
+ handle = await fs.open(real, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
135
+ }
136
+ catch (error) {
137
+ const code = error.code;
138
+ if (code === 'ELOOP')
139
+ throw outside(name);
140
+ throw refuse(code === 'ENOENT' ? 'FILE_NOT_FOUND' : 'FILE_UNREADABLE', code === 'ENOENT' ? `No file named "${name}" was found at the path given.` : `"${name}" could not be read.`, code === 'ENOENT' ? 'Check the path, then call again.' : 'Check that this process may read the file, then call again.');
141
+ }
142
+ const info = await handle.stat();
143
+ if (info.dev !== before.dev || info.ino !== before.ino)
144
+ throw outside(name);
145
+ // A parent directory swapped for a symlink after the lstat would still give the same dev and
146
+ // ino only for a hard link, but the opened file would be outside. On Linux, ask the kernel
147
+ // where the open handle really is. Without /proc (macOS, Windows) only the dev/ino check
148
+ // remains: a local process that can rewrite folders inside the upload folder at the right
149
+ // moment could race an upload. This connector gives the model no way to create links.
150
+ if (await procFdExists()) {
151
+ let opened;
152
+ try {
153
+ opened = await fs.realpath(`/proc/self/fd/${handle.fd}`);
154
+ }
155
+ catch {
156
+ throw outside(name);
157
+ }
158
+ if (!insideAndVisible(uploadDir, opened))
159
+ throw outside(name);
160
+ }
161
+ if (!info.isFile()) {
162
+ throw refuse('INVALID_ARGUMENT', `"${name}" is not a regular file.`, 'Give the path of a file, not a directory or a device.');
163
+ }
164
+ if (info.size > MAX_UPLOAD_BYTES)
165
+ throw tooLarge(`"${name}"`);
166
+ const buffer = Buffer.alloc(MAX_UPLOAD_BYTES + 1);
167
+ let total = 0;
168
+ while (total < buffer.length) {
169
+ const { bytesRead } = await handle.read(buffer, total, buffer.length - total, total);
170
+ if (bytesRead === 0)
171
+ break;
172
+ total += bytesRead;
173
+ }
174
+ if (total > MAX_UPLOAD_BYTES)
175
+ throw tooLarge(`"${name}"`);
176
+ return { name, type: mimeTypeFor(name), bytes: buffer.subarray(0, total) };
177
+ }
178
+ catch (error) {
179
+ if (error instanceof InitiativeApiError)
180
+ throw error;
181
+ throw refuse('FILE_UNREADABLE', `"${name}" could not be read.`, 'Check that this process may read the file, then call again.');
182
+ }
183
+ finally {
184
+ await handle?.close();
185
+ }
186
+ }
187
+ function decodeInline(content, filename) {
188
+ if (filename === '' || /[\\/\u0000-\u001f]/.test(filename) || filename === '.' || filename === '..') {
189
+ throw refuse('INVALID_ARGUMENT', `filename ${JSON.stringify(filename)} is not valid.`, 'Give a plain file name such as report.pdf, with no folder.');
190
+ }
191
+ if (content.length > Math.ceil((MAX_UPLOAD_BYTES * 4) / 3) * 2 + 1024)
192
+ throw tooLarge('The content');
193
+ const compact = content.replace(/\s+/g, '');
194
+ // Check the length before decoding, so a huge string is never turned into a huge buffer.
195
+ if (compact.length > Math.ceil((MAX_UPLOAD_BYTES * 4) / 3) + 4)
196
+ throw tooLarge('The content');
197
+ const bytes = Buffer.from(compact, 'base64');
198
+ const strip = (s) => s.replace(/=+$/, '');
199
+ if (compact === '' || !/^[A-Za-z0-9+/]*={0,2}$/.test(compact) || strip(bytes.toString('base64')) !== strip(compact)) {
200
+ throw refuse('INVALID_ARGUMENT', 'content_base64 is not valid base64.', 'Send standard base64 text of the file, or use file_path.');
201
+ }
202
+ if (bytes.length > MAX_UPLOAD_BYTES)
203
+ throw tooLarge('The content');
204
+ return { name: filename, type: mimeTypeFor(filename), bytes };
205
+ }
206
+ //# sourceMappingURL=upload-source.js.map
@@ -0,0 +1,34 @@
1
+ import type { ErrorContext } from '../errors.js';
2
+ import type { TokenSource } from '../token-source.js';
3
+ import { type ApiResponse, type Timing } from './transport.js';
4
+ export interface WriteOptions {
5
+ /** Extra facts the error mapper needs to give good advice, e.g. the module that was asked for. */
6
+ readonly context?: ErrorContext;
7
+ }
8
+ export interface UploadFile {
9
+ readonly name: string;
10
+ readonly type: string;
11
+ readonly bytes: Uint8Array;
12
+ }
13
+ /**
14
+ * The write half of the API client. It shares one transport with the read client, and every
15
+ * request it makes follows the outcome rule: a failure after the request may have left is
16
+ * WRITE_OUTCOME_UNKNOWN and is never retried. Only a 429 is retried, as the CRM answers it
17
+ * before any controller runs.
18
+ */
19
+ export declare class InitiativeWriteClient {
20
+ private readonly transport;
21
+ constructor(baseUrl: string, tokenSource: TokenSource, fetchImpl?: typeof fetch, timeoutMs?: number, timing?: Timing);
22
+ create<T>(module: string, attributes: unknown, opts?: WriteOptions): Promise<ApiResponse<T>>;
23
+ update<T>(module: string, id: string, attributes: unknown, opts?: WriteOptions): Promise<ApiResponse<T>>;
24
+ remove(module: string, id: string, opts?: WriteOptions): Promise<ApiResponse<null>>;
25
+ link<T>(module: string, id: string, rel: string, relId: string, attributes?: unknown, opts?: WriteOptions): Promise<ApiResponse<T>>;
26
+ updateLink<T>(module: string, id: string, rel: string, relId: string, attributes: unknown, opts?: WriteOptions): Promise<ApiResponse<T>>;
27
+ unlink(module: string, id: string, rel: string, relId: string, opts?: WriteOptions): Promise<ApiResponse<null>>;
28
+ createComment<T>(attributes: unknown, opts?: WriteOptions): Promise<ApiResponse<T>>;
29
+ uploadDocument<T>(attributes: unknown, file: UploadFile, opts?: WriteOptions): Promise<ApiResponse<T>>;
30
+ convertLead<T>(leadId: string, attributes: unknown, opts?: WriteOptions): Promise<ApiResponse<T>>;
31
+ private relatedPath;
32
+ private url;
33
+ private json;
34
+ }
@@ -0,0 +1,57 @@
1
+ import { REQUEST_TIMEOUT_MS } from '../constants.js';
2
+ import { idSegment, moduleSegment } from './path.js';
3
+ import { REAL_TIMING, Transport } from './transport.js';
4
+ /**
5
+ * The write half of the API client. It shares one transport with the read client, and every
6
+ * request it makes follows the outcome rule: a failure after the request may have left is
7
+ * WRITE_OUTCOME_UNKNOWN and is never retried. Only a 429 is retried, as the CRM answers it
8
+ * before any controller runs.
9
+ */
10
+ export class InitiativeWriteClient {
11
+ transport;
12
+ constructor(baseUrl, tokenSource, fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS, timing = REAL_TIMING) {
13
+ this.transport = new Transport(baseUrl, tokenSource, fetchImpl, timeoutMs, timing);
14
+ }
15
+ async create(module, attributes, opts = {}) {
16
+ return this.json('POST', `/${moduleSegment(module)}`, { data: { attributes } }, opts);
17
+ }
18
+ async update(module, id, attributes, opts = {}) {
19
+ return this.json('PATCH', `/${moduleSegment(module)}/${idSegment(id)}`, { data: { attributes } }, opts);
20
+ }
21
+ async remove(module, id, opts = {}) {
22
+ return this.json('DELETE', `/${moduleSegment(module)}/${idSegment(id)}`, undefined, opts);
23
+ }
24
+ async link(module, id, rel, relId, attributes, opts = {}) {
25
+ idSegment(relId); // rejects a bad related id even though a POST carries it in the body
26
+ return this.json('POST', this.relatedPath(module, id, rel), { data: { id: relId, ...(attributes === undefined ? {} : { attributes }) } }, opts);
27
+ }
28
+ async updateLink(module, id, rel, relId, attributes, opts = {}) {
29
+ return this.json('PATCH', `${this.relatedPath(module, id, rel)}/${idSegment(relId)}`, { data: { attributes } }, opts);
30
+ }
31
+ async unlink(module, id, rel, relId, opts = {}) {
32
+ return this.json('DELETE', `${this.relatedPath(module, id, rel)}/${idSegment(relId)}`, undefined, opts);
33
+ }
34
+ async createComment(attributes, opts = {}) {
35
+ return this.json('POST', '/comments', { data: { attributes } }, opts);
36
+ }
37
+ async uploadDocument(attributes, file, opts = {}) {
38
+ const form = new FormData();
39
+ form.append('data', JSON.stringify({ data: { attributes } }));
40
+ // Copy into a fresh buffer: a Uint8Array view may sit on a shared or larger ArrayBuffer.
41
+ form.append('file', new Blob([new Uint8Array(file.bytes)], { type: file.type }), file.name);
42
+ return await this.transport.send('POST', this.url('/documents'), { form }, opts.context, true);
43
+ }
44
+ async convertLead(leadId, attributes, opts = {}) {
45
+ return this.json('POST', `/leads/${idSegment(leadId)}/convert`, { data: { attributes } }, opts);
46
+ }
47
+ relatedPath(module, id, rel) {
48
+ return `/${moduleSegment(module)}/${idSegment(id)}/related/${moduleSegment(rel, 'related_module')}`;
49
+ }
50
+ url(path) {
51
+ return new URL(`${this.transport.baseUrl}${path}`).toString();
52
+ }
53
+ json(method, path, body, opts) {
54
+ return this.transport.send(method, this.url(path), body === undefined ? undefined : { json: JSON.stringify(body) }, opts.context, true);
55
+ }
56
+ }
57
+ //# sourceMappingURL=write-client.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Where the bearer token for the call being made right now comes from.
3
+ *
4
+ * This is the seam between the two ways a credential reaches the connector. On the local stdio
5
+ * route (phase 1) one token is read from the environment at startup and never changes. On the
6
+ * hosted route (phase 2) a different token arrives with every request, in an Authorization header
7
+ * issued by the sign-in flow. Everything above this interface — the HTTP client, the tools, the
8
+ * error mapping — is identical on both routes and must never be handed a bare token string.
9
+ *
10
+ * getToken() is asynchronous for the same reason: a per-request source may have to look something
11
+ * up, and widening a synchronous interface later would touch every call site.
12
+ */
13
+ export interface TokenSource {
14
+ getToken(): Promise<string>;
15
+ }
16
+ /** One token for the life of the process. The stdio route's source. */
17
+ export declare class StaticTokenSource implements TokenSource {
18
+ private readonly token;
19
+ constructor(token: string);
20
+ getToken(): Promise<string>;
21
+ }
@@ -0,0 +1,11 @@
1
+ /** One token for the life of the process. The stdio route's source. */
2
+ export class StaticTokenSource {
3
+ token;
4
+ constructor(token) {
5
+ this.token = token;
6
+ }
7
+ async getToken() {
8
+ return this.token;
9
+ }
10
+ }
11
+ //# sourceMappingURL=token-source.js.map