gabriel-notion 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/dist/cli/gabriel-notion.d.ts +17 -0
- package/dist/cli/gabriel-notion.js +147 -0
- package/dist/cli/gabriel-notion.js.map +1 -0
- package/dist/client/client.d.ts +220 -0
- package/dist/client/client.js +632 -0
- package/dist/client/client.js.map +1 -0
- package/dist/client/events/normalize.d.ts +114 -0
- package/dist/client/events/normalize.js +407 -0
- package/dist/client/events/normalize.js.map +1 -0
- package/dist/client/events/pipeline.d.ts +191 -0
- package/dist/client/events/pipeline.js +559 -0
- package/dist/client/events/pipeline.js.map +1 -0
- package/dist/client/events/record-diff.d.ts +16 -0
- package/dist/client/events/record-diff.js +54 -0
- package/dist/client/events/record-diff.js.map +1 -0
- package/dist/client/events/types.d.ts +124 -0
- package/dist/client/events/types.js +24 -0
- package/dist/client/events/types.js.map +1 -0
- package/dist/client/guard/llm-context.d.ts +8 -0
- package/dist/client/guard/llm-context.js +94 -0
- package/dist/client/guard/llm-context.js.map +1 -0
- package/dist/client/guard/origin.d.ts +54 -0
- package/dist/client/guard/origin.js +167 -0
- package/dist/client/guard/origin.js.map +1 -0
- package/dist/client/guard/scope.d.ts +76 -0
- package/dist/client/guard/scope.js +177 -0
- package/dist/client/guard/scope.js.map +1 -0
- package/dist/client/properties.d.ts +77 -0
- package/dist/client/properties.js +86 -0
- package/dist/client/properties.js.map +1 -0
- package/dist/client/tree.d.ts +25 -0
- package/dist/client/tree.js +85 -0
- package/dist/client/tree.js.map +1 -0
- package/dist/client/types.d.ts +111 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/client/watch/discovery.d.ts +117 -0
- package/dist/client/watch/discovery.js +514 -0
- package/dist/client/watch/discovery.js.map +1 -0
- package/dist/client/write-api.d.ts +70 -0
- package/dist/client/write-api.js +366 -0
- package/dist/client/write-api.js.map +1 -0
- package/dist/client/write.d.ts +55 -0
- package/dist/client/write.js +182 -0
- package/dist/client/write.js.map +1 -0
- package/dist/core/account.d.ts +20 -0
- package/dist/core/account.js +46 -0
- package/dist/core/account.js.map +1 -0
- package/dist/core/browser-extract.d.ts +29 -0
- package/dist/core/browser-extract.js +73 -0
- package/dist/core/browser-extract.js.map +1 -0
- package/dist/core/cookie-store.d.ts +99 -0
- package/dist/core/cookie-store.js +291 -0
- package/dist/core/cookie-store.js.map +1 -0
- package/dist/core/cookies.d.ts +51 -0
- package/dist/core/cookies.js +164 -0
- package/dist/core/cookies.js.map +1 -0
- package/dist/core/core.d.ts +127 -0
- package/dist/core/core.js +216 -0
- package/dist/core/core.js.map +1 -0
- package/dist/core/credentials.d.ts +41 -0
- package/dist/core/credentials.js +112 -0
- package/dist/core/credentials.js.map +1 -0
- package/dist/core/http.d.ts +79 -0
- package/dist/core/http.js +221 -0
- package/dist/core/http.js.map +1 -0
- package/dist/core/ids.d.ts +21 -0
- package/dist/core/ids.js +87 -0
- package/dist/core/ids.js.map +1 -0
- package/dist/core/msgstore.d.ts +254 -0
- package/dist/core/msgstore.js +738 -0
- package/dist/core/msgstore.js.map +1 -0
- package/dist/core/records.d.ts +75 -0
- package/dist/core/records.js +126 -0
- package/dist/core/records.js.map +1 -0
- package/dist/core/session.d.ts +55 -0
- package/dist/core/session.js +82 -0
- package/dist/core/session.js.map +1 -0
- package/dist/core/sign-in.d.ts +96 -0
- package/dist/core/sign-in.js +314 -0
- package/dist/core/sign-in.js.map +1 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +30 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +29 -0
- package/dist/index.js.map +1 -0
- package/dist/markdown/build.d.ts +14 -0
- package/dist/markdown/build.js +33 -0
- package/dist/markdown/build.js.map +1 -0
- package/dist/markdown/index.d.ts +7 -0
- package/dist/markdown/index.js +8 -0
- package/dist/markdown/index.js.map +1 -0
- package/dist/markdown/inline-parse.d.ts +14 -0
- package/dist/markdown/inline-parse.js +242 -0
- package/dist/markdown/inline-parse.js.map +1 -0
- package/dist/markdown/inline-render.d.ts +25 -0
- package/dist/markdown/inline-render.js +107 -0
- package/dist/markdown/inline-render.js.map +1 -0
- package/dist/markdown/languages.d.ts +3 -0
- package/dist/markdown/languages.js +36 -0
- package/dist/markdown/languages.js.map +1 -0
- package/dist/markdown/model.d.ts +66 -0
- package/dist/markdown/model.js +4 -0
- package/dist/markdown/model.js.map +1 -0
- package/dist/markdown/parse.d.ts +4 -0
- package/dist/markdown/parse.js +384 -0
- package/dist/markdown/parse.js.map +1 -0
- package/dist/markdown/render.d.ts +21 -0
- package/dist/markdown/render.js +207 -0
- package/dist/markdown/render.js.map +1 -0
- package/dist/state/file.d.ts +57 -0
- package/dist/state/file.js +257 -0
- package/dist/state/file.js.map +1 -0
- package/dist/state/store.d.ts +66 -0
- package/dist/state/store.js +86 -0
- package/dist/state/store.js.map +1 -0
- package/dist/state/watch-state.d.ts +70 -0
- package/dist/state/watch-state.js +154 -0
- package/dist/state/watch-state.js.map +1 -0
- package/dist/util/async.d.ts +19 -0
- package/dist/util/async.js +63 -0
- package/dist/util/async.js.map +1 -0
- package/dist/util/emitter.d.ts +6 -0
- package/dist/util/emitter.js +22 -0
- package/dist/util/emitter.js.map +1 -0
- package/dist/util/logger.d.ts +13 -0
- package/dist/util/logger.js +15 -0
- package/dist/util/logger.js.map +1 -0
- package/dist/util/redact.d.ts +7 -0
- package/dist/util/redact.js +23 -0
- package/dist/util/redact.js.map +1 -0
- package/package.json +62 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
## [0.1.0] - 2026-11-24
|
|
6
|
+
|
|
7
|
+
First release: read, write and watch Notion through the web session.
|
|
8
|
+
|
|
9
|
+
- Read and write API with Notion-flavored Markdown, verified by read-back.
|
|
10
|
+
- Change events named like the official webhooks, for a whole workspace or chosen subtrees,
|
|
11
|
+
delivered in-process, with recovery after disconnects and restarts.
|
|
12
|
+
- Agent safety: origin marking, loop guard, scoped views, untrusted LLM envelopes.
|
|
13
|
+
- Sign-in helpers and the `gabriel-notion` CLI.
|
|
14
|
+
|
|
15
|
+
Details by slice:
|
|
16
|
+
|
|
17
|
+
- Package skeleton (S0).
|
|
18
|
+
- `NotionCore`: in-memory cookie jar with `Set-Cookie` handling, HTTP client with workspace and active-user headers, read/write retry classes, session state machine with `auth.dead`, account and workspace binding, credential-safe errors and health (S1).
|
|
19
|
+
- Records, transactions and IDs: batched record reads (≤1,000), `role: none` and missing records mapped to `NOT_FOUND` after a session check, atomic `submit`, read-back `verify` with `WRITE_NOT_APPLIED`, ID parsing from UUIDs and page URLs, web-compatible v8 block IDs (S2).
|
|
20
|
+
- Optional credential write-back: `credentialStore` saves a cookie snapshot when a session cookie rotates; `FileCredentialStore` (0600, atomic), `loadSessionCookies()` (env, then file), `parseCookieHeader()`.
|
|
21
|
+
- Markdown codec (S4): `renderPage` reproduces official `fetch` output byte for byte on the shared fixtures; `parseMarkdown` / `parseInline` read that format and plain Markdown; `specsToRecords` builds block records from parsed specs.
|
|
22
|
+
- `NotionClient` read API (S5): `me`, `users.list/search/get`, `search` (≤1,000, `truncated`), `pages.get` (Markdown or block tree, decoded row properties), `databases.get/query` (local cursor over a cached ID list), `comments.list`. The workspace binds lazily on the first call.
|
|
23
|
+
- Browser sign-in (S3): `signInWithBrowser()` opens a temporary-profile Chrome window and returns Notion cookies in-process (optional direct Google entry); `listWorkspaces()` verifies stored cookies. New error codes `BROWSER_NOT_FOUND`, `SIGN_IN_TIMEOUT`.
|
|
24
|
+
- `extractFromDebugChrome()` reads the Notion session from a Chrome started with `--remote-debugging-port`; `gabriel-notion` CLI with `auth login | extract | status | logout`, saving through `FileCredentialStore`.
|
|
25
|
+
- Write API (S6): `pages.create` (page, database row, teamspace root, private; Markdown body; title from a leading heading), `pages.updateProperties` (by property name), `pages.updateContent` (`replace_all`, `insert`, `update`), `comments.create` (page, block, inline selection) and `comments.reply`. Every write is read back and fails with `WRITE_NOT_APPLIED` when it did not take effect.
|
|
26
|
+
- `extractFromChrome()` / `listChromeSessions()` / `gabriel-notion auth read` and `auth profiles`: decrypt the Notion session from Chrome's on-disk cookie store on macOS (no browser launch, no re-login), scanning every profile with one Keychain read, auto-picking the signed-in one and listing choices when several are signed in. Verified end-to-end against real Chrome.
|
|
27
|
+
- StateStore (S8): `StateStore` interface with `MemoryStateStore` and `FileStateStore` (atomic snapshot via temp file + fsync + rename, 0600/0700, debounced writes, single-process lock, `STATE_STORE_UNAVAILABLE` on unusable storage, rejected writes not applied); `WatchState` stores the page tree, subscription versions, activity cursors and the last 10,000 event IDs per workspace, committing a cursor and its event IDs atomically.
|
|
28
|
+
- Message Store connection (S7): `MessageStore` pool over Engine.IO v4 + Primus on Node's built-in `WebSocket` (injectable `webSocketFactory`): answers both heartbeats, detects dead peers, `registerBatchSubscriptions` / `unregisterBatchSubscriptions` / `ackNotification`, at most 40,000 keys per connection in 5,000-key batches, a batch answered with `error` retried on a new connection, `SUBSCRIPTION_CAP_EXCEEDED` past `maxConnections`, full-jitter reconnect that resubscribes with the last message versions and reports `connection.ready` with the downtime, unknown frames reported once as `protocol.drift`. `NotionCore.subscribe` / `unsubscribe` / `onSignal` / `stopRealtime` / `messageStore`; the session cookie is sent while valid and dropped when `AUTH_DEAD` or with `anonymousRealtime`; `health().realtime` lists connections.
|
|
29
|
+
- Event pipeline (S9): `normalizeActivities` maps activity-log edits to webhook-named events (`page.*`, `database.created`, `data_source.*`, `comment.*`, `view.*`) with aggregation per entity and type, cancellation, access filtering and deterministic event IDs from edit keys; `diffRecord` covers comment edits and deletions, view edits and property renames. `EventPipeline` coalesces signals (1 s), re-reads every 90 s, closes windows after 10 quiet minutes, takes a baseline on first watch, pages back to the stored cursor, commits cursor and edit keys atomically, unwatches entities with `role: "none"`, and reports `guard.protocol_drift` once per kind. `NotionClient.on()`, `start()` (explicit roots for now), `stop()`, `health()`. Shared fixtures in `spec/fixtures/events`, JSON Schemas in `spec/schema`.
|
|
30
|
+
- Watch scope and discovery (S10): `watch: { mode: "workspace" | "explicit", roots?, rescanIntervalMs? }`. `Discovery` walks the page tree from the workspace root, private section, readable teamspaces and pages shared with the account (or from explicit roots), through non-page blocks, stores it in the StateStore and watches every page, database and data source; follows new content from `versions/<page>:block`, `versions/<team>:team`, `versions/<spaceView>:space_view`, `versions/<space>:space`, `user_shared_pages_in_space/…` and `teams_in_space_v2/…`; emits `page.created` for new pages at container roots; warm starts watch the stored tree first and re-walk in the background; a periodic walk (default 6 h) reconciles the tree. New entities get a lazy baseline (`since`) instead of an up-front activity read. `health().watch`. Two-account integration tests in `test/integration` (`pnpm test:integration`). The Message Store marks the current-state frame that answers a version -1 subscription as `initial`, which the pipeline and discovery do not treat as a change, and activity reads are capped at 8 in flight (found in a cold start of a large workspace: 86,874 keys, 3 connections, about 6 minutes).
|
|
31
|
+
- Disconnect and restart recovery (S11): a lost connection or a warm start begins a recovery; entities whose keys are replayed after resubscribing with stored versions (plus open windows) are read back with `delivery: "backfill"` after a 5 s catch-up window; live events are held until `connection.gap` (`{ kind, from, to, recovered, failed, entities, events }`) is emitted; `aliveAt` is stored every 60 s and on stop; `health().lagSeconds` counts from the start of a running recovery and status is `degraded` while recovering or after an unrecovered gap. Message Store frames with version -1 are flagged `initial` (no state is not a change).
|
|
32
|
+
- Agent safety guards (S12): origin `this_client` for the SDK's own writes (records registered before each transaction, versions confirmed by read-back, lock/trash edits matched by kind and claimed once), not delivered unless `guards.deliverThisClient`; the SDK's edits and the account's other edits are separate events. Loop guard: at most 5 writes per target page per 60 s from event handlers (`guards.loop`), else `LOOP_DETECTED` and `guard.loop_detected`. `client.scope(policy)` returns a `ScopedNotionClient` (no `core`) limited to page roots and teamspaces, with read-only, action allow-list, approval hook, and switches for search and users; refusals throw `SCOPE_POLICY_VIOLATION`. `toLLMContext()` on delivered events and `pages.get()` results renders an untrusted envelope whose tags the content cannot open or close. `client.getWorkspace()`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EzEasy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,152 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gabriel-notion (Node.js)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read, write and watch Notion as yourself, through your Notion web sign-in: search, pages as
|
|
4
|
+
Markdown, databases, comments and members, plus change events named like Notion's official
|
|
5
|
+
webhooks for everything you can read in a workspace — delivered in your process, no public URL,
|
|
6
|
+
no integration to install.
|
|
7
|
+
|
|
8
|
+
Requires Node.js 22 or later. No runtime dependencies.
|
|
9
|
+
|
|
10
|
+
> Personal, non-commercial project; not affiliated with or endorsed by Notion. It uses Notion's
|
|
11
|
+
> private web protocol, which may change, and acts with your identity: use it only on accounts and
|
|
12
|
+
> workspaces you are allowed to automate, following your organization's policies and Notion's
|
|
13
|
+
> terms. The session cookie is equivalent to your password.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install gabriel-notion
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Before the npm release, install the tarball from a GitHub Release or one you packed
|
|
22
|
+
(`npm pack` in `sdks/node`):
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install ./gabriel-notion-0.1.0.tgz
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Sign in
|
|
29
|
+
|
|
30
|
+
The SDK needs your browser session's cookies. The CLI saves them to
|
|
31
|
+
`~/.config/gabriel-notion/session.json` (mode 0600); cookie values are never printed.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npx gabriel-notion auth read # macOS: read the session from Chrome's cookie store (no new login)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx gabriel-notion auth login # open a temporary Chrome window and sign in
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npx gabriel-notion auth status # check the saved session
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`auth extract --port 9222` reads it from a Chrome started with `--remote-debugging-port`, and
|
|
46
|
+
`auth logout --yes` deletes the file. In code: `loadSessionCookies()` reads
|
|
47
|
+
`GABRIEL_NOTION_COOKIES` (a browser `Cookie` header) first, then that file;
|
|
48
|
+
`signInWithBrowser()`, `extractFromChrome()` and `listWorkspaces()` do the rest.
|
|
49
|
+
|
|
50
|
+
## Read and write
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { NotionClient, loadSessionCookies } from "gabriel-notion";
|
|
54
|
+
|
|
55
|
+
const client = NotionClient.fromCookies({ cookies: (await loadSessionCookies())!, workspace: "My workspace" });
|
|
56
|
+
|
|
57
|
+
const page = await client.pages.get("https://www.notion.so/My-page-0123456789abcdef0123456789abcdef");
|
|
58
|
+
console.log(page.page.title, page.markdown);
|
|
59
|
+
|
|
60
|
+
await client.pages.updateContent(page.page.id, { op: "insert", markdown: "A new paragraph." });
|
|
61
|
+
await client.comments.create({ pageId: page.page.id, markdown: "Done." });
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
| Area | Methods |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| Identity and members | `me()`, `users.list()`, `users.search()`, `users.get()` |
|
|
67
|
+
| Search | `search(query, { titleOnly, under, sort, createdBetween, editedBetween, limit })` — at most 1,000 hits, `truncated` when there were more; a hit's `type` is the block type (`page`, `collection_view_page`, …) |
|
|
68
|
+
| Pages | `pages.get(id, { format: "markdown" \| "blocks" })`, `pages.create({ parent, title, markdown, properties })`, `pages.updateProperties()`, `pages.updateContent({ op: "replace_all" \| "insert" \| "update" })` |
|
|
69
|
+
| Databases | `databases.get()`, `databases.query(id, { filter, sorts, view, limit, cursor })` |
|
|
70
|
+
| Comments | `comments.list()`, `comments.create({ pageId, markdown, on })`, `comments.reply()` |
|
|
71
|
+
| Protocol | `client.core.callApi()`, `getRecords()`, `submit()`, `subscribe()`, `onSignal()` |
|
|
72
|
+
|
|
73
|
+
Page bodies are Notion-flavored Markdown, as in the official tools. IDs may be UUIDs, 32 hex
|
|
74
|
+
characters or page URLs. Every write is read back before it returns and fails with
|
|
75
|
+
`WRITE_NOT_APPLIED` if it did not take effect. See [`examples/read-write.ts`](examples/read-write.ts).
|
|
76
|
+
|
|
77
|
+
## Watch for changes
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const client = NotionClient.fromCookies({ cookies, workspace: "My workspace" }); // watch: whole workspace
|
|
81
|
+
|
|
82
|
+
client.on("page.content_updated", (e) => console.log(e.entity.id, e.data.updated_blocks));
|
|
83
|
+
client.on("comment.created", (e) => console.log("comment on", e.data.page_id));
|
|
84
|
+
client.on("connection.gap", (g) => console.log("recovered:", g.recovered));
|
|
85
|
+
await client.start();
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`watch: { mode: "explicit", roots: [pageOrDatabase] }` watches only those subtrees. The first
|
|
89
|
+
`start()` walks every page you can read (about 6 minutes for a workspace with 30,000 pages) and
|
|
90
|
+
saves the tree; later starts resume from it. See [`examples/watch.ts`](examples/watch.ts).
|
|
91
|
+
|
|
92
|
+
| Event | When |
|
|
93
|
+
| --- | --- |
|
|
94
|
+
| `page.created` | a page or database row is created (also at a teamspace root, in your private section, or newly shared with you) |
|
|
95
|
+
| `page.content_updated` | blocks in a page change (`data.updated_blocks`) |
|
|
96
|
+
| `page.properties_updated` | a page's title or a row's properties change (`data.updated_properties`) |
|
|
97
|
+
| `page.moved` | a page gets a new parent |
|
|
98
|
+
| `page.deleted`, `page.undeleted` | moved to or restored from the trash |
|
|
99
|
+
| `page.locked`, `page.unlocked` | page lock changes |
|
|
100
|
+
| `database.created` | a database is added to a page |
|
|
101
|
+
| `data_source.schema_updated` | properties are added, renamed or removed |
|
|
102
|
+
| `data_source.content_updated` | rows are added or removed |
|
|
103
|
+
| `comment.created`, `comment.updated`, `comment.deleted` | comments change |
|
|
104
|
+
| `view.created`, `view.updated`, `view.deleted` | database views change |
|
|
105
|
+
|
|
106
|
+
Every event has `id` (stable, for de-duplication), `type`, `timestamp`, `workspaceId`, `entity`,
|
|
107
|
+
`authors`, `data`, `origin`, `delivery` and `web` (the activity and, for single edits, the record
|
|
108
|
+
before and after). JSON Schemas are in [`spec/schema`](../../spec/schema).
|
|
109
|
+
|
|
110
|
+
* **Latency.** Typically 1–6 s; text typed into an open editing session can take up to about 90 s,
|
|
111
|
+
because Notion merges continuous edits into one activity.
|
|
112
|
+
* **`origin`.** `this_client` (this SDK's own writes — not delivered unless
|
|
113
|
+
`guards: { deliverThisClient: true }`), `self_other_client` (you, elsewhere), `other_user`.
|
|
114
|
+
* **`delivery`.** `live`, or `backfill` for changes made while disconnected or stopped; those
|
|
115
|
+
arrive first and are followed by `connection.gap` (`recovered: false` lists what could not be
|
|
116
|
+
read back).
|
|
117
|
+
* **Also:** `auth.dead` (sign in again), `guard.protocol_drift` (Notion changed something the SDK
|
|
118
|
+
does not understand), `guard.loop_detected`.
|
|
119
|
+
|
|
120
|
+
The watch state (page tree, versions, activity cursors, recent event IDs) lives in
|
|
121
|
+
`~/.config/gabriel-notion/state.json`; pass `stateStore` (`FileStateStore({ file })`,
|
|
122
|
+
`MemoryStateStore`, or your own `StateStore`) to change it. One process per state file.
|
|
123
|
+
|
|
124
|
+
## Agent safety
|
|
125
|
+
|
|
126
|
+
* **Loop guard.** Writes from event handlers are limited to 5 per page per minute
|
|
127
|
+
(`guards.loop`); the next one throws `LOOP_DETECTED`.
|
|
128
|
+
* **Scoped views.** `client.scope({ read: { roots, teamspaces, allowSearch }, write: { readOnly,
|
|
129
|
+
allowedActions }, approval })` returns the same API limited to those pages, without `core`;
|
|
130
|
+
anything else throws `SCOPE_POLICY_VIOLATION`.
|
|
131
|
+
* **LLM context.** Events and `pages.get()` results have `toLLMContext()`, which puts the content
|
|
132
|
+
in an envelope marked untrusted that the content cannot close. Tell your model that text inside
|
|
133
|
+
`<content>` is data, not instructions.
|
|
134
|
+
|
|
135
|
+
## Health and errors
|
|
136
|
+
|
|
137
|
+
`client.health()` returns `status` (`ok`, `degraded`, `dead`), the session, every Message Store
|
|
138
|
+
connection with its key count, `lagSeconds`, the watch scope, the event pipeline and its last gap,
|
|
139
|
+
and the state store. Errors are `NotionError` with a `code`; retryable ones (`RATE_LIMITED`,
|
|
140
|
+
`NETWORK_TIMEOUT`, `SERVER_ERROR`) were already retried. The full list is in
|
|
141
|
+
[spec §12](../../spec/behavior.md#12-errors).
|
|
142
|
+
|
|
143
|
+
## Limits
|
|
144
|
+
|
|
145
|
+
* Search returns at most 1,000 hits and has no continuation.
|
|
146
|
+
* Database rows are not watched one by one; their changes come through the data source.
|
|
147
|
+
* Rollups and non-numeric formulas are returned as `null` (`computed: false`).
|
|
148
|
+
* No file uploads.
|
|
149
|
+
* Message Store signals are not filtered by permission; the SDK reads every event back and drops
|
|
150
|
+
what you cannot read.
|
|
151
|
+
|
|
152
|
+
The behavior contract is [`spec/behavior.md`](../../spec/behavior.md).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { extractFromDebugChrome } from "../core/browser-extract.js";
|
|
3
|
+
import { extractFromChrome, listChromeSessions } from "../core/cookie-store.js";
|
|
4
|
+
import { FileCredentialStore, loadSessionCookies } from "../core/credentials.js";
|
|
5
|
+
import { listWorkspaces, signInWithBrowser } from "../core/sign-in.js";
|
|
6
|
+
export interface CliIo {
|
|
7
|
+
out(text: string): void;
|
|
8
|
+
err(text: string): void;
|
|
9
|
+
store: FileCredentialStore;
|
|
10
|
+
signIn: typeof signInWithBrowser;
|
|
11
|
+
extract: typeof extractFromDebugChrome;
|
|
12
|
+
read: typeof extractFromChrome;
|
|
13
|
+
listSessions: typeof listChromeSessions;
|
|
14
|
+
list: typeof listWorkspaces;
|
|
15
|
+
load: typeof loadSessionCookies;
|
|
16
|
+
}
|
|
17
|
+
export declare function main(argv: string[], io: CliIo): Promise<number>;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { extractFromDebugChrome } from "../core/browser-extract.js";
|
|
3
|
+
import { extractFromChrome, listChromeSessions } from "../core/cookie-store.js";
|
|
4
|
+
import { FileCredentialStore, loadSessionCookies } from "../core/credentials.js";
|
|
5
|
+
import { listWorkspaces, signInWithBrowser } from "../core/sign-in.js";
|
|
6
|
+
import { NotionError } from "../errors.js";
|
|
7
|
+
const HELP = `gabriel-notion — credential helper for gabriel-notion
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
gabriel-notion auth login [--google] [--email <address>]
|
|
11
|
+
Open a dedicated Chrome window with a temporary profile; after you sign in, the session
|
|
12
|
+
is verified and saved (0600). --google opens Google's consent screen directly.
|
|
13
|
+
gabriel-notion auth read [--profile <name>]
|
|
14
|
+
Read the session directly from your Chrome cookie store (no browser window, no re-login),
|
|
15
|
+
verify it, and save it (0600). With no --profile, auto-picks the only signed-in profile
|
|
16
|
+
and lists them if several are. macOS only; the first read prompts once for Keychain access.
|
|
17
|
+
gabriel-notion auth profiles
|
|
18
|
+
List the Chrome profiles that are signed in to Notion.
|
|
19
|
+
gabriel-notion auth extract [--port <n>]
|
|
20
|
+
Read the session from a Chrome you started with --remote-debugging-port (default 9222)
|
|
21
|
+
and signed in to Notion, verify it, and save it (0600).
|
|
22
|
+
gabriel-notion auth status
|
|
23
|
+
Verify the session from GABRIEL_NOTION_COOKIES or the saved file and list workspaces.
|
|
24
|
+
gabriel-notion auth logout --yes
|
|
25
|
+
Delete the saved session file.
|
|
26
|
+
|
|
27
|
+
The session file is $GABRIEL_NOTION_CONFIG_DIR/session.json, or
|
|
28
|
+
$XDG_CONFIG_HOME/gabriel-notion/session.json (default ~/.config). Cookie values are never printed.
|
|
29
|
+
`;
|
|
30
|
+
function flag(args, name) {
|
|
31
|
+
const i = args.indexOf(name);
|
|
32
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
33
|
+
}
|
|
34
|
+
function describe(io, userId, workspaces) {
|
|
35
|
+
io.out(`Signed in as user ${userId}. Workspaces (${workspaces.length}):\n`);
|
|
36
|
+
for (const w of workspaces)
|
|
37
|
+
io.out(` - ${w.name || "(unnamed)"} ${w.id}\n`);
|
|
38
|
+
}
|
|
39
|
+
export async function main(argv, io) {
|
|
40
|
+
const [group, command, ...rest] = argv;
|
|
41
|
+
if (group !== "auth" || !command) {
|
|
42
|
+
io.out(HELP);
|
|
43
|
+
return group === undefined || group === "--help" || group === "help" ? 0 : 1;
|
|
44
|
+
}
|
|
45
|
+
switch (command) {
|
|
46
|
+
case "login": {
|
|
47
|
+
const email = flag(rest, "--email");
|
|
48
|
+
const r = await io.signIn({
|
|
49
|
+
...(rest.includes("--google") ? { provider: "google" } : {}),
|
|
50
|
+
...(email ? { email } : {}),
|
|
51
|
+
onStatus: (s) => {
|
|
52
|
+
if (s === "opening")
|
|
53
|
+
io.err("Opening a sign-in window; complete the Notion sign-in there. It closes automatically.\n");
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
describe(io, r.userId, r.workspaces);
|
|
57
|
+
await io.store.save(r.cookies);
|
|
58
|
+
io.out(`Saved to ${io.store.file} (mode 0600).\n`);
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
case "read": {
|
|
62
|
+
const profileArg = flag(rest, "--profile");
|
|
63
|
+
if (!profileArg) {
|
|
64
|
+
const sessions = await io.listSessions({});
|
|
65
|
+
if (sessions.length === 0) {
|
|
66
|
+
io.err("No Chrome profile is signed in to Notion. Sign in to Notion in Chrome, or run `gabriel-notion auth login`.\n");
|
|
67
|
+
return 1;
|
|
68
|
+
}
|
|
69
|
+
if (sessions.length > 1) {
|
|
70
|
+
io.err("Several Chrome profiles are signed in to Notion; choose one with --profile:\n");
|
|
71
|
+
for (const x of sessions)
|
|
72
|
+
io.err(` --profile ${JSON.stringify(x.profileName ?? x.profile)}${x.email ? ` (${x.email})` : ""}\n`);
|
|
73
|
+
return 1;
|
|
74
|
+
}
|
|
75
|
+
const s0 = sessions[0];
|
|
76
|
+
describe(io, s0.userId, s0.workspaces);
|
|
77
|
+
await io.store.save(s0.cookies);
|
|
78
|
+
io.out(`Read Chrome profile ${JSON.stringify(s0.profileName ?? s0.profile)}. Saved to ${io.store.file} (mode 0600).\n`);
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
const r = await io.read({ profile: profileArg });
|
|
82
|
+
describe(io, r.userId, r.workspaces);
|
|
83
|
+
await io.store.save(r.cookies);
|
|
84
|
+
io.out(`Saved to ${io.store.file} (mode 0600).\n`);
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
case "profiles": {
|
|
88
|
+
const sessions = await io.listSessions({});
|
|
89
|
+
if (sessions.length === 0) {
|
|
90
|
+
io.out("No Chrome profile is signed in to Notion.\n");
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
for (const x of sessions)
|
|
94
|
+
io.out(` ${JSON.stringify(x.profileName ?? x.profile)} profile=${x.profile} user=${x.userId}${x.email ? ` ${x.email}` : ""} workspaces=${x.workspaces.length}\n`);
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
case "extract": {
|
|
98
|
+
const portArg = flag(rest, "--port");
|
|
99
|
+
const r = await io.extract({ port: portArg ? Number(portArg) : 9222 });
|
|
100
|
+
describe(io, r.userId, r.workspaces);
|
|
101
|
+
await io.store.save(r.cookies);
|
|
102
|
+
io.out(`Saved to ${io.store.file} (mode 0600).\n`);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
case "status": {
|
|
106
|
+
const cookies = await io.load({ store: io.store });
|
|
107
|
+
if (!cookies) {
|
|
108
|
+
io.err(`No session: set GABRIEL_NOTION_COOKIES or run \`gabriel-notion auth login\` (${io.store.file}).\n`);
|
|
109
|
+
return 1;
|
|
110
|
+
}
|
|
111
|
+
const r = await io.list({ cookies });
|
|
112
|
+
describe(io, r.userId, r.workspaces);
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
case "logout": {
|
|
116
|
+
if (!rest.includes("--yes")) {
|
|
117
|
+
io.err(`This deletes ${io.store.file}. Re-run with --yes to confirm. It does not sign the session out on Notion's side.\n`);
|
|
118
|
+
return 1;
|
|
119
|
+
}
|
|
120
|
+
io.out((await io.store.clear()) ? `Deleted ${io.store.file}.\n` : `Nothing to delete at ${io.store.file}.\n`);
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
default:
|
|
124
|
+
io.out(HELP);
|
|
125
|
+
return 1;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const isEntry = process.argv[1] !== undefined && /gabriel-notion(\.js|\.ts)?$/.test(process.argv[1]);
|
|
129
|
+
if (isEntry) {
|
|
130
|
+
const io = {
|
|
131
|
+
out: (t) => process.stdout.write(t),
|
|
132
|
+
err: (t) => process.stderr.write(t),
|
|
133
|
+
store: new FileCredentialStore(),
|
|
134
|
+
signIn: signInWithBrowser,
|
|
135
|
+
extract: extractFromDebugChrome,
|
|
136
|
+
read: extractFromChrome,
|
|
137
|
+
listSessions: listChromeSessions,
|
|
138
|
+
list: listWorkspaces,
|
|
139
|
+
load: loadSessionCookies,
|
|
140
|
+
};
|
|
141
|
+
main(process.argv.slice(2), io).then((code) => process.exit(code), (err) => {
|
|
142
|
+
const msg = err instanceof NotionError ? `${err.code}: ${err.message}` : "unexpected error";
|
|
143
|
+
process.stderr.write(`error: ${msg}\n`);
|
|
144
|
+
process.exit(1);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
//# sourceMappingURL=gabriel-notion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gabriel-notion.js","sourceRoot":"","sources":["../../src/cli/gabriel-notion.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAsB,MAAM,yBAAyB,CAAC;AACpG,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAG3C,MAAM,IAAI,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsBZ,CAAC;AAcF,SAAS,IAAI,CAAC,IAAc,EAAE,IAAY;IACxC,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,IA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AAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAClC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAC5B,CAAC,GAAY,EAAE,EAAE;QACf,MAAM,GAAG,GAAG,GAAG,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC;QAC5F,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { inspect } from "node:util";
|
|
2
|
+
import { NotionCore, type NotionCoreOptions } from "../core/core.js";
|
|
3
|
+
import type { SessionEvents } from "../core/session.js";
|
|
4
|
+
import { type BlockRecord } from "../markdown/model.js";
|
|
5
|
+
import type { StateStore, StateStoreHealth } from "../state/store.js";
|
|
6
|
+
import { type ConnectionGapEvent, type PipelineHealth, type PipelineOptions } from "./events/pipeline.js";
|
|
7
|
+
import { type DiscoveryHealth, type WatchOptions } from "./watch/discovery.js";
|
|
8
|
+
import { type LoopDetectedEvent } from "./guard/origin.js";
|
|
9
|
+
import { ScopedNotionClient, type ScopePolicy } from "./guard/scope.js";
|
|
10
|
+
import type { EventType, NotionEvent, ProtocolDriftEvent } from "./events/types.js";
|
|
11
|
+
import { type PropertySchema } from "./properties.js";
|
|
12
|
+
import { RecordCache } from "./tree.js";
|
|
13
|
+
import { type ContentEdit, type CreateCommentOptions, type CreatePageOptions } from "./write-api.js";
|
|
14
|
+
import type { PropertyInput } from "./write.js";
|
|
15
|
+
import type { Comment, DatabaseMeta, Discussion, Filter, Page, PageMeta, PageResult, Row, SearchHit, Sort, User, ViewMeta, Workspace } from "./types.js";
|
|
16
|
+
export type { WatchOptions } from "./watch/discovery.js";
|
|
17
|
+
export interface NotionClientOptions extends NotionCoreOptions {
|
|
18
|
+
/** The workspace this client acts in, by ID or exact name. Resolved on the first call. */
|
|
19
|
+
workspace: string;
|
|
20
|
+
/** Persistent watch state. Default: `FileStateStore` at its default path. */
|
|
21
|
+
stateStore?: StateStore;
|
|
22
|
+
watch?: WatchOptions;
|
|
23
|
+
/** Agent safety guards (spec §11). */
|
|
24
|
+
guards?: {
|
|
25
|
+
/** Deliver events caused by this SDK instance's own writes (`origin: "this_client"`). Default false. */
|
|
26
|
+
deliverThisClient?: boolean;
|
|
27
|
+
/** Writes from event handlers per target page within `windowMs` (default 5 per 60 s). */
|
|
28
|
+
loop?: {
|
|
29
|
+
maxWrites?: number;
|
|
30
|
+
windowMs?: number;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/** Tuning for the event pipeline (coalescing delay, re-read period, quiet period); mainly for tests. */
|
|
34
|
+
events?: Pick<PipelineOptions, "coalesceMs" | "recordSignalDelayMs" | "rereadMs" | "quietMs" | "pageSize" | "maxPages" | "catchUpMs" | "aliveIntervalMs" | "now">;
|
|
35
|
+
}
|
|
36
|
+
export interface ClientEvents extends Record<string, unknown> {
|
|
37
|
+
"*": NotionEvent;
|
|
38
|
+
"guard.protocol_drift": ProtocolDriftEvent;
|
|
39
|
+
"guard.loop_detected": LoopDetectedEvent;
|
|
40
|
+
"connection.gap": ConnectionGapEvent;
|
|
41
|
+
"auth.dead": SessionEvents["auth.dead"];
|
|
42
|
+
}
|
|
43
|
+
/** A change event with `toLLMContext()` attached (non-enumerable). */
|
|
44
|
+
export type DeliveredEvent<T extends EventType = EventType> = NotionEvent<T> & {
|
|
45
|
+
toLLMContext(): string;
|
|
46
|
+
};
|
|
47
|
+
/** A page read with `toLLMContext()` attached (non-enumerable). */
|
|
48
|
+
export type PageWithContext = PageResult & {
|
|
49
|
+
toLLMContext(): string;
|
|
50
|
+
};
|
|
51
|
+
export interface ClientHealth {
|
|
52
|
+
status: "ok" | "degraded" | "dead";
|
|
53
|
+
session: ReturnType<NotionCore["health"]>["session"];
|
|
54
|
+
connections: NonNullable<ReturnType<NotionCore["health"]>["realtime"]>["connections"];
|
|
55
|
+
lagSeconds: number;
|
|
56
|
+
events?: PipelineHealth;
|
|
57
|
+
watch?: DiscoveryHealth;
|
|
58
|
+
state?: StateStoreHealth;
|
|
59
|
+
}
|
|
60
|
+
type BlockRec = BlockRecord & {
|
|
61
|
+
created_time?: number;
|
|
62
|
+
last_edited_time?: number;
|
|
63
|
+
created_by_id?: string;
|
|
64
|
+
last_edited_by_id?: string;
|
|
65
|
+
view_ids?: string[];
|
|
66
|
+
discussions?: string[];
|
|
67
|
+
};
|
|
68
|
+
export declare function pageMeta(b: BlockRec, cache?: RecordCache): PageMeta;
|
|
69
|
+
/**
|
|
70
|
+
* Semantic client (spec §2). Reads in v0.1-alpha.1: identity, users, search, pages,
|
|
71
|
+
* databases and comments. One client acts as one account in one workspace.
|
|
72
|
+
*/
|
|
73
|
+
export declare class NotionClient {
|
|
74
|
+
readonly core: NotionCore;
|
|
75
|
+
private readonly workspaceArg;
|
|
76
|
+
private readonly ready;
|
|
77
|
+
private bound?;
|
|
78
|
+
private readonly queryCache;
|
|
79
|
+
private readonly emitter;
|
|
80
|
+
private readonly stateStore?;
|
|
81
|
+
private readonly watchOpts;
|
|
82
|
+
private readonly eventOpts;
|
|
83
|
+
private store?;
|
|
84
|
+
private pipeline?;
|
|
85
|
+
private discovery?;
|
|
86
|
+
private starting?;
|
|
87
|
+
private readonly logger;
|
|
88
|
+
private readonly selfWrites;
|
|
89
|
+
private readonly loopGuard;
|
|
90
|
+
private readonly deliverThisClient;
|
|
91
|
+
private constructor();
|
|
92
|
+
/** Runs a write method: loop guard on the target page, then the write with the target recorded. */
|
|
93
|
+
private guarded;
|
|
94
|
+
/**
|
|
95
|
+
* A least-privilege view for LLM tools (spec §11.3): the same read and write API,
|
|
96
|
+
* limited to the policy's pages and teamspaces, optionally read-only, without search, or with
|
|
97
|
+
* an approval hook for every write. It has no `core`, `on` or `start`. Calls outside the policy
|
|
98
|
+
* fail with `SCOPE_POLICY_VIOLATION`.
|
|
99
|
+
*/
|
|
100
|
+
scope(policy: ScopePolicy): ScopedNotionClient;
|
|
101
|
+
/**
|
|
102
|
+
* Subscribes to an event type, or `"*"` for every change event. Events are delivered only after
|
|
103
|
+
* `start()`. Returns an unsubscribe function. Handler errors are logged and do not stop delivery.
|
|
104
|
+
*/
|
|
105
|
+
on<T extends EventType>(type: T, handler: (event: DeliveredEvent<T>) => unknown): () => void;
|
|
106
|
+
on(type: "*", handler: (event: DeliveredEvent) => unknown): () => void;
|
|
107
|
+
/** The session died (§3): sign in again; nothing more is read or delivered. */
|
|
108
|
+
on(type: "auth.dead", handler: (event: SessionEvents["auth.dead"]) => void): () => void;
|
|
109
|
+
/** A handler kept writing to one page; the refused write threw `LOOP_DETECTED`. */
|
|
110
|
+
on(type: "guard.loop_detected", handler: (event: LoopDetectedEvent) => void): () => void;
|
|
111
|
+
on(type: "guard.protocol_drift", handler: (event: ProtocolDriftEvent) => void): () => void;
|
|
112
|
+
/** End of every recovery after a disconnect or restart; `recovered: false` lists what could not be backfilled. */
|
|
113
|
+
on(type: "connection.gap", handler: (event: ConnectionGapEvent) => void): () => void;
|
|
114
|
+
/**
|
|
115
|
+
* Validates the session, opens the state store, connects to the Message Store and starts
|
|
116
|
+
* watching (spec §9): on the first run it walks the page tree from its roots (the whole
|
|
117
|
+
* workspace, or `watch.roots`) and stores it; later runs watch the stored tree at once and
|
|
118
|
+
* correct it in the background. Resolves once every subscription is acknowledged.
|
|
119
|
+
*/
|
|
120
|
+
start(): Promise<void>;
|
|
121
|
+
private doStart;
|
|
122
|
+
/** Stops watching, closes the Message Store connections and flushes the state store. */
|
|
123
|
+
stop(): Promise<void>;
|
|
124
|
+
health(): ClientHealth;
|
|
125
|
+
/** Creates a client from session cookies. Nothing is sent until the first call. */
|
|
126
|
+
static fromCookies(opts: NotionClientOptions): NotionClient;
|
|
127
|
+
/** The workspace this client acts in, resolved (and bound) on first use. */
|
|
128
|
+
getWorkspace(): Promise<Workspace>;
|
|
129
|
+
/** Binds the workspace once; an unknown workspace fails here with INVALID_ARGUMENT. */
|
|
130
|
+
private workspace;
|
|
131
|
+
private cache;
|
|
132
|
+
private internals;
|
|
133
|
+
me(): Promise<User & {
|
|
134
|
+
workspaces: Workspace[];
|
|
135
|
+
}>;
|
|
136
|
+
readonly users: {
|
|
137
|
+
list: (opts?: {
|
|
138
|
+
type?: "members" | "guests";
|
|
139
|
+
query?: string;
|
|
140
|
+
cursor?: string;
|
|
141
|
+
limit?: number;
|
|
142
|
+
}) => Promise<Page<User>>;
|
|
143
|
+
search: (query: string, opts?: {
|
|
144
|
+
limit?: number;
|
|
145
|
+
}) => Promise<User[]>;
|
|
146
|
+
get: (userId: string) => Promise<User>;
|
|
147
|
+
};
|
|
148
|
+
search(query: string, opts?: {
|
|
149
|
+
titleOnly?: boolean;
|
|
150
|
+
under?: string;
|
|
151
|
+
sort?: "relevance" | "created" | "lastEdited";
|
|
152
|
+
direction?: "asc" | "desc";
|
|
153
|
+
createdBetween?: [Date, Date];
|
|
154
|
+
editedBetween?: [Date, Date];
|
|
155
|
+
limit?: number;
|
|
156
|
+
}): Promise<{
|
|
157
|
+
results: SearchHit[];
|
|
158
|
+
truncated: boolean;
|
|
159
|
+
}>;
|
|
160
|
+
readonly pages: {
|
|
161
|
+
/**
|
|
162
|
+
* Reads a page: metadata, decoded properties (database rows), and the body as
|
|
163
|
+
* Notion-flavored Markdown (default) or as a block tree. The whole subtree is read.
|
|
164
|
+
*/
|
|
165
|
+
get: (pageId: string, opts?: {
|
|
166
|
+
format?: "markdown" | "blocks";
|
|
167
|
+
signal?: AbortSignal;
|
|
168
|
+
}) => Promise<PageWithContext>;
|
|
169
|
+
/** Creates a page (or a database row) with an optional Markdown body; returns it with any skipped-block warnings. */
|
|
170
|
+
create: (opts: CreatePageOptions) => Promise<PageMeta & {
|
|
171
|
+
warnings: string[];
|
|
172
|
+
}>;
|
|
173
|
+
/** Updates the title (any page) or properties (database rows) by property name; verified by read-back. */
|
|
174
|
+
updateProperties: (pageId: string, properties: Record<string, PropertyInput>) => Promise<PageMeta>;
|
|
175
|
+
/**
|
|
176
|
+
* Edits the body: `replace_all` (keeps subpages and inline databases), `insert` (after or before
|
|
177
|
+
* a top-level block), or `update` (find and replace within one block's Markdown).
|
|
178
|
+
*/
|
|
179
|
+
updateContent: (pageId: string, edit: ContentEdit) => Promise<{
|
|
180
|
+
changedBlockIds: string[];
|
|
181
|
+
warnings: string[];
|
|
182
|
+
}>;
|
|
183
|
+
};
|
|
184
|
+
private readPage;
|
|
185
|
+
private database;
|
|
186
|
+
readonly databases: {
|
|
187
|
+
get: (dbId: string) => Promise<{
|
|
188
|
+
database: DatabaseMeta;
|
|
189
|
+
schema: Record<string, PropertySchema>;
|
|
190
|
+
views: ViewMeta[];
|
|
191
|
+
}>;
|
|
192
|
+
/**
|
|
193
|
+
* Queries rows. The server has no continuation, but returns every matching row ID in one
|
|
194
|
+
* call; the client caches that list for 10 minutes and pages through it with its own cursor,
|
|
195
|
+
* so pages neither overlap nor skip while the cache lives. A cursor used after expiry re-runs
|
|
196
|
+
* the query and continues at the same offset (rows changed meanwhile may shift).
|
|
197
|
+
*/
|
|
198
|
+
query: (dbId: string, opts?: {
|
|
199
|
+
filter?: Filter;
|
|
200
|
+
sorts?: Sort[];
|
|
201
|
+
view?: string;
|
|
202
|
+
limit?: number;
|
|
203
|
+
cursor?: string;
|
|
204
|
+
signal?: AbortSignal;
|
|
205
|
+
}) => Promise<Page<Row>>;
|
|
206
|
+
};
|
|
207
|
+
readonly comments: {
|
|
208
|
+
/** Discussions on the page and on any block in it, with their comments in order. */
|
|
209
|
+
list: (pageId: string, opts?: {
|
|
210
|
+
includeResolved?: boolean;
|
|
211
|
+
signal?: AbortSignal;
|
|
212
|
+
}) => Promise<Discussion[]>;
|
|
213
|
+
/** Adds a page, block or inline (selection) comment in a new discussion. */
|
|
214
|
+
create: (opts: CreateCommentOptions) => Promise<Comment>;
|
|
215
|
+
/** Replies in an existing discussion. */
|
|
216
|
+
reply: (discussionId: string, markdown: string) => Promise<Comment>;
|
|
217
|
+
};
|
|
218
|
+
toJSON(): Record<string, unknown>;
|
|
219
|
+
[inspect.custom](): string;
|
|
220
|
+
}
|