standardnotes-mcp 0.0.0-stage → 3.0.1

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 (49) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/LICENSE +22 -0
  3. package/README.md +336 -3
  4. package/SECURITY.md +56 -0
  5. package/dist/cli/install.js +180 -0
  6. package/dist/cli/isMain.js +21 -0
  7. package/dist/cli/login.js +117 -0
  8. package/dist/cli/logout.js +22 -0
  9. package/dist/cli/setup.js +192 -0
  10. package/dist/config.js +60 -0
  11. package/dist/index.js +10 -0
  12. package/dist/security/errors.js +20 -0
  13. package/dist/security/logger.js +17 -0
  14. package/dist/security/redact.js +31 -0
  15. package/dist/security/regex.js +27 -0
  16. package/dist/server.js +329 -0
  17. package/dist/sn/cache.js +53 -0
  18. package/dist/sn/client.js +1999 -0
  19. package/dist/sn/crypto.js +63 -0
  20. package/dist/sn/dates.js +157 -0
  21. package/dist/sn/entitlement.js +75 -0
  22. package/dist/sn/frontmatter.js +171 -0
  23. package/dist/sn/governance.js +40 -0
  24. package/dist/sn/http.js +289 -0
  25. package/dist/sn/links.js +78 -0
  26. package/dist/sn/markdownSections.js +141 -0
  27. package/dist/sn/predicates.js +135 -0
  28. package/dist/sn/protocol004.js +401 -0
  29. package/dist/sn/scope.js +68 -0
  30. package/dist/sn/search.js +260 -0
  31. package/dist/sn/session.js +55 -0
  32. package/dist/sn/tagHierarchy.js +105 -0
  33. package/dist/sn/tasks.js +32 -0
  34. package/dist/sn/templates.js +23 -0
  35. package/dist/sn/types.js +12 -0
  36. package/dist/tools/daily.js +126 -0
  37. package/dist/tools/export.js +96 -0
  38. package/dist/tools/history.js +41 -0
  39. package/dist/tools/links.js +51 -0
  40. package/dist/tools/notes.js +404 -0
  41. package/dist/tools/smartviews.js +52 -0
  42. package/dist/tools/tags.js +82 -0
  43. package/dist/tools/tasks.js +43 -0
  44. package/dist/tools/templates.js +145 -0
  45. package/dist/version.js +12 -0
  46. package/docs/protocol-004.md +72 -0
  47. package/docs/self-hosted.md +120 -0
  48. package/docs/troubleshooting.md +89 -0
  49. package/package.json +86 -6
@@ -0,0 +1,289 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+ import { Agent, fetch } from "undici";
4
+ import { logger } from "../security/logger.js";
5
+ import { redactString } from "../security/redact.js";
6
+ const require = createRequire(import.meta.url);
7
+ const { version: PKG_VERSION } = require("../../package.json");
8
+ // Do NOT spoof a browser User-Agent. Between v0.3.2 (2026-02) and v0.5.0
9
+ // (2026-07) we sent a Chrome UA + Origin/Referer to slip past Cloudflare's
10
+ // JS challenge, and it worked. It stopped working around 2026-08: CF now
11
+ // scores "claims to be Chrome but has a non-browser TLS fingerprint" as
12
+ // impersonation and challenges HARDER — HTTP 403, `cf-mitigated: challenge`.
13
+ // An honest UA that identifies the project passes cleanly on the same edge
14
+ // (see issue #6, reproduced from a residential IP on 2026-08-04).
15
+ //
16
+ // If login ever returns "Non-JSON response ... Just a moment ...", the fix
17
+ // is NOT to reintroduce browser spoofing — that direction is closed. Check
18
+ // first that api.standardnotes.com hasn't added a new gate (e.g. requiring
19
+ // a header we're not sending, or a stricter version floor in X-SNJS-Version
20
+ // / X-Application-Version) by comparing against upstream github.com/
21
+ // jonhadfield/gosn-v2 (common/client_headers.go).
22
+ const HONEST_UA = `standardnotes-mcp/${PKG_VERSION}`;
23
+ const X_CLIENT = HONEST_UA;
24
+ // Standard Notes' api-gateway (since ~2026-05) rejects any request missing
25
+ // these two version headers with HTTP 400 "Your client version is no longer
26
+ // supported. Please update Standard Notes to the latest version." The gateway
27
+ // gates on these headers — NOT on the body `api` field. Bump them when the
28
+ // gateway raises its floor again (symptom: login suddenly 400s with that exact
29
+ // message). Current accepted values tracked upstream by github.com/jonhadfield/
30
+ // gosn-v2 (common/client_headers.go), which hit the same wall.
31
+ const SNJS_VERSION = "2.211.7";
32
+ const APP_VERSION = "Desktop-3.201.27";
33
+ let dispatcher;
34
+ let dispatcherInitialized = false;
35
+ // Cloudflare in front of api.standardnotes.com flags HTTP/1.1 clients as bots
36
+ // regardless of headers — modern browsers/curl negotiate h2. Node's fetch
37
+ // defaults to h1.1, which fails the JS challenge. allowH2 makes undici
38
+ // negotiate ALPN h2 with the server, falling back to h1.1 if unsupported
39
+ // (so self-hosted servers without h2 still work).
40
+ function getDispatcher() {
41
+ if (dispatcherInitialized && dispatcher)
42
+ return dispatcher;
43
+ dispatcherInitialized = true;
44
+ const expected = process.env.SN_CERT_FINGERPRINT;
45
+ const agentOpts = { allowH2: true };
46
+ if (expected) {
47
+ const expectedNorm = expected.replace(/:/g, "").toLowerCase();
48
+ if (!/^[0-9a-f]{64}$/.test(expectedNorm)) {
49
+ throw new Error("SN_CERT_FINGERPRINT must be a SHA-256 fingerprint (64 hex chars, colons optional)");
50
+ }
51
+ agentOpts.connect = {
52
+ checkServerIdentity: (_host, cert) => {
53
+ const got = (cert.fingerprint256 ?? "")
54
+ .replace(/:/g, "")
55
+ .toLowerCase();
56
+ if (got !== expectedNorm) {
57
+ return new Error(`TLS cert pinning mismatch: server presented fingerprint ` +
58
+ `${got || "<missing>"} but SN_CERT_FINGERPRINT expects ${expectedNorm}`);
59
+ }
60
+ return undefined;
61
+ },
62
+ };
63
+ logger.info("TLS cert pinning enabled via SN_CERT_FINGERPRINT");
64
+ }
65
+ dispatcher = new Agent(agentOpts);
66
+ return dispatcher;
67
+ }
68
+ export function parseResponseMeta(raw) {
69
+ if (typeof raw !== "object" || raw === null)
70
+ return undefined;
71
+ const r = raw;
72
+ const out = {};
73
+ const auth = r.auth;
74
+ if (auth && typeof auth === "object" && Array.isArray(auth.roles)) {
75
+ out.auth = {
76
+ roles: auth.roles
77
+ .filter((x) => typeof x === "object" && x !== null && typeof x.name === "string")
78
+ .map((x) => ({ name: x.name })),
79
+ };
80
+ }
81
+ const server = r.server;
82
+ if (server && typeof server === "object" && typeof server.filesServerUrl === "string") {
83
+ out.server = { filesServerUrl: server.filesServerUrl };
84
+ }
85
+ return out;
86
+ }
87
+ export class SnApiError extends Error {
88
+ tag;
89
+ status;
90
+ payload;
91
+ constructor(message, tag, status, payload) {
92
+ super(message);
93
+ this.tag = tag;
94
+ this.status = status;
95
+ this.payload = payload;
96
+ }
97
+ }
98
+ async function snFetch(url, init) {
99
+ return (await snFetchWithMeta(url, init)).data;
100
+ }
101
+ async function snFetchWithMeta(url, init) {
102
+ const headers = new Headers(init.headers);
103
+ // Honest UA (see HONEST_UA declaration above). Do NOT reintroduce
104
+ // browser-UA spoofing here — Cloudflare now challenges impersonators
105
+ // harder than honest non-browser clients.
106
+ if (!headers.has("User-Agent"))
107
+ headers.set("User-Agent", HONEST_UA);
108
+ if (!headers.has("X-Client"))
109
+ headers.set("X-Client", X_CLIENT);
110
+ // Required by the SN api-gateway (see SNJS_VERSION / APP_VERSION above).
111
+ if (!headers.has("X-SNJS-Version")) {
112
+ headers.set("X-SNJS-Version", SNJS_VERSION);
113
+ }
114
+ if (!headers.has("X-Application-Version")) {
115
+ headers.set("X-Application-Version", APP_VERSION);
116
+ }
117
+ if (!headers.has("Accept")) {
118
+ headers.set("Accept", "application/json, text/plain, */*");
119
+ }
120
+ if (!headers.has("Accept-Language")) {
121
+ headers.set("Accept-Language", "en-US,en;q=0.9");
122
+ }
123
+ const finalInit = {
124
+ ...init,
125
+ headers,
126
+ dispatcher: getDispatcher(),
127
+ };
128
+ // Two-step cast via unknown: @types/node ≥26 makes DOM Headers extend
129
+ // SpecIterableIterator (with .map/.filter/.take/.drop), while undici's own
130
+ // Headers type is still the older shape. TS then rejects a direct
131
+ // `finalInit as Parameters<typeof fetch>[1]` cast even though the runtime
132
+ // shapes are compatible. `as unknown as` is the standard escape hatch
133
+ // sanctioned by the TS diagnostic ("If this was intentional, convert the
134
+ // expression to 'unknown' first.").
135
+ const res = await fetch(url, finalInit);
136
+ if (res.status === 429) {
137
+ const retryAfter = res.headers.get("retry-after");
138
+ const hint = retryAfter ? ` Retry after ${retryAfter}s.` : "";
139
+ throw new SnApiError(`Rate limited by Standard Notes server (HTTP 429).${hint} ` +
140
+ `Wait before retrying — do not loop.`, "rate-limited", 429, retryAfter ? { retryAfter } : undefined);
141
+ }
142
+ const text = await res.text();
143
+ let body;
144
+ try {
145
+ body = text ? JSON.parse(text) : {};
146
+ }
147
+ catch {
148
+ const snippet = redactString(text.slice(0, 200))
149
+ .replace(/\s+/g, " ")
150
+ .trim();
151
+ throw new Error(`Non-JSON response from ${url} (status ${res.status})` +
152
+ (snippet ? `: ${snippet}` : ""));
153
+ }
154
+ const data = body.data;
155
+ // SN puts the error at the top level on auth endpoints, under `data` on sync.
156
+ const err = body.error ?? data?.error;
157
+ if (!res.ok || err) {
158
+ let message = err?.message ?? `HTTP ${res.status}`;
159
+ // No structured message (unknown shape, or an error object without one):
160
+ // attach a redacted snippet of the raw body so the failure is diagnosable
161
+ // instead of an opaque "HTTP 400".
162
+ if (!err?.message) {
163
+ const snippet = redactString(text.slice(0, 200))
164
+ .replace(/\s+/g, " ")
165
+ .trim();
166
+ if (snippet && snippet !== "{}")
167
+ message += `: ${snippet}`;
168
+ }
169
+ throw new SnApiError(message, err?.tag, res.status, err?.payload);
170
+ }
171
+ return { data: (data ?? {}), meta: parseResponseMeta(body.meta) };
172
+ }
173
+ // ----- PKCE helpers (Standard Notes custom flavor — NOT RFC 7636) -----
174
+ //
175
+ // verifier = hex(32 random bytes) — 64 lowercase hex chars
176
+ // challenge = base64url_nopad( utf8( hex(sha256( utf8(verifier) )) ) )
177
+ // The server stores the challenge during /v2/login-params, then recomputes
178
+ // from the submitted verifier on /v2/login.
179
+ export function generateCodeVerifier() {
180
+ return randomBytes(32).toString("hex");
181
+ }
182
+ export function computeCodeChallenge(verifier) {
183
+ const shaHex = createHash("sha256").update(verifier, "utf8").digest("hex");
184
+ return Buffer.from(shaHex, "utf8").toString("base64url");
185
+ }
186
+ // ----- Auth endpoints -----
187
+ export async function getLoginParams(cfg, email, codeChallenge,
188
+ // Server-side, MFA is verified inside the /v2/login-params handler
189
+ // (BaseAuthController.pkceParams calls verifyMFA before returning key
190
+ // params), NOT inside /v2/login. So on an mfa-required failure the client
191
+ // must re-call THIS endpoint with `{ [mfa_key]: code }` in the body — that
192
+ // is what `extraBody` carries. Empty/omitted = first attempt.
193
+ extraBody) {
194
+ const body = await snFetch(`${cfg.serverUrl}/v2/login-params`, {
195
+ method: "POST",
196
+ headers: { "Content-Type": "application/json" },
197
+ body: JSON.stringify({
198
+ email,
199
+ api: "20200115",
200
+ code_challenge: codeChallenge,
201
+ ...extraBody,
202
+ }),
203
+ });
204
+ if (body.version !== "004" || !body.pw_nonce || !body.identifier) {
205
+ throw new Error("Account is not on protocol 004 or server returned unexpected shape. " +
206
+ "Upgrade via the Standard Notes app and retry.");
207
+ }
208
+ return body;
209
+ }
210
+ export async function login(cfg, email, serverPassword, codeVerifier) {
211
+ // The server does NOT re-verify MFA at /v2/login (pkceSignIn skips
212
+ // verifyMFA — see BaseAuthController). MFA is gated upstream at
213
+ // /v2/login-params; once we've cleared it there, this call carries no
214
+ // MFA payload.
215
+ const payload = {
216
+ email,
217
+ password: serverPassword,
218
+ code_verifier: codeVerifier,
219
+ api: "20200115",
220
+ ephemeral: false,
221
+ };
222
+ return snFetch(`${cfg.serverUrl}/v2/login`, {
223
+ method: "POST",
224
+ headers: { "Content-Type": "application/json" },
225
+ body: JSON.stringify(payload),
226
+ });
227
+ }
228
+ export async function sync(cfg, params) {
229
+ const payload = {
230
+ api: "20200115",
231
+ limit: params.limit ?? 150,
232
+ items: params.items ?? [],
233
+ };
234
+ if (params.syncToken)
235
+ payload["sync_token"] = params.syncToken;
236
+ if (params.cursorToken)
237
+ payload["cursor_token"] = params.cursorToken;
238
+ const { data: res, meta } = await snFetchWithMeta(`${cfg.serverUrl}/v1/items`, {
239
+ method: "POST",
240
+ headers: {
241
+ "Content-Type": "application/json",
242
+ Authorization: `Bearer ${cfg.authToken}`,
243
+ },
244
+ body: JSON.stringify(payload),
245
+ });
246
+ logger.debug("sync page", {
247
+ retrieved: res.retrieved_items?.length ?? 0,
248
+ saved: res.saved_items?.length ?? 0,
249
+ hasCursor: Boolean(res.cursor_token),
250
+ });
251
+ return {
252
+ retrieved_items: res.retrieved_items ?? [],
253
+ saved_items: res.saved_items ?? [],
254
+ conflicts: res.conflicts ?? [],
255
+ sync_token: res.sync_token,
256
+ cursor_token: res.cursor_token,
257
+ integrity_hash: res.integrity_hash,
258
+ meta,
259
+ };
260
+ }
261
+ export async function refreshSession(cfg, accessToken, refreshToken) {
262
+ return snFetch(`${cfg.serverUrl}/v1/sessions/refresh`, {
263
+ method: "POST",
264
+ headers: {
265
+ "Content-Type": "application/json",
266
+ Authorization: `Bearer ${accessToken}`,
267
+ },
268
+ body: JSON.stringify({
269
+ access_token: accessToken,
270
+ refresh_token: refreshToken,
271
+ api: "20200115",
272
+ }),
273
+ });
274
+ }
275
+ export async function listRevisions(cfg, itemUuid) {
276
+ const res = await snFetch(`${cfg.serverUrl}/v2/items/${itemUuid}/revisions`, {
277
+ method: "GET",
278
+ headers: { Authorization: `Bearer ${cfg.authToken}` },
279
+ });
280
+ return res.revisions ?? [];
281
+ }
282
+ export async function getRevision(cfg, itemUuid, revisionUuid) {
283
+ const res = await snFetch(`${cfg.serverUrl}/v2/items/${itemUuid}/revisions/${revisionUuid}`, {
284
+ method: "GET",
285
+ headers: { Authorization: `Bearer ${cfg.authToken}` },
286
+ });
287
+ return res.revision;
288
+ }
289
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,78 @@
1
+ const WIKILINK = /\[\[([^[\]|#\r\n]+)(?:#[^[\]|\r\n]*)?(?:\|([^[\]\r\n]+))?\]\]/g;
2
+ /** Remove fenced and inline code so `[[x]]` in code isn't a link. */
3
+ function stripCode(text) {
4
+ return text
5
+ .replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "")
6
+ .replace(/`[^`\n]*`/g, "");
7
+ }
8
+ export function parseWikilinks(text) {
9
+ const out = [];
10
+ const seen = new Set();
11
+ for (const m of stripCode(text).matchAll(WIKILINK)) {
12
+ const target = (m[1] ?? "").trim();
13
+ if (target === "")
14
+ continue;
15
+ const key = target.toLowerCase();
16
+ if (seen.has(key))
17
+ continue;
18
+ seen.add(key);
19
+ const alias = m[2]?.trim();
20
+ out.push(alias ? { target, alias } : { target });
21
+ }
22
+ return out;
23
+ }
24
+ /** uuids referenced by `snbubble` nodes in a Super note's Lexical JSON. */
25
+ export function superBubbleUuids(text) {
26
+ let root;
27
+ try {
28
+ root = JSON.parse(text);
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ const out = new Set();
34
+ const stack = [root];
35
+ let guard = 0;
36
+ while (stack.length > 0 && guard++ < 100_000) {
37
+ const node = stack.pop();
38
+ if (Array.isArray(node)) {
39
+ stack.push(...node);
40
+ continue;
41
+ }
42
+ if (typeof node !== "object" || node === null)
43
+ continue;
44
+ const rec = node;
45
+ if (rec.type === "snbubble" && typeof rec.itemUuid === "string") {
46
+ out.add(rec.itemUuid);
47
+ }
48
+ for (const v of Object.values(rec)) {
49
+ if (typeof v === "object" && v !== null)
50
+ stack.push(v);
51
+ }
52
+ }
53
+ return [...out];
54
+ }
55
+ /** uuids of notes this note links to natively (references + Super bubbles). */
56
+ export function nativeLinkUuids(note) {
57
+ const out = new Set();
58
+ for (const r of note.references) {
59
+ if (r.content_type === "Note" && r.reference_type === "NoteToNote") {
60
+ out.add(r.uuid);
61
+ }
62
+ }
63
+ if (note.noteType === "super") {
64
+ for (const u of superBubbleUuids(note.text))
65
+ out.add(u);
66
+ }
67
+ return [...out];
68
+ }
69
+ /** Normalised key for title matching. */
70
+ export function titleKey(title) {
71
+ return title.trim().toLowerCase();
72
+ }
73
+ /** Whether `text` already contains a wikilink to `title`. */
74
+ export function hasWikilinkTo(text, title) {
75
+ const key = titleKey(title);
76
+ return parseWikilinks(text).some((l) => titleKey(l.target) === key);
77
+ }
78
+ //# sourceMappingURL=links.js.map
@@ -0,0 +1,141 @@
1
+ import { ToolError } from "../security/errors.js";
2
+ function parse(text) {
3
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
4
+ const lines = text.split(/\r?\n/);
5
+ const headings = [];
6
+ // Stack of currently-open headings; index = level - 1.
7
+ const stack = [];
8
+ let fence = null;
9
+ for (let i = 0; i < lines.length; i++) {
10
+ const line = lines[i] ?? "";
11
+ const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line);
12
+ if (fenceMatch) {
13
+ const marker = fenceMatch[1] ?? "";
14
+ if (fence === null) {
15
+ fence = { char: marker.charAt(0), length: marker.length };
16
+ }
17
+ else if (marker.charAt(0) === fence.char &&
18
+ marker.length >= fence.length) {
19
+ fence = null;
20
+ }
21
+ continue;
22
+ }
23
+ if (fence !== null)
24
+ continue;
25
+ const h = /^ {0,3}(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
26
+ if (!h)
27
+ continue;
28
+ const hashes = h[1] ?? "";
29
+ const title = h[2] ?? "";
30
+ const level = hashes.length;
31
+ while (stack.length > 0 && (stack[stack.length - 1]?.level ?? 0) >= level) {
32
+ stack.pop();
33
+ }
34
+ const info = {
35
+ level,
36
+ title,
37
+ line: i,
38
+ path: [...stack.map((s) => s.title), title],
39
+ };
40
+ stack.push(info);
41
+ headings.push(info);
42
+ }
43
+ return { lines, eol, headings };
44
+ }
45
+ /** Document map: every heading with its level and full `::` path. */
46
+ export function outline(text) {
47
+ return parse(text).headings;
48
+ }
49
+ function resolveHeading(parsed, sectionPath) {
50
+ const segments = sectionPath
51
+ .split("::")
52
+ .map((s) => s.trim())
53
+ .filter((s) => s.length > 0);
54
+ if (segments.length === 0) {
55
+ throw new ToolError("section_invalid", "Empty section path.", 'Pass a heading title like "Log" or a path like "Projects::Alpha".');
56
+ }
57
+ const wanted = segments.map((s) => s.toLowerCase());
58
+ const matches = parsed.headings.filter((h) => {
59
+ if (h.path.length < wanted.length)
60
+ return false;
61
+ const tail = h.path
62
+ .slice(h.path.length - wanted.length)
63
+ .map((t) => t.toLowerCase());
64
+ return tail.every((t, i) => t === wanted[i]);
65
+ });
66
+ if (matches.length === 0) {
67
+ const available = parsed.headings
68
+ .slice(0, 10)
69
+ .map((h) => h.path.join("::"))
70
+ .join(", ");
71
+ throw new ToolError("section_not_found", `No heading matches "${sectionPath}" in this note.` +
72
+ (available ? ` Headings present: ${available}.` : " The note has no headings."), "Use notes_get with format=outline to see the note's heading structure.");
73
+ }
74
+ if (matches.length > 1) {
75
+ const candidates = matches.map((h) => h.path.join("::")).join('", "');
76
+ throw new ToolError("ambiguous_section", `"${sectionPath}" matches ${matches.length} headings. Candidates: "${candidates}".`, "Pass the full path (Parent::Child) of the section you mean.");
77
+ }
78
+ const first = matches[0];
79
+ if (!first) {
80
+ throw new ToolError("section_not_found", `No heading matches "${sectionPath}".`);
81
+ }
82
+ return first;
83
+ }
84
+ /** Line index just past the end of a section's body. */
85
+ function sectionEnd(parsed, heading) {
86
+ for (const h of parsed.headings) {
87
+ if (h.line > heading.line && h.level <= heading.level)
88
+ return h.line;
89
+ }
90
+ return parsed.lines.length;
91
+ }
92
+ /** Body text of one section (heading line excluded). */
93
+ export function getSectionBody(text, sectionPath) {
94
+ const parsed = parse(text);
95
+ const heading = resolveHeading(parsed, sectionPath);
96
+ const end = sectionEnd(parsed, heading);
97
+ return parsed.lines.slice(heading.line + 1, end).join(parsed.eol);
98
+ }
99
+ /**
100
+ * Insert `content` into a section. "append" lands at the end of the
101
+ * section body (before any trailing blank lines, so following headings
102
+ * keep their spacing); "prepend" lands directly under the heading line.
103
+ * Blank-line separation is added on both sides as needed.
104
+ */
105
+ export function insertIntoSection(text, sectionPath, content, position) {
106
+ const parsed = parse(text);
107
+ const heading = resolveHeading(parsed, sectionPath);
108
+ const end = sectionEnd(parsed, heading);
109
+ const contentLines = content.split(/\r?\n/);
110
+ const lines = [...parsed.lines];
111
+ if (position === "prepend") {
112
+ const insertAt = heading.line + 1;
113
+ const insertion = [];
114
+ if (lines[insertAt] !== "")
115
+ insertion.push("");
116
+ insertion.push(...contentLines);
117
+ if (insertAt < lines.length && lines[insertAt] !== "")
118
+ insertion.push("");
119
+ lines.splice(insertAt, 0, ...insertion);
120
+ }
121
+ else {
122
+ let insertAt = end;
123
+ while (insertAt - 1 > heading.line && lines[insertAt - 1] === "") {
124
+ insertAt--;
125
+ }
126
+ const insertion = [];
127
+ if (insertAt - 1 >= heading.line + 1 && lines[insertAt - 1] !== "") {
128
+ insertion.push("");
129
+ }
130
+ else if (insertAt - 1 === heading.line) {
131
+ insertion.push("");
132
+ }
133
+ insertion.push(...contentLines);
134
+ // Keep a blank line before whatever follows the section.
135
+ if (insertAt < lines.length && lines[insertAt] !== "")
136
+ insertion.push("");
137
+ lines.splice(insertAt, 0, ...insertion);
138
+ }
139
+ return lines.join(parsed.eol);
140
+ }
141
+ //# sourceMappingURL=markdownSections.js.map
@@ -0,0 +1,135 @@
1
+ import { ToolError } from "../security/errors.js";
2
+ import { assertSafeRegex } from "../security/regex.js";
3
+ import { parseFrontmatter } from "./frontmatter.js";
4
+ export function isPredicateJson(v) {
5
+ return (typeof v === "object" &&
6
+ v !== null &&
7
+ typeof v.operator === "string");
8
+ }
9
+ function leafValue(target, keypath) {
10
+ let cur = target;
11
+ for (const part of keypath.split(".")) {
12
+ if (typeof cur !== "object" || cur === null)
13
+ return undefined;
14
+ cur = cur[part];
15
+ }
16
+ return cur;
17
+ }
18
+ function compare(operator, value, targetValue) {
19
+ // SN coerces the strings "true"/"false" to booleans at predicate-build time.
20
+ if (targetValue === "true")
21
+ targetValue = true;
22
+ if (targetValue === "false")
23
+ targetValue = false;
24
+ switch (operator) {
25
+ case "=":
26
+ return value === targetValue;
27
+ case "!=":
28
+ return value !== targetValue;
29
+ case "<":
30
+ case ">":
31
+ case "<=":
32
+ case ">=": {
33
+ const a = Number(value);
34
+ const b = Number(targetValue);
35
+ if (!Number.isFinite(a) || !Number.isFinite(b))
36
+ return false;
37
+ if (operator === "<")
38
+ return a < b;
39
+ if (operator === ">")
40
+ return a > b;
41
+ if (operator === "<=")
42
+ return a <= b;
43
+ return a >= b;
44
+ }
45
+ case "startsWith":
46
+ return (typeof value === "string" &&
47
+ typeof targetValue === "string" &&
48
+ value.toLowerCase().startsWith(targetValue.toLowerCase()));
49
+ case "includes":
50
+ if (Array.isArray(value))
51
+ return value.includes(targetValue);
52
+ return (typeof value === "string" &&
53
+ typeof targetValue === "string" &&
54
+ value.toLowerCase().includes(targetValue.toLowerCase()));
55
+ case "matches": {
56
+ if (typeof value !== "string" || typeof targetValue !== "string") {
57
+ return false;
58
+ }
59
+ assertSafeRegex(targetValue);
60
+ return new RegExp(targetValue, "i").test(value);
61
+ }
62
+ case "in":
63
+ return Array.isArray(targetValue) && targetValue.includes(value);
64
+ default:
65
+ throw new ToolError("predicate_operator_unknown", `Unknown predicate operator "${operator}".`, 'Supported: =, !=, <, >, <=, >=, startsWith, includes, matches, in, not, and, or.');
66
+ }
67
+ }
68
+ export function evaluatePredicate(predicate, target) {
69
+ const { operator, value } = predicate;
70
+ if (operator === "and" || operator === "or") {
71
+ if (!Array.isArray(value) || value.length === 0)
72
+ return false;
73
+ const subs = value.filter(isPredicateJson);
74
+ if (operator === "and") {
75
+ return subs.every((p) => evaluatePredicate(p, target));
76
+ }
77
+ return subs.some((p) => evaluatePredicate(p, target));
78
+ }
79
+ if (operator === "not") {
80
+ if (!isPredicateJson(value))
81
+ return false;
82
+ return !evaluatePredicate(value, target);
83
+ }
84
+ if (predicate.keypath === undefined)
85
+ return false;
86
+ return compare(operator, leafValue(target, predicate.keypath), value);
87
+ }
88
+ /**
89
+ * Flatten a note (+ computed fields) into the record predicates run
90
+ * against. Key names mirror SN's note model so predicates created in the
91
+ * app evaluate identically here. `tagsCount` is computed by the caller
92
+ * from the tag cache, matching SN's ItemWithTags wrapper.
93
+ *
94
+ * `frontmatter` exposes the note's top-level YAML frontmatter keys (an
95
+ * extension of this server, not an SN keypath), so `frontmatter.status`
96
+ * or `frontmatter.tags` work as keypaths. Values keep their YAML types:
97
+ * numbers, booleans, strings, and string lists (use `includes` on lists).
98
+ * Super notes have no frontmatter. Callers only ever pass notes the client
99
+ * is allowed to read, so this can't be used to probe hidden notes.
100
+ */
101
+ export function notePredicateTarget(n, tagsCount) {
102
+ return {
103
+ uuid: n.uuid,
104
+ content_type: "Note",
105
+ title: n.title,
106
+ text: n.text,
107
+ trashed: n.trashed,
108
+ archived: n.archived,
109
+ pinned: n.pinned,
110
+ protected: n.protected,
111
+ locked: n.locked,
112
+ noteType: n.noteType,
113
+ tagsCount,
114
+ created_at_timestamp: n.created_at_timestamp,
115
+ updated_at_timestamp: n.updated_at_timestamp,
116
+ frontmatter: n.noteType === "super" ? {} : parseFrontmatter(n.text).data,
117
+ };
118
+ }
119
+ /** One-line human summary of a predicate tree, for smartviews_list. */
120
+ export function summarizePredicate(predicate) {
121
+ if (!isPredicateJson(predicate))
122
+ return "(no predicate)";
123
+ const { operator, value, keypath } = predicate;
124
+ if (operator === "and" || operator === "or") {
125
+ const parts = Array.isArray(value)
126
+ ? value.map((p) => summarizePredicate(p))
127
+ : [];
128
+ return parts.join(` ${operator.toUpperCase()} `);
129
+ }
130
+ if (operator === "not") {
131
+ return `NOT (${summarizePredicate(value)})`;
132
+ }
133
+ return `${keypath ?? "?"} ${operator} ${JSON.stringify(value)}`;
134
+ }
135
+ //# sourceMappingURL=predicates.js.map