@dinoxx/dinox-cli 3.0.0 → 3.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/dist/chunks/{chunk-BZQYECIH.js → chunk-52XLDO77.js} +1 -1
- package/dist/chunks/{chunk-N5YDNM3P.js → chunk-5SORBZTD.js} +1 -1
- package/dist/chunks/{chunk-N2VYTZWU.js → chunk-DKY574LO.js} +3 -3
- package/dist/chunks/{chunk-ARBWJ3ZA.js → chunk-G6Y3MOUL.js} +1075 -109
- package/dist/chunks/{chunk-2DREJFKB.js → chunk-JNRA4TTH.js} +1 -1
- package/dist/chunks/{chunk-3VZNZWDG.js → chunk-LAWV5XGL.js} +5 -0
- package/dist/chunks/{chunk-MLOITAK6.js → chunk-LXC3IW4L.js} +2 -2
- package/dist/chunks/{chunk-NVKSI4BD.js → chunk-MMO7CINX.js} +50 -590
- package/dist/chunks/{chunk-HG3RZFDX.js → chunk-OZXS77HJ.js} +7 -7
- package/dist/chunks/{chunk-KJBN7TD7.js → chunk-PCB2JD6H.js} +6 -6
- package/dist/chunks/{chunk-6D3QLMRM.js → chunk-TOGYWN3D.js} +1 -1
- package/dist/chunks/{chunk-WABL3OUP.js → chunk-WCY3EKJQ.js} +4 -4
- package/dist/chunks/{chunk-SM2QOO45.js → chunk-YFGDTC2F.js} +9 -2
- package/dist/chunks/{chunk-QPVGA46P.js → chunk-YX4SIEVS.js} +3 -3
- package/dist/chunks/{cookies-ORQ3RLAH.js → cookies-UUQZXH4R.js} +4 -4
- package/dist/chunks/{ensure-MPOQ244L.js → ensure-2OPNFDRW.js} +7 -7
- package/dist/chunks/{execute-KMNZ5EFR.js → execute-C5W5ZJDC.js} +5 -5
- package/dist/chunks/{install-35YBLHXE.js → install-VBMWNPO6.js} +1 -1
- package/dist/chunks/{mcp-H667ML2O.js → mcp-WK7KIU44.js} +8 -6
- package/dist/chunks/{mcpServer-G2WEAD2O.js → mcpServer-M4HJFSNU.js} +13 -13
- package/dist/chunks/{run-7D6ATULD.js → run-WNHMZLSJ.js} +11 -11
- package/dist/chunks/{runCli-QEWWUIZN.js → runCli-GKTCIDBF.js} +12 -12
- package/dist/chunks/{setup-DSTOF3BZ.js → setup-UYCLFOZH.js} +6 -6
- package/dist/dinox.js +7 -7
- package/dist/dsh-plugin/lib/client.js +977 -267
- package/dist/dsh-plugin/lib/index.js +10 -6
- package/dist/dsh-plugin/package.json +1 -1
- package/dist/dsh-plugin/runtime.json +1 -1
- package/dist/editor-ui/mcp-app.html +420 -318
- package/package.json +5 -2
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
toAuthorizationHeaderValue,
|
|
25
25
|
withAsyncRelease,
|
|
26
26
|
writeDaemonLogLine
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-WCY3EKJQ.js";
|
|
28
28
|
import {
|
|
29
29
|
DEFAULT_TODO_FILTER,
|
|
30
30
|
TASK_STATUS_MARKDOWN_MARKER,
|
|
@@ -45,9 +45,11 @@ import {
|
|
|
45
45
|
taskStatusFromMarkdownMarker,
|
|
46
46
|
toTodoList,
|
|
47
47
|
todoSearchWire
|
|
48
|
-
} from "./chunk-
|
|
48
|
+
} from "./chunk-JNRA4TTH.js";
|
|
49
49
|
import {
|
|
50
|
+
DAEMON_METHOD_HEADER,
|
|
50
51
|
DAEMON_SERVICE_ENV,
|
|
52
|
+
DEFAULT_DAEMON_PORT,
|
|
51
53
|
acquireDaemonExclusiveIntentLock,
|
|
52
54
|
acquireDaemonStartLock,
|
|
53
55
|
acquireExclusiveSqliteLease,
|
|
@@ -65,7 +67,7 @@ import {
|
|
|
65
67
|
savePid,
|
|
66
68
|
shutdownLegacyDaemon,
|
|
67
69
|
waitForFreshDaemon
|
|
68
|
-
} from "./chunk-
|
|
70
|
+
} from "./chunk-YFGDTC2F.js";
|
|
69
71
|
import {
|
|
70
72
|
agentLaunch
|
|
71
73
|
} from "./chunk-7ODU7LXP.js";
|
|
@@ -80,7 +82,7 @@ import {
|
|
|
80
82
|
requestContext,
|
|
81
83
|
resolveUserPath,
|
|
82
84
|
sanitizeForTerminal
|
|
83
|
-
} from "./chunk-
|
|
85
|
+
} from "./chunk-TOGYWN3D.js";
|
|
84
86
|
import {
|
|
85
87
|
getConfigDir,
|
|
86
88
|
getConfigFilePath,
|
|
@@ -92,7 +94,7 @@ import {
|
|
|
92
94
|
DinoxError,
|
|
93
95
|
buildStructuredErrorPayload,
|
|
94
96
|
isRegisteredErrorCode
|
|
95
|
-
} from "./chunk-
|
|
97
|
+
} from "./chunk-LAWV5XGL.js";
|
|
96
98
|
|
|
97
99
|
// src/auth/userInfo.ts
|
|
98
100
|
import { isDeepStrictEqual } from "node:util";
|
|
@@ -11806,12 +11808,9 @@ async function uploadToOfficialStorage(deps, source, options2 = {}) {
|
|
|
11806
11808
|
content_md: null,
|
|
11807
11809
|
summary: null
|
|
11808
11810
|
});
|
|
11809
|
-
return { resourceId: id, url, name, mediaType, sizeBytes: bytes.byteLength };
|
|
11811
|
+
return { resourceId: id, url, name, mediaType, sizeBytes: bytes.byteLength, storageKey: key };
|
|
11810
11812
|
}
|
|
11811
11813
|
|
|
11812
|
-
// src/daemon/types.ts
|
|
11813
|
-
var DEFAULT_DAEMON_PORT = 45678;
|
|
11814
|
-
|
|
11815
11814
|
// src/daemon/index.ts
|
|
11816
11815
|
import { existsSync as existsSync3, watch, mkdirSync } from "node:fs";
|
|
11817
11816
|
import path13 from "node:path";
|
|
@@ -14363,7 +14362,7 @@ var NOTE_LOCAL_FTS_TABLE = "note_local_fts";
|
|
|
14363
14362
|
var DEFAULT_BATCH_SIZE = 300;
|
|
14364
14363
|
async function syncNoteTokenIndex(db, options2) {
|
|
14365
14364
|
const batchSize = Math.max(1, Math.trunc(options2?.batchSize ?? DEFAULT_BATCH_SIZE));
|
|
14366
|
-
const
|
|
14365
|
+
const nowIso3 = options2?.nowIso ?? nowIsoUtc;
|
|
14367
14366
|
const tokenize = options2?.tokenize ?? tokenizeWithJieba;
|
|
14368
14367
|
const signal = options2?.signal;
|
|
14369
14368
|
if (signal?.aborted) {
|
|
@@ -14373,7 +14372,7 @@ async function syncNoteTokenIndex(db, options2) {
|
|
|
14373
14372
|
if (signal?.aborted) {
|
|
14374
14373
|
return createIndexResult("", "", false);
|
|
14375
14374
|
}
|
|
14376
|
-
const state = await ensureIndexState(db,
|
|
14375
|
+
const state = await ensureIndexState(db, nowIso3);
|
|
14377
14376
|
let cursorUpdatedAt = state.cursor_updated_at ?? "";
|
|
14378
14377
|
let cursorId = state.cursor_id ?? "";
|
|
14379
14378
|
const result = createIndexResult(cursorUpdatedAt, cursorId, true);
|
|
@@ -14416,19 +14415,19 @@ async function syncNoteTokenIndex(db, options2) {
|
|
|
14416
14415
|
for (const row of rows) {
|
|
14417
14416
|
if (signal?.aborted) {
|
|
14418
14417
|
result.complete = false;
|
|
14419
|
-
await updateIndexCursor(db, cursorUpdatedAt, cursorId,
|
|
14418
|
+
await updateIndexCursor(db, cursorUpdatedAt, cursorId, nowIso3);
|
|
14420
14419
|
result.cursor = { updatedAt: cursorUpdatedAt, id: cursorId };
|
|
14421
14420
|
return result;
|
|
14422
14421
|
}
|
|
14423
|
-
const sortKey = await indexNoteRow(db, row, result,
|
|
14422
|
+
const sortKey = await indexNoteRow(db, row, result, nowIso3, tokenize);
|
|
14424
14423
|
cursorUpdatedAt = sortKey;
|
|
14425
14424
|
cursorId = row.id;
|
|
14426
14425
|
}
|
|
14427
|
-
await updateIndexCursor(db, cursorUpdatedAt, cursorId,
|
|
14426
|
+
await updateIndexCursor(db, cursorUpdatedAt, cursorId, nowIso3);
|
|
14428
14427
|
result.cursor = { updatedAt: cursorUpdatedAt, id: cursorId };
|
|
14429
14428
|
options2?.onBatch?.(result);
|
|
14430
14429
|
}
|
|
14431
|
-
result.complete = await reconcileSkippedRows(db, result, batchSize,
|
|
14430
|
+
result.complete = await reconcileSkippedRows(db, result, batchSize, nowIso3, tokenize, signal);
|
|
14432
14431
|
result.cursor = {
|
|
14433
14432
|
updatedAt: cursorUpdatedAt,
|
|
14434
14433
|
id: cursorId
|
|
@@ -14521,7 +14520,7 @@ async function rebuildNoteTokenIndex(db, options2) {
|
|
|
14521
14520
|
await db.execute("DELETE FROM note_local_index_state WHERE id = ?", [INDEX_STATE_ID]);
|
|
14522
14521
|
return syncNoteTokenIndex(db, options2);
|
|
14523
14522
|
}
|
|
14524
|
-
async function indexNoteRow(db, row, result,
|
|
14523
|
+
async function indexNoteRow(db, row, result, nowIso3, tokenize) {
|
|
14525
14524
|
result.scanned += 1;
|
|
14526
14525
|
const sortKey = noteSortKey(row);
|
|
14527
14526
|
const bodySource = selectIndexBodyText(row);
|
|
@@ -14542,12 +14541,12 @@ async function indexNoteRow(db, row, result, nowIso2, tokenize) {
|
|
|
14542
14541
|
SET note_updated_at = ?, is_del = ?, indexed_at = ?
|
|
14543
14542
|
WHERE id = ?
|
|
14544
14543
|
`,
|
|
14545
|
-
[sortKey, deleted ? 1 : 0,
|
|
14544
|
+
[sortKey, deleted ? 1 : 0, nowIso3(), row.id]
|
|
14546
14545
|
);
|
|
14547
14546
|
result.skipped += 1;
|
|
14548
14547
|
return sortKey;
|
|
14549
14548
|
}
|
|
14550
|
-
const changed = await reindexOneNoteFts(db, row, sourceHash, bodySource,
|
|
14549
|
+
const changed = await reindexOneNoteFts(db, row, sourceHash, bodySource, nowIso3, tokenize);
|
|
14551
14550
|
if (changed.upserted) {
|
|
14552
14551
|
result.reindexed += 1;
|
|
14553
14552
|
result.ftsRowsUpserted += 1;
|
|
@@ -14556,7 +14555,7 @@ async function indexNoteRow(db, row, result, nowIso2, tokenize) {
|
|
|
14556
14555
|
}
|
|
14557
14556
|
return sortKey;
|
|
14558
14557
|
}
|
|
14559
|
-
async function reconcileSkippedRows(db, result, batchSize,
|
|
14558
|
+
async function reconcileSkippedRows(db, result, batchSize, nowIso3, tokenize, signal) {
|
|
14560
14559
|
while (true) {
|
|
14561
14560
|
if (signal?.aborted) {
|
|
14562
14561
|
return false;
|
|
@@ -14591,7 +14590,7 @@ async function reconcileSkippedRows(db, result, batchSize, nowIso2, tokenize, si
|
|
|
14591
14590
|
if (signal?.aborted) {
|
|
14592
14591
|
return false;
|
|
14593
14592
|
}
|
|
14594
|
-
await indexNoteRow(db, row, result,
|
|
14593
|
+
await indexNoteRow(db, row, result, nowIso3, tokenize);
|
|
14595
14594
|
}
|
|
14596
14595
|
}
|
|
14597
14596
|
while (true) {
|
|
@@ -14622,14 +14621,14 @@ async function reconcileSkippedRows(db, result, batchSize, nowIso2, tokenize, si
|
|
|
14622
14621
|
}
|
|
14623
14622
|
return true;
|
|
14624
14623
|
}
|
|
14625
|
-
async function updateIndexCursor(db, cursorUpdatedAt, cursorId,
|
|
14624
|
+
async function updateIndexCursor(db, cursorUpdatedAt, cursorId, nowIso3) {
|
|
14626
14625
|
await db.execute(
|
|
14627
14626
|
`
|
|
14628
14627
|
UPDATE note_local_index_state
|
|
14629
14628
|
SET cursor_updated_at = ?, cursor_id = ?, updated_at = ?
|
|
14630
14629
|
WHERE id = ?
|
|
14631
14630
|
`,
|
|
14632
|
-
[cursorUpdatedAt, cursorId,
|
|
14631
|
+
[cursorUpdatedAt, cursorId, nowIso3(), INDEX_STATE_ID]
|
|
14633
14632
|
);
|
|
14634
14633
|
}
|
|
14635
14634
|
async function ensureFtsTable(db) {
|
|
@@ -14674,7 +14673,7 @@ async function countRowsIfAvailable(db, sql, params = []) {
|
|
|
14674
14673
|
throw error;
|
|
14675
14674
|
}
|
|
14676
14675
|
}
|
|
14677
|
-
async function ensureIndexState(db,
|
|
14676
|
+
async function ensureIndexState(db, nowIso3) {
|
|
14678
14677
|
const state = await db.getOptional(
|
|
14679
14678
|
`
|
|
14680
14679
|
SELECT cursor_updated_at, cursor_id
|
|
@@ -14691,16 +14690,16 @@ async function ensureIndexState(db, nowIso2) {
|
|
|
14691
14690
|
INSERT INTO note_local_index_state (id, cursor_updated_at, cursor_id, updated_at)
|
|
14692
14691
|
VALUES (?, ?, ?, ?)
|
|
14693
14692
|
`,
|
|
14694
|
-
[INDEX_STATE_ID, "", "",
|
|
14693
|
+
[INDEX_STATE_ID, "", "", nowIso3()]
|
|
14695
14694
|
);
|
|
14696
14695
|
return {
|
|
14697
14696
|
cursor_updated_at: "",
|
|
14698
14697
|
cursor_id: ""
|
|
14699
14698
|
};
|
|
14700
14699
|
}
|
|
14701
|
-
async function reindexOneNoteFts(db, row, sourceHash, bodySource,
|
|
14700
|
+
async function reindexOneNoteFts(db, row, sourceHash, bodySource, nowIso3, tokenize) {
|
|
14702
14701
|
const updatedAt = noteSortKey(row);
|
|
14703
|
-
const indexedAt =
|
|
14702
|
+
const indexedAt = nowIso3();
|
|
14704
14703
|
const deleted = isDeleted(row.is_del);
|
|
14705
14704
|
await db.execute(`DELETE FROM ${NOTE_LOCAL_FTS_TABLE} WHERE note_id = ?`, [row.id]);
|
|
14706
14705
|
let upserted = false;
|
|
@@ -14979,15 +14978,15 @@ var AcpGatewayAdapter = class {
|
|
|
14979
14978
|
return { kind: this.kind, agentName: agentInfo?.name ?? null, agentVersion: agentInfo?.version ?? null };
|
|
14980
14979
|
}
|
|
14981
14980
|
async runTurn(input) {
|
|
14982
|
-
const
|
|
14983
|
-
const { sessionId, created } = await this.resolveSession(
|
|
14984
|
-
await this.applyConfig(
|
|
14981
|
+
const agent2 = await this.ensureProcess();
|
|
14982
|
+
const { sessionId, created } = await this.resolveSession(agent2, input.sessionId, input.cwd);
|
|
14983
|
+
await this.applyConfig(agent2, sessionId, input.config);
|
|
14985
14984
|
const turn = { onEvent: input.onEvent, awaitApproval: input.awaitApproval, sendFile: input.sendFile, sent: 0 };
|
|
14986
14985
|
this.turns.set(sessionId, turn);
|
|
14987
14986
|
const startedAt = Date.now();
|
|
14988
14987
|
const onAbort = () => {
|
|
14989
|
-
void
|
|
14990
|
-
const pid =
|
|
14988
|
+
void agent2.connection.cancel({ sessionId }).catch(() => void 0);
|
|
14989
|
+
const pid = agent2.child.pid;
|
|
14991
14990
|
if (pid && this.turns.size === 1) {
|
|
14992
14991
|
void killRecentDescendants(pid, startedAt).then((pids) => {
|
|
14993
14992
|
if (pids.length) this.log("stopped commands left by a cancelled turn", { sessionId, pids });
|
|
@@ -15001,7 +15000,7 @@ var AcpGatewayAdapter = class {
|
|
|
15001
15000
|
for (const resource of input.resources) {
|
|
15002
15001
|
prompt.push({ type: "resource_link", uri: resource.uri, name: resource.name, mimeType: resource.mediaType ?? null });
|
|
15003
15002
|
}
|
|
15004
|
-
const response = await
|
|
15003
|
+
const response = await agent2.connection.prompt({ sessionId, prompt });
|
|
15005
15004
|
if (turn.sent === 0) await this.sendGeneratedImages(turn, sessionId, startedAt);
|
|
15006
15005
|
return { sessionId, stopReason: STOP_REASON[response.stopReason] ?? "end_turn" };
|
|
15007
15006
|
} catch (error) {
|
|
@@ -15031,24 +15030,24 @@ var AcpGatewayAdapter = class {
|
|
|
15031
15030
|
return this.probing;
|
|
15032
15031
|
}
|
|
15033
15032
|
async probeConfig() {
|
|
15034
|
-
const
|
|
15033
|
+
const agent2 = await this.ensureProcess();
|
|
15035
15034
|
const revision = this.catalogRevision;
|
|
15036
|
-
const created = await
|
|
15037
|
-
this.rememberConfig(
|
|
15038
|
-
if (
|
|
15039
|
-
await
|
|
15035
|
+
const created = await agent2.connection.newSession({ cwd: this.gateway.cwd ?? os3.homedir(), mcpServers: [] });
|
|
15036
|
+
this.rememberConfig(agent2, created.sessionId, created.configOptions, revision === this.catalogRevision);
|
|
15037
|
+
if (agent2.init.agentCapabilities?.sessionCapabilities?.close) {
|
|
15038
|
+
await agent2.connection.closeSession({ sessionId: created.sessionId }).catch(
|
|
15040
15039
|
(error) => this.log("closing the settings session failed", { error: String(error) })
|
|
15041
15040
|
);
|
|
15042
15041
|
}
|
|
15043
15042
|
return this.catalog ?? [];
|
|
15044
15043
|
}
|
|
15045
15044
|
async dispose() {
|
|
15046
|
-
const
|
|
15045
|
+
const agent2 = this.process;
|
|
15047
15046
|
this.process = null;
|
|
15048
15047
|
this.starting = null;
|
|
15049
|
-
if (!
|
|
15050
|
-
|
|
15051
|
-
|
|
15048
|
+
if (!agent2) return;
|
|
15049
|
+
agent2.child.stdin.end();
|
|
15050
|
+
agent2.child.kill("SIGTERM");
|
|
15052
15051
|
this.sessionTokens.clear();
|
|
15053
15052
|
}
|
|
15054
15053
|
/** Codex leaves generated images on disk; send the ones this turn made when it sent nothing itself. */
|
|
@@ -15070,55 +15069,55 @@ var AcpGatewayAdapter = class {
|
|
|
15070
15069
|
void turn.sendFile(file).catch((error) => this.log("sending a file from the agent message failed", { error: String(error) }));
|
|
15071
15070
|
}
|
|
15072
15071
|
/** Continues the session (loading it in `cwd` when this process has not seen it) or starts one there. */
|
|
15073
|
-
async resolveSession(
|
|
15074
|
-
if (sessionId &&
|
|
15075
|
-
if (sessionId &&
|
|
15072
|
+
async resolveSession(agent2, sessionId, cwd) {
|
|
15073
|
+
if (sessionId && agent2.liveSessions.has(sessionId)) return { sessionId, created: false };
|
|
15074
|
+
if (sessionId && agent2.init.agentCapabilities?.loadSession) {
|
|
15076
15075
|
try {
|
|
15077
15076
|
const token2 = crypto5.randomBytes(18).toString("base64url");
|
|
15078
|
-
const loaded = await
|
|
15077
|
+
const loaded = await agent2.connection.loadSession({ sessionId, cwd, mcpServers: this.mcpServers(token2, cwd) });
|
|
15079
15078
|
this.sessionTokens.set(token2, sessionId);
|
|
15080
|
-
|
|
15081
|
-
this.rememberConfig(
|
|
15079
|
+
agent2.liveSessions.add(sessionId);
|
|
15080
|
+
this.rememberConfig(agent2, sessionId, loaded.configOptions);
|
|
15082
15081
|
return { sessionId, created: false };
|
|
15083
15082
|
} catch (error) {
|
|
15084
15083
|
this.log("session/load failed; starting a new session", { sessionId, error: String(error) });
|
|
15085
15084
|
}
|
|
15086
15085
|
}
|
|
15087
15086
|
const token = crypto5.randomBytes(18).toString("base64url");
|
|
15088
|
-
const created = await
|
|
15087
|
+
const created = await agent2.connection.newSession({ cwd, mcpServers: this.mcpServers(token, cwd) });
|
|
15089
15088
|
this.sessionTokens.set(token, created.sessionId);
|
|
15090
|
-
|
|
15091
|
-
this.rememberConfig(
|
|
15089
|
+
agent2.liveSessions.add(created.sessionId);
|
|
15090
|
+
this.rememberConfig(agent2, created.sessionId, created.configOptions);
|
|
15092
15091
|
return { sessionId: created.sessionId, created: true };
|
|
15093
15092
|
}
|
|
15094
15093
|
/**
|
|
15095
15094
|
* Brings the session to the requested settings before its turn. Entries the
|
|
15096
15095
|
* agent does not offer are skipped, so a stale choice never fails the run.
|
|
15097
15096
|
*/
|
|
15098
|
-
async applyConfig(
|
|
15099
|
-
const options2 =
|
|
15097
|
+
async applyConfig(agent2, sessionId, config) {
|
|
15098
|
+
const options2 = agent2.sessionConfig.get(sessionId);
|
|
15100
15099
|
const yolo = gatewayApproval(this.gateway) === "yolo";
|
|
15101
15100
|
const forced = yolo ? mostPermissiveMode(options2) : guardedMode(options2);
|
|
15102
15101
|
const wanted = forced && (yolo || config?.[forced.id] === void 0) ? { ...config ?? {}, [forced.id]: forced.value } : config ?? {};
|
|
15103
15102
|
for (const [configId, value] of Object.entries(wanted)) {
|
|
15104
|
-
const option =
|
|
15103
|
+
const option = agent2.sessionConfig.get(sessionId)?.find((item) => item.id === configId);
|
|
15105
15104
|
if (!option || option.currentValue === value) continue;
|
|
15106
15105
|
if (!option.values.some((item) => item.value === value)) {
|
|
15107
15106
|
this.log("agent setting not offered; skipped", { configId, value });
|
|
15108
15107
|
continue;
|
|
15109
15108
|
}
|
|
15110
15109
|
try {
|
|
15111
|
-
const response = await
|
|
15112
|
-
this.rememberConfig(
|
|
15110
|
+
const response = await agent2.connection.setSessionConfigOption({ sessionId, configId, value });
|
|
15111
|
+
this.rememberConfig(agent2, sessionId, response.configOptions);
|
|
15113
15112
|
} catch (error) {
|
|
15114
15113
|
this.log("agent setting failed; continuing with the current one", { configId, error: String(error) });
|
|
15115
15114
|
}
|
|
15116
15115
|
}
|
|
15117
15116
|
}
|
|
15118
|
-
rememberConfig(
|
|
15117
|
+
rememberConfig(agent2, sessionId, options2, updateCatalog = true) {
|
|
15119
15118
|
if (!options2) return;
|
|
15120
15119
|
const normalized = normalizeConfigOptions(options2);
|
|
15121
|
-
|
|
15120
|
+
agent2.sessionConfig.set(sessionId, normalized);
|
|
15122
15121
|
if (updateCatalog) {
|
|
15123
15122
|
this.catalog = normalized;
|
|
15124
15123
|
this.catalogExpiresAt = Date.now() + 5 * 6e4;
|
|
@@ -15174,10 +15173,10 @@ var AcpGatewayAdapter = class {
|
|
|
15174
15173
|
exited
|
|
15175
15174
|
]);
|
|
15176
15175
|
exited.catch(() => void 0);
|
|
15177
|
-
const
|
|
15178
|
-
this.process =
|
|
15176
|
+
const agent2 = { child, connection, init, liveSessions: /* @__PURE__ */ new Set(), sessionConfig: /* @__PURE__ */ new Map() };
|
|
15177
|
+
this.process = agent2;
|
|
15179
15178
|
this.log("agent connected", { agent: init.agentInfo?.name ?? command, protocol: init.protocolVersion });
|
|
15180
|
-
return
|
|
15179
|
+
return agent2;
|
|
15181
15180
|
}
|
|
15182
15181
|
handleSessionUpdate(params) {
|
|
15183
15182
|
const update = params.update;
|
|
@@ -15509,21 +15508,21 @@ function mergeRequiredEnv(existing, required) {
|
|
|
15509
15508
|
}
|
|
15510
15509
|
return { env, changed };
|
|
15511
15510
|
}
|
|
15512
|
-
async function adoptDetectedAgent(userId,
|
|
15511
|
+
async function adoptDetectedAgent(userId, agent2) {
|
|
15513
15512
|
const gateways = await loadGateways(userId);
|
|
15514
|
-
const existing = gateways.find((gateway2) => gateway2.agentId ===
|
|
15515
|
-
(gateway2) => !gateway2.agentId && gateway2.kind === "acp" && gateway2.command !== void 0 && path6.basename(gateway2.command) === path6.basename(
|
|
15513
|
+
const existing = gateways.find((gateway2) => gateway2.agentId === agent2.id) ?? gateways.find(
|
|
15514
|
+
(gateway2) => !gateway2.agentId && gateway2.kind === "acp" && gateway2.command !== void 0 && path6.basename(gateway2.command) === path6.basename(agent2.command) && JSON.stringify(gateway2.args ?? []) === JSON.stringify(agent2.args)
|
|
15516
15515
|
);
|
|
15517
15516
|
if (existing) {
|
|
15518
|
-
const requiredEnv = mergeRequiredEnv(existing.env,
|
|
15519
|
-
if (existing.agentId ===
|
|
15517
|
+
const requiredEnv = mergeRequiredEnv(existing.env, agent2.env);
|
|
15518
|
+
if (existing.agentId === agent2.id && sameLaunch(existing, agent2) && !requiredEnv.changed) {
|
|
15520
15519
|
return { gateway: existing, change: "unchanged" };
|
|
15521
15520
|
}
|
|
15522
15521
|
const updated = {
|
|
15523
15522
|
...existing,
|
|
15524
|
-
agentId:
|
|
15525
|
-
command:
|
|
15526
|
-
args:
|
|
15523
|
+
agentId: agent2.id,
|
|
15524
|
+
command: agent2.command,
|
|
15525
|
+
args: agent2.args,
|
|
15527
15526
|
...requiredEnv.env ? { env: requiredEnv.env } : {}
|
|
15528
15527
|
};
|
|
15529
15528
|
await saveGateways(
|
|
@@ -15533,15 +15532,15 @@ async function adoptDetectedAgent(userId, agent) {
|
|
|
15533
15532
|
return { gateway: updated, change: "updated" };
|
|
15534
15533
|
}
|
|
15535
15534
|
const names = new Set(gateways.map((gateway2) => gateway2.name));
|
|
15536
|
-
let name =
|
|
15537
|
-
for (let index = 2; names.has(name); index += 1) name = `${
|
|
15535
|
+
let name = agent2.name;
|
|
15536
|
+
for (let index = 2; names.has(name); index += 1) name = `${agent2.name} ${index}`;
|
|
15538
15537
|
const gateway = await addGateway(userId, {
|
|
15539
15538
|
name,
|
|
15540
15539
|
kind: "acp",
|
|
15541
|
-
agentId:
|
|
15542
|
-
command:
|
|
15543
|
-
args:
|
|
15544
|
-
...
|
|
15540
|
+
agentId: agent2.id,
|
|
15541
|
+
command: agent2.command,
|
|
15542
|
+
args: agent2.args,
|
|
15543
|
+
...agent2.env ? { env: agent2.env } : {}
|
|
15545
15544
|
});
|
|
15546
15545
|
return { gateway, change: "added" };
|
|
15547
15546
|
}
|
|
@@ -17617,11 +17616,11 @@ var GatewayDeviceHost = class {
|
|
|
17617
17616
|
}
|
|
17618
17617
|
async handleRunRequest(msg) {
|
|
17619
17618
|
const { value, byteLength: byteLength2 } = decode(msg);
|
|
17620
|
-
const
|
|
17619
|
+
const invalid3 = validateRunRequest(value, byteLength2);
|
|
17621
17620
|
const raw = value ?? {};
|
|
17622
17621
|
const ids = { requestId: String(raw.requestId ?? ""), runId: String(raw.runId ?? ""), threadId: String(raw.threadId ?? "") };
|
|
17623
|
-
if (
|
|
17624
|
-
this.respondAck(msg, ids, "invalid_request", { error:
|
|
17622
|
+
if (invalid3) {
|
|
17623
|
+
this.respondAck(msg, ids, "invalid_request", { error: invalid3 });
|
|
17625
17624
|
return;
|
|
17626
17625
|
}
|
|
17627
17626
|
const request = value;
|
|
@@ -17702,7 +17701,7 @@ var GatewayDeviceHost = class {
|
|
|
17702
17701
|
}
|
|
17703
17702
|
async handleApprove(msg) {
|
|
17704
17703
|
const { value, byteLength: byteLength2 } = decode(msg);
|
|
17705
|
-
const
|
|
17704
|
+
const invalid3 = validateApprovalRequest(value, byteLength2);
|
|
17706
17705
|
const raw = value ?? {};
|
|
17707
17706
|
const base = {
|
|
17708
17707
|
protocolVersion: REMOTE_DEVICE_PROTOCOL_VERSION,
|
|
@@ -17712,8 +17711,8 @@ var GatewayDeviceHost = class {
|
|
|
17712
17711
|
threadId: String(raw.threadId ?? ""),
|
|
17713
17712
|
approvalId: String(raw.approvalId ?? "")
|
|
17714
17713
|
};
|
|
17715
|
-
if (
|
|
17716
|
-
msg.respond(encode({ ...base, accepted: false, code: "invalid_request", error:
|
|
17714
|
+
if (invalid3) {
|
|
17715
|
+
msg.respond(encode({ ...base, accepted: false, code: "invalid_request", error: invalid3 }));
|
|
17717
17716
|
return;
|
|
17718
17717
|
}
|
|
17719
17718
|
const code = this.executor.respondApproval({
|
|
@@ -18627,7 +18626,7 @@ function opaqueSpec(node, inline) {
|
|
|
18627
18626
|
return [inline ? "span" : "div", { ...base, class: inline ? "dx-chip" : "dx-atom", title: kept() }, shown(node)];
|
|
18628
18627
|
}
|
|
18629
18628
|
var OPAQUE_TYPES = /* @__PURE__ */ new Set(["dxOpaqueBlock", "dxOpaqueInline"]);
|
|
18630
|
-
var READ_ONLY_TYPES = /* @__PURE__ */ new Set(["emoji"
|
|
18629
|
+
var READ_ONLY_TYPES = /* @__PURE__ */ new Set(["emoji"]);
|
|
18631
18630
|
var opaque = (node, inline) => ({ type: inline ? "dxOpaqueInline" : "dxOpaqueBlock", attrs: { raw: JSON.stringify(node) } });
|
|
18632
18631
|
function dedupeMarks(marks, schema) {
|
|
18633
18632
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -22983,7 +22982,7 @@ async function validateSavedViewSemantics(executor, userId, filter, config) {
|
|
|
22983
22982
|
[...fields].filter((field) => field.startsWith("prop.")).map((field) => field.slice("prop.".length))
|
|
22984
22983
|
)
|
|
22985
22984
|
);
|
|
22986
|
-
const
|
|
22985
|
+
const propertySemantics2 = /* @__PURE__ */ new Map();
|
|
22987
22986
|
if (propertyKeys.length > 0) {
|
|
22988
22987
|
const placeholders = propertyKeys.map(() => "?").join(", ");
|
|
22989
22988
|
const rows = await executor.getAll(
|
|
@@ -23026,7 +23025,7 @@ async function validateSavedViewSemantics(executor, userId, filter, config) {
|
|
|
23026
23025
|
);
|
|
23027
23026
|
for (const row of rows) {
|
|
23028
23027
|
if (row.key && isPropertyType(row.type)) {
|
|
23029
|
-
|
|
23028
|
+
propertySemantics2.set(
|
|
23030
23029
|
row.key,
|
|
23031
23030
|
propertyDefToSemantic(
|
|
23032
23031
|
row.type,
|
|
@@ -23037,14 +23036,14 @@ async function validateSavedViewSemantics(executor, userId, filter, config) {
|
|
|
23037
23036
|
}
|
|
23038
23037
|
}
|
|
23039
23038
|
for (const key of propertyKeys) {
|
|
23040
|
-
if (!
|
|
23039
|
+
if (!propertySemantics2.has(key)) {
|
|
23041
23040
|
throw new Error("SAVED_VIEW_PROPERTY_NOT_FOUND");
|
|
23042
23041
|
}
|
|
23043
23042
|
}
|
|
23044
23043
|
}
|
|
23045
23044
|
const semantics = /* @__PURE__ */ new Map();
|
|
23046
23045
|
for (const field of fields) {
|
|
23047
|
-
const semantic = field.startsWith("prop.") ?
|
|
23046
|
+
const semantic = field.startsWith("prop.") ? propertySemantics2.get(field.slice("prop.".length)) : SYSTEM_FIELD_SEMANTICS[field];
|
|
23048
23047
|
if (!semantic) {
|
|
23049
23048
|
throw new Error("SAVED_VIEW_INVALID_FIELD");
|
|
23050
23049
|
}
|
|
@@ -23719,8 +23718,17 @@ function createMetaStore(db, userId) {
|
|
|
23719
23718
|
if (result.changed) changed.push("properties");
|
|
23720
23719
|
}
|
|
23721
23720
|
if (patch.properties && Object.keys(patch.properties).length) {
|
|
23722
|
-
const
|
|
23723
|
-
|
|
23721
|
+
const entries = Object.entries(patch.properties);
|
|
23722
|
+
const cleared = entries.filter(([, value]) => value === null).map(([key]) => key);
|
|
23723
|
+
const values = Object.fromEntries(entries.filter(([, value]) => value !== null));
|
|
23724
|
+
if (Object.keys(values).length) {
|
|
23725
|
+
const result = await setNoteProperties(db, { userId, noteId, patch: values });
|
|
23726
|
+
if (result.changed) changed.push("properties");
|
|
23727
|
+
}
|
|
23728
|
+
if (cleared.length) {
|
|
23729
|
+
const result = await updateNotePropertySlots2(db, { userId, noteId, operation: "clear", keys: cleared });
|
|
23730
|
+
if (result.changed) changed.push("properties");
|
|
23731
|
+
}
|
|
23724
23732
|
}
|
|
23725
23733
|
if (patch.remove?.length) {
|
|
23726
23734
|
const result = await updateNotePropertySlots2(db, { userId, noteId, operation: "remove", keys: patch.remove });
|
|
@@ -23731,8 +23739,593 @@ function createMetaStore(db, userId) {
|
|
|
23731
23739
|
return { meta, catalog, update };
|
|
23732
23740
|
}
|
|
23733
23741
|
|
|
23742
|
+
// src/commands/savedViews/fields.ts
|
|
23743
|
+
var SYSTEM_FIELD_META = {
|
|
23744
|
+
"sys.title": { name: "Title", propertyType: "text", type: "text" },
|
|
23745
|
+
"sys.created_at": { name: "Created at", propertyType: "date", type: "date" },
|
|
23746
|
+
"sys.updated_at": { name: "Updated at", propertyType: "date", type: "date" },
|
|
23747
|
+
"sys.tags": { name: "Tags", propertyType: "multi_select", type: "list" },
|
|
23748
|
+
"sys.zettel_boxes": { name: "Zettel boxes", propertyType: "relation", type: "list" },
|
|
23749
|
+
"sys.source": { name: "Source", propertyType: "text", type: "text" },
|
|
23750
|
+
"sys.type": { name: "Type", propertyType: "text", type: "text" },
|
|
23751
|
+
"sys.primary_resource_type": { name: "Primary resource type", propertyType: "select", type: "select" },
|
|
23752
|
+
"sys.starred_at": { name: "Starred at", propertyType: "date", type: "date" },
|
|
23753
|
+
"sys.images": { name: "Images", propertyType: "text", type: "text" },
|
|
23754
|
+
"sys.cover": { name: "Cover", propertyType: "text", type: "text" },
|
|
23755
|
+
"sys.audio": { name: "Audio", propertyType: "text", type: "text" },
|
|
23756
|
+
"sys.video": { name: "Video", propertyType: "text", type: "text" },
|
|
23757
|
+
"sys.file": { name: "File", propertyType: "text", type: "text" }
|
|
23758
|
+
};
|
|
23759
|
+
function valueTypeForPropertyType(type) {
|
|
23760
|
+
switch (type) {
|
|
23761
|
+
case "number":
|
|
23762
|
+
case "unique_id":
|
|
23763
|
+
return "number";
|
|
23764
|
+
case "date":
|
|
23765
|
+
return "date";
|
|
23766
|
+
case "select":
|
|
23767
|
+
case "status":
|
|
23768
|
+
return "select";
|
|
23769
|
+
case "checkbox":
|
|
23770
|
+
return "boolean";
|
|
23771
|
+
case "multi_select":
|
|
23772
|
+
case "relation":
|
|
23773
|
+
return "list";
|
|
23774
|
+
default:
|
|
23775
|
+
return "text";
|
|
23776
|
+
}
|
|
23777
|
+
}
|
|
23778
|
+
function catalogItem(field, name, propertyType2, type) {
|
|
23779
|
+
const displayOnly = isSavedViewDisplayOnlyField(field);
|
|
23780
|
+
const filterOperators = getSavedViewFilterOperatorsForField(field, propertyType2);
|
|
23781
|
+
return {
|
|
23782
|
+
field,
|
|
23783
|
+
name,
|
|
23784
|
+
type,
|
|
23785
|
+
propertyType: propertyType2,
|
|
23786
|
+
sortable: canSortSavedViewField(field, propertyType2),
|
|
23787
|
+
filterable: filterOperators.length > 0,
|
|
23788
|
+
displayOnly,
|
|
23789
|
+
filterOperators,
|
|
23790
|
+
available: true
|
|
23791
|
+
};
|
|
23792
|
+
}
|
|
23793
|
+
function propertyItem(definition) {
|
|
23794
|
+
const field = `prop.${definition.key}`;
|
|
23795
|
+
const item = {
|
|
23796
|
+
...catalogItem(field, definition.name || definition.key, definition.type, valueTypeForPropertyType(definition.type)),
|
|
23797
|
+
propertyDefinitionId: definition.id,
|
|
23798
|
+
description: definition.description ?? null,
|
|
23799
|
+
icon: definition.icon ?? null,
|
|
23800
|
+
...definition.options ? { options: definition.options } : {},
|
|
23801
|
+
...definition.config ? { config: definition.config } : {}
|
|
23802
|
+
};
|
|
23803
|
+
const error = definition.optionsMigrationPending ? { code: "PROPERTY_OPTIONS_MIGRATION_REQUIRED", message: "Legacy select options must be migrated first (dino prop migrate-options)" } : definition.optionsInvalid ? { code: "PROPERTY_OPTIONS_INVALID", message: "Stored property options are invalid" } : definition.configInvalid ? { code: "PROPERTY_DEF_CONFIG_INVALID", message: "Stored property config is invalid" } : null;
|
|
23804
|
+
return error ? { ...item, available: false, error } : item;
|
|
23805
|
+
}
|
|
23806
|
+
async function listPropertyDefinitions(db, userId, limit) {
|
|
23807
|
+
const rows = await fetchDomainReadModel(db, "properties.catalog", { userId, ...limit ? { limit } : {} });
|
|
23808
|
+
return rows.map(mapPropertyDef);
|
|
23809
|
+
}
|
|
23810
|
+
async function listSavedViewFields(db, userId) {
|
|
23811
|
+
const systemItems = SAVED_VIEW_SYSTEM_FIELDS.map((name) => {
|
|
23812
|
+
const field = `sys.${name}`;
|
|
23813
|
+
const meta = SYSTEM_FIELD_META[field] ?? { name, propertyType: "text", type: "text" };
|
|
23814
|
+
const item = catalogItem(field, meta.name, meta.propertyType, meta.type);
|
|
23815
|
+
return field === "sys.primary_resource_type" ? { ...item, values: SAVED_VIEW_PRIMARY_RESOURCE_TYPES } : item;
|
|
23816
|
+
});
|
|
23817
|
+
const definitions = await listPropertyDefinitions(db, userId);
|
|
23818
|
+
return [...systemItems, ...definitions.map(propertyItem)];
|
|
23819
|
+
}
|
|
23820
|
+
|
|
23821
|
+
// src/commands/savedViews/model.ts
|
|
23822
|
+
function issuesOf(error) {
|
|
23823
|
+
return error.issues.map((issue) => ({ path: issue.path.map(String).join("."), message: issue.message }));
|
|
23824
|
+
}
|
|
23825
|
+
function invalid(code, message, issues) {
|
|
23826
|
+
return new DinoxError(message, { code, details: issues === void 0 ? void 0 : { issues }, recoverable: false });
|
|
23827
|
+
}
|
|
23828
|
+
function parseJson3(raw, label, code) {
|
|
23829
|
+
const value = raw?.trim() ?? "";
|
|
23830
|
+
if (!value) throw invalid(code, `${label} is required`);
|
|
23831
|
+
try {
|
|
23832
|
+
return JSON.parse(value);
|
|
23833
|
+
} catch {
|
|
23834
|
+
throw invalid(code, `${label} must be valid JSON`);
|
|
23835
|
+
}
|
|
23836
|
+
}
|
|
23837
|
+
function validateSavedViewFilter(value) {
|
|
23838
|
+
const parsed = savedViewFilterSchema.safeParse(value);
|
|
23839
|
+
if (!parsed.success) {
|
|
23840
|
+
throw invalid("SAVED_VIEW_INVALID_FILTER", "Saved view filter is invalid", issuesOf(parsed.error));
|
|
23841
|
+
}
|
|
23842
|
+
return parsed.data;
|
|
23843
|
+
}
|
|
23844
|
+
function validateSavedViewConfig(value) {
|
|
23845
|
+
const parsed = savedViewConfigSchema.safeParse(value);
|
|
23846
|
+
if (!parsed.success) {
|
|
23847
|
+
throw invalid("SAVED_VIEW_INVALID_CONFIG", "Saved view config is invalid", issuesOf(parsed.error));
|
|
23848
|
+
}
|
|
23849
|
+
return parsed.data;
|
|
23850
|
+
}
|
|
23851
|
+
function parseSavedViewFilter(raw) {
|
|
23852
|
+
return validateSavedViewFilter(parseJson3(raw, "Saved view filter_json", "SAVED_VIEW_INVALID_FILTER"));
|
|
23853
|
+
}
|
|
23854
|
+
function parseSavedViewConfig(raw) {
|
|
23855
|
+
return validateSavedViewConfig(parseJson3(raw, "Saved view config_json", "SAVED_VIEW_INVALID_CONFIG"));
|
|
23856
|
+
}
|
|
23857
|
+
function baseFields(row) {
|
|
23858
|
+
return {
|
|
23859
|
+
id: row.id.trim(),
|
|
23860
|
+
userId: row.user_id?.trim() ?? "",
|
|
23861
|
+
name: row.name?.trim() ?? "",
|
|
23862
|
+
emoji: row.emoji,
|
|
23863
|
+
templateId: row.template_id,
|
|
23864
|
+
groupId: row.group_id,
|
|
23865
|
+
sortRank: row.sort_rank,
|
|
23866
|
+
pinnedAt: row.pinned_at,
|
|
23867
|
+
createdAt: row.created_at,
|
|
23868
|
+
updatedAt: row.updated_at
|
|
23869
|
+
};
|
|
23870
|
+
}
|
|
23871
|
+
function mapSavedViewRow(row) {
|
|
23872
|
+
const base = baseFields(row);
|
|
23873
|
+
if (!base.id || !base.userId || !base.name || base.name.length > 120) {
|
|
23874
|
+
throw invalid("SAVED_VIEW_INVALID_ROW", "c_saved_view row is missing a valid id, user_id, or name");
|
|
23875
|
+
}
|
|
23876
|
+
const filter = parseSavedViewFilter(row.filter_json);
|
|
23877
|
+
const config = parseSavedViewConfig(row.config_json);
|
|
23878
|
+
return { ...base, layout: config.layout, filter, config };
|
|
23879
|
+
}
|
|
23880
|
+
function inspectSavedViewRow(row) {
|
|
23881
|
+
try {
|
|
23882
|
+
return { valid: true, view: mapSavedViewRow(row) };
|
|
23883
|
+
} catch (error) {
|
|
23884
|
+
const dinoxError = error instanceof DinoxError ? error : invalid("SAVED_VIEW_INVALID_ROW", String(error));
|
|
23885
|
+
const issues = dinoxError.details?.issues;
|
|
23886
|
+
return {
|
|
23887
|
+
valid: false,
|
|
23888
|
+
view: {
|
|
23889
|
+
...baseFields(row),
|
|
23890
|
+
viewType: row.view_type,
|
|
23891
|
+
filterJson: row.filter_json,
|
|
23892
|
+
configJson: row.config_json
|
|
23893
|
+
},
|
|
23894
|
+
error: {
|
|
23895
|
+
code: dinoxError.code,
|
|
23896
|
+
message: dinoxError.message,
|
|
23897
|
+
...issues === void 0 ? {} : { issues }
|
|
23898
|
+
}
|
|
23899
|
+
};
|
|
23900
|
+
}
|
|
23901
|
+
}
|
|
23902
|
+
|
|
23903
|
+
// src/commands/savedViews/repo.ts
|
|
23904
|
+
var ACTIVE_VIEW_TYPE_SQL = `view_type IN (${SAVED_VIEW_LAYOUTS.map((layout) => `'${layout}'`).join(", ")})`;
|
|
23905
|
+
var SAVED_VIEW_COLUMNS = `
|
|
23906
|
+
id, user_id, name, emoji, filter_json, view_type, config_json, template_id, group_id,
|
|
23907
|
+
sort_rank, pinned_at, created_at, updated_at, is_del
|
|
23908
|
+
`;
|
|
23909
|
+
function nowIso2() {
|
|
23910
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
23911
|
+
}
|
|
23912
|
+
function notFound(id) {
|
|
23913
|
+
return new DinoxError(`Saved view not found: ${id}`, { code: "SAVED_VIEW_NOT_FOUND", details: { viewId: id } });
|
|
23914
|
+
}
|
|
23915
|
+
function catalogItem2(row) {
|
|
23916
|
+
const inspection = inspectSavedViewRow(row);
|
|
23917
|
+
const view = inspection.view;
|
|
23918
|
+
return {
|
|
23919
|
+
id: view.id,
|
|
23920
|
+
name: view.name,
|
|
23921
|
+
emoji: view.emoji,
|
|
23922
|
+
layout: inspection.valid ? inspection.view.layout : row.view_type,
|
|
23923
|
+
templateId: view.templateId,
|
|
23924
|
+
groupId: view.groupId,
|
|
23925
|
+
sortRank: view.sortRank,
|
|
23926
|
+
pinnedAt: view.pinnedAt,
|
|
23927
|
+
createdAt: view.createdAt,
|
|
23928
|
+
updatedAt: view.updatedAt,
|
|
23929
|
+
valid: inspection.valid,
|
|
23930
|
+
...inspection.valid ? {} : { error: { code: inspection.error.code, message: inspection.error.message } }
|
|
23931
|
+
};
|
|
23932
|
+
}
|
|
23933
|
+
async function listSavedViews(db, input) {
|
|
23934
|
+
const rows = await fetchDomainReadModel(db, "savedViews.catalog", {
|
|
23935
|
+
userId: input.userId,
|
|
23936
|
+
...input.limit === void 0 ? {} : { limit: input.limit }
|
|
23937
|
+
});
|
|
23938
|
+
return rows.filter((row) => row.id?.trim()).map(catalogItem2);
|
|
23939
|
+
}
|
|
23940
|
+
async function findSavedViewRow(db, input) {
|
|
23941
|
+
return await db.getOptional(
|
|
23942
|
+
`
|
|
23943
|
+
SELECT ${SAVED_VIEW_COLUMNS}
|
|
23944
|
+
FROM c_saved_view
|
|
23945
|
+
WHERE id = ?
|
|
23946
|
+
AND user_id = ?
|
|
23947
|
+
AND ${ACTIVE_VIEW_TYPE_SQL}
|
|
23948
|
+
AND (is_del IS NULL OR is_del = 0)
|
|
23949
|
+
LIMIT 1
|
|
23950
|
+
`,
|
|
23951
|
+
[input.id.trim(), input.userId]
|
|
23952
|
+
) ?? null;
|
|
23953
|
+
}
|
|
23954
|
+
async function getSavedView(db, input) {
|
|
23955
|
+
const row = await findSavedViewRow(db, input);
|
|
23956
|
+
if (!row) throw notFound(input.id);
|
|
23957
|
+
return inspectSavedViewRow(row);
|
|
23958
|
+
}
|
|
23959
|
+
function parseJsonValue(raw) {
|
|
23960
|
+
if (!raw?.trim()) return void 0;
|
|
23961
|
+
try {
|
|
23962
|
+
return JSON.parse(raw);
|
|
23963
|
+
} catch {
|
|
23964
|
+
return void 0;
|
|
23965
|
+
}
|
|
23966
|
+
}
|
|
23967
|
+
function parseObject(raw) {
|
|
23968
|
+
const value = parseJsonValue(raw);
|
|
23969
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
23970
|
+
}
|
|
23971
|
+
function parseStringArray(raw) {
|
|
23972
|
+
const value = parseJsonValue(raw);
|
|
23973
|
+
return Array.isArray(value) ? value.flatMap((item) => typeof item === "string" && item.trim() ? [item.trim()] : []) : [];
|
|
23974
|
+
}
|
|
23975
|
+
function parseImages(raw) {
|
|
23976
|
+
const value = parseJsonValue(raw);
|
|
23977
|
+
return Array.isArray(value) ? value : [];
|
|
23978
|
+
}
|
|
23979
|
+
function resolveSystemValue(row, field) {
|
|
23980
|
+
switch (field) {
|
|
23981
|
+
case "sys.title":
|
|
23982
|
+
return row.title;
|
|
23983
|
+
case "sys.created_at":
|
|
23984
|
+
return row.created_at;
|
|
23985
|
+
case "sys.updated_at":
|
|
23986
|
+
return row.updated_at;
|
|
23987
|
+
case "sys.starred_at":
|
|
23988
|
+
return row.starred_at;
|
|
23989
|
+
case "sys.source":
|
|
23990
|
+
return row.source;
|
|
23991
|
+
case "sys.type":
|
|
23992
|
+
return row.type;
|
|
23993
|
+
case "sys.tags":
|
|
23994
|
+
return parseStringArray(row.tags);
|
|
23995
|
+
case "sys.zettel_boxes":
|
|
23996
|
+
return parseStringArray(row.zettel_boxes);
|
|
23997
|
+
case "sys.images":
|
|
23998
|
+
return parseImages(row.images);
|
|
23999
|
+
case "sys.cover":
|
|
24000
|
+
return parseImages(row.images)[0] ?? null;
|
|
24001
|
+
case "sys.primary_resource_type":
|
|
24002
|
+
return row.primary_resource_type ?? null;
|
|
24003
|
+
case "sys.audio":
|
|
24004
|
+
case "sys.video":
|
|
24005
|
+
case "sys.file":
|
|
24006
|
+
return row.primary_resource_type === field.slice("sys.".length);
|
|
24007
|
+
default:
|
|
24008
|
+
return void 0;
|
|
24009
|
+
}
|
|
24010
|
+
}
|
|
24011
|
+
function describeOption(value, options2) {
|
|
24012
|
+
const option = options2.find((candidate) => candidate.id === value);
|
|
24013
|
+
return option ? { id: option.id, label: option.label, archived: option.archived, color: option.color, ...option.group ? { group: option.group } : {} } : { id: value, label: null, unknown: true };
|
|
24014
|
+
}
|
|
24015
|
+
function displayValue(value, semantic) {
|
|
24016
|
+
const options2 = semantic?.options;
|
|
24017
|
+
if (!options2) return value;
|
|
24018
|
+
if ((semantic.propertyType === "select" || semantic.propertyType === "status") && typeof value === "string") {
|
|
24019
|
+
return describeOption(value, options2);
|
|
24020
|
+
}
|
|
24021
|
+
if (semantic.propertyType === "multi_select" && Array.isArray(value)) {
|
|
24022
|
+
return value.map((item) => typeof item === "string" ? describeOption(item, options2) : item);
|
|
24023
|
+
}
|
|
24024
|
+
return value;
|
|
24025
|
+
}
|
|
24026
|
+
function evaluateComputedColumn(properties, column4) {
|
|
24027
|
+
const read = (field) => {
|
|
24028
|
+
if (!field.startsWith("prop.")) return null;
|
|
24029
|
+
const raw = properties[field.slice("prop.".length)];
|
|
24030
|
+
return typeof raw === "number" && Number.isFinite(raw) ? raw : null;
|
|
24031
|
+
};
|
|
24032
|
+
const left = read(column4.expr.left);
|
|
24033
|
+
const right = read(column4.expr.right);
|
|
24034
|
+
if (left === null || right === null) return null;
|
|
24035
|
+
switch (column4.expr.op) {
|
|
24036
|
+
case "*":
|
|
24037
|
+
return left * right;
|
|
24038
|
+
case "/":
|
|
24039
|
+
return right === 0 ? null : left / right;
|
|
24040
|
+
case "+":
|
|
24041
|
+
return left + right;
|
|
24042
|
+
case "-":
|
|
24043
|
+
return left - right;
|
|
24044
|
+
}
|
|
24045
|
+
}
|
|
24046
|
+
function projectRow(row, fields, computedColumns, semantics) {
|
|
24047
|
+
const properties = parseObject(row.properties);
|
|
24048
|
+
const values = {};
|
|
24049
|
+
const displayValues = {};
|
|
24050
|
+
for (const field of fields) {
|
|
24051
|
+
const value = field.startsWith("prop.") ? Object.hasOwn(properties, field.slice("prop.".length)) ? properties[field.slice("prop.".length)] : void 0 : resolveSystemValue(row, field);
|
|
24052
|
+
if (value === void 0) continue;
|
|
24053
|
+
values[field] = value;
|
|
24054
|
+
if (field === "sys.zettel_boxes") {
|
|
24055
|
+
const details = parseSavedViewZettelBoxDetails(row.zettel_box_details);
|
|
24056
|
+
if (details.length > 0) displayValues[field] = details;
|
|
24057
|
+
continue;
|
|
24058
|
+
}
|
|
24059
|
+
const display = displayValue(value, semantics.get(field));
|
|
24060
|
+
if (display !== value) displayValues[field] = display;
|
|
24061
|
+
}
|
|
24062
|
+
for (const column4 of computedColumns) {
|
|
24063
|
+
values[`calc.${column4.id}`] = evaluateComputedColumn(properties, column4);
|
|
24064
|
+
}
|
|
24065
|
+
return {
|
|
24066
|
+
id: row.id,
|
|
24067
|
+
title: row.title,
|
|
24068
|
+
values,
|
|
24069
|
+
...Object.keys(displayValues).length > 0 ? { displayValues } : {}
|
|
24070
|
+
};
|
|
24071
|
+
}
|
|
24072
|
+
function projectedColumns(config, semantics) {
|
|
24073
|
+
return [
|
|
24074
|
+
...config.columns.map((column4) => {
|
|
24075
|
+
const semantic = semantics.get(column4.field);
|
|
24076
|
+
return {
|
|
24077
|
+
field: column4.field,
|
|
24078
|
+
type: semantic?.type ?? "text",
|
|
24079
|
+
propertyType: semantic?.propertyType ?? null,
|
|
24080
|
+
dateMode: semantic?.dateMode ?? null,
|
|
24081
|
+
...semantic?.displayOnly ? { displayOnly: true } : {},
|
|
24082
|
+
...semantic?.options ? { options: semantic.options } : {}
|
|
24083
|
+
};
|
|
24084
|
+
}),
|
|
24085
|
+
...(config.computedColumns ?? []).map((column4) => ({
|
|
24086
|
+
field: `calc.${column4.id}`,
|
|
24087
|
+
type: "number",
|
|
24088
|
+
propertyType: null,
|
|
24089
|
+
dateMode: null,
|
|
24090
|
+
computed: column4
|
|
24091
|
+
}))
|
|
24092
|
+
];
|
|
24093
|
+
}
|
|
24094
|
+
async function resolveScope(db, input) {
|
|
24095
|
+
try {
|
|
24096
|
+
return await resolveSavedViewQueryScope(db, input);
|
|
24097
|
+
} catch (error) {
|
|
24098
|
+
const mapped = toDinoxError(error, "savedViews.query");
|
|
24099
|
+
if (mapped.code === "SAVED_VIEW_NOT_FOUND") throw notFound(input.viewId);
|
|
24100
|
+
throw mapped;
|
|
24101
|
+
}
|
|
24102
|
+
}
|
|
24103
|
+
async function querySavedView(db, input) {
|
|
24104
|
+
const limit = Math.min(500, Math.max(1, Math.trunc(input.limit ?? 100)));
|
|
24105
|
+
const offset = Math.max(0, Math.trunc(input.offset ?? 0));
|
|
24106
|
+
return withReadTransaction(db, async (tx) => {
|
|
24107
|
+
const scope = await resolveScope(tx, input);
|
|
24108
|
+
const pageInput = { viewId: input.viewId, userId: input.userId, timeZone: input.timeZone, limit, offset };
|
|
24109
|
+
const rawRows = await fetchSavedViewScopedPage(tx, pageInput, scope);
|
|
24110
|
+
const totalCount = await countSavedViewScopedRows(tx, pageInput, scope);
|
|
24111
|
+
const view = await getSavedView(tx, { id: input.viewId, userId: input.userId });
|
|
24112
|
+
const fields = scope.config.columns.map((column4) => column4.field);
|
|
24113
|
+
const rows = rawRows.map((row) => projectRow(row, fields, scope.config.computedColumns ?? [], scope.semantics));
|
|
24114
|
+
const nextOffset = offset + rows.length;
|
|
24115
|
+
const hasMore = nextOffset < totalCount;
|
|
24116
|
+
return {
|
|
24117
|
+
view: view.view,
|
|
24118
|
+
columns: projectedColumns(scope.config, scope.semantics),
|
|
24119
|
+
totalCount,
|
|
24120
|
+
offset,
|
|
24121
|
+
limit,
|
|
24122
|
+
nextOffset: hasMore ? nextOffset : null,
|
|
24123
|
+
hasMore,
|
|
24124
|
+
rows
|
|
24125
|
+
};
|
|
24126
|
+
});
|
|
24127
|
+
}
|
|
24128
|
+
async function countSavedViewRows(db, input) {
|
|
24129
|
+
return withReadTransaction(db, async (tx) => {
|
|
24130
|
+
const scope = await resolveScope(tx, input);
|
|
24131
|
+
return countSavedViewScopedRows(tx, input, scope);
|
|
24132
|
+
});
|
|
24133
|
+
}
|
|
24134
|
+
async function getSavedViewAnalytics(db, input) {
|
|
24135
|
+
const view = await getSavedView(db, { id: input.viewId, userId: input.userId });
|
|
24136
|
+
const [analytics] = await fetchDomainReadModel(db, "savedViews.analytics", {
|
|
24137
|
+
viewId: input.viewId,
|
|
24138
|
+
userId: input.userId,
|
|
24139
|
+
...input.timeZone ? { timeZone: input.timeZone } : {}
|
|
24140
|
+
});
|
|
24141
|
+
const config = view.valid ? view.view.config : void 0;
|
|
24142
|
+
return {
|
|
24143
|
+
stats: analytics?.stats ?? [],
|
|
24144
|
+
charts: analytics?.charts ?? [],
|
|
24145
|
+
summary: analytics?.summary ?? [],
|
|
24146
|
+
config: {
|
|
24147
|
+
...config?.stats ? { stats: config.stats } : {},
|
|
24148
|
+
...config?.charts ? { charts: config.charts } : {},
|
|
24149
|
+
...config?.summary ? { summary: config.summary } : {},
|
|
24150
|
+
...config?.computedColumns ? { computedColumns: config.computedColumns } : {}
|
|
24151
|
+
}
|
|
24152
|
+
};
|
|
24153
|
+
}
|
|
24154
|
+
async function propertySemantics(db, userId) {
|
|
24155
|
+
const definitions = await listPropertyDefinitions(db, userId);
|
|
24156
|
+
return new Map(definitions.map((definition) => [
|
|
24157
|
+
`prop.${definition.key}`,
|
|
24158
|
+
{
|
|
24159
|
+
type: valueTypeForPropertyType(definition.type),
|
|
24160
|
+
propertyType: definition.type,
|
|
24161
|
+
...definition.options ? { options: definition.options } : {}
|
|
24162
|
+
}
|
|
24163
|
+
]));
|
|
24164
|
+
}
|
|
24165
|
+
async function getNoteDetailSections(db, input) {
|
|
24166
|
+
return withReadTransaction(db, async (tx) => {
|
|
24167
|
+
const sections = await fetchDomainReadModel(tx, "savedViews.noteDetail", {
|
|
24168
|
+
noteId: input.noteId,
|
|
24169
|
+
userId: input.userId,
|
|
24170
|
+
...input.timeZone ? { timeZone: input.timeZone } : {},
|
|
24171
|
+
...input.limit === void 0 ? {} : { limit: input.limit }
|
|
24172
|
+
});
|
|
24173
|
+
if (sections.length === 0) return [];
|
|
24174
|
+
const semantics = await propertySemantics(tx, input.userId);
|
|
24175
|
+
const result = [];
|
|
24176
|
+
for (const section of sections) {
|
|
24177
|
+
const view = await getSavedView(tx, { id: section.view_id, userId: input.userId });
|
|
24178
|
+
const config = view.valid ? view.view.config : createDefaultSavedViewConfig();
|
|
24179
|
+
const fields = config.columns.map((column4) => column4.field);
|
|
24180
|
+
result.push({
|
|
24181
|
+
viewId: section.view_id,
|
|
24182
|
+
name: section.name,
|
|
24183
|
+
emoji: section.emoji,
|
|
24184
|
+
totalCount: section.total_count,
|
|
24185
|
+
columns: projectedColumns(config, semantics),
|
|
24186
|
+
rows: section.rows.map((row) => projectRow(row, fields, config.computedColumns ?? [], semantics))
|
|
24187
|
+
});
|
|
24188
|
+
}
|
|
24189
|
+
return result;
|
|
24190
|
+
});
|
|
24191
|
+
}
|
|
24192
|
+
function withLayout(config, layout) {
|
|
24193
|
+
return layout === void 0 || layout === config.layout ? config : { ...config, layout };
|
|
24194
|
+
}
|
|
24195
|
+
async function resolveUpdateConfig(db, input) {
|
|
24196
|
+
if (input.config !== void 0) return withLayout(input.config, input.layout);
|
|
24197
|
+
if (input.layout === void 0) return void 0;
|
|
24198
|
+
const row = await findSavedViewRow(db, input);
|
|
24199
|
+
if (!row) throw notFound(input.id);
|
|
24200
|
+
return withLayout(parseSavedViewConfig(row.config_json), input.layout);
|
|
24201
|
+
}
|
|
24202
|
+
function definedEntries(value) {
|
|
24203
|
+
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
|
|
24204
|
+
}
|
|
24205
|
+
async function runCreate2(db, input) {
|
|
24206
|
+
const config = withLayout(input.config ?? createDefaultSavedViewConfig(), input.layout);
|
|
24207
|
+
const { result: id } = await runDomainCommand(db, "savedViews.create", definedEntries({
|
|
24208
|
+
userId: input.userId,
|
|
24209
|
+
name: input.name,
|
|
24210
|
+
emoji: input.emoji,
|
|
24211
|
+
filter: input.filter ?? createDefaultSavedViewFilter(),
|
|
24212
|
+
config,
|
|
24213
|
+
templateId: input.templateId,
|
|
24214
|
+
groupId: input.groupId,
|
|
24215
|
+
sortRank: input.sortRank,
|
|
24216
|
+
pinnedAt: input.pinnedAt,
|
|
24217
|
+
updatedAt: nowIso2()
|
|
24218
|
+
}));
|
|
24219
|
+
return getSavedView(db, { id, userId: input.userId });
|
|
24220
|
+
}
|
|
24221
|
+
async function runUpdate(db, input) {
|
|
24222
|
+
const config = await resolveUpdateConfig(db, input);
|
|
24223
|
+
const { result: changed } = await runDomainCommand(db, "savedViews.update", definedEntries({
|
|
24224
|
+
id: input.id,
|
|
24225
|
+
userId: input.userId,
|
|
24226
|
+
name: input.name,
|
|
24227
|
+
emoji: input.emoji,
|
|
24228
|
+
filter: input.filter,
|
|
24229
|
+
config,
|
|
24230
|
+
templateId: input.templateId,
|
|
24231
|
+
groupId: input.groupId,
|
|
24232
|
+
sortRank: input.sortRank,
|
|
24233
|
+
pinnedAt: input.pinnedAt,
|
|
24234
|
+
updatedAt: nowIso2()
|
|
24235
|
+
}));
|
|
24236
|
+
if (!changed) throw notFound(input.id);
|
|
24237
|
+
return getSavedView(db, input);
|
|
24238
|
+
}
|
|
24239
|
+
async function runDelete2(db, input) {
|
|
24240
|
+
const before = await getSavedView(db, input);
|
|
24241
|
+
const { result: changed } = await runDomainCommand(db, "savedViews.softDelete", {
|
|
24242
|
+
id: input.id,
|
|
24243
|
+
userId: input.userId,
|
|
24244
|
+
updatedAt: nowIso2()
|
|
24245
|
+
});
|
|
24246
|
+
if (!changed) throw notFound(input.id);
|
|
24247
|
+
return before;
|
|
24248
|
+
}
|
|
24249
|
+
async function createSavedView2(db, input) {
|
|
24250
|
+
return runCreate2(db, input);
|
|
24251
|
+
}
|
|
24252
|
+
async function updateSavedView2(db, input) {
|
|
24253
|
+
return runUpdate(db, input);
|
|
24254
|
+
}
|
|
24255
|
+
async function deleteSavedView(db, input) {
|
|
24256
|
+
return runDelete2(db, input);
|
|
24257
|
+
}
|
|
24258
|
+
async function previewCreateSavedView(db, input) {
|
|
24259
|
+
return previewInRolledBackTransaction(db, (tx) => runCreate2(tx, input), async (_tx, after) => ({
|
|
24260
|
+
action: "create",
|
|
24261
|
+
before: null,
|
|
24262
|
+
after
|
|
24263
|
+
}));
|
|
24264
|
+
}
|
|
24265
|
+
async function previewUpdateSavedView(db, input) {
|
|
24266
|
+
const before = await getSavedView(db, input);
|
|
24267
|
+
return previewInRolledBackTransaction(db, (tx) => runUpdate(tx, input), async (_tx, after) => ({
|
|
24268
|
+
action: "update",
|
|
24269
|
+
before,
|
|
24270
|
+
after
|
|
24271
|
+
}));
|
|
24272
|
+
}
|
|
24273
|
+
async function previewDeleteSavedView(db, input) {
|
|
24274
|
+
return previewInRolledBackTransaction(db, (tx) => runDelete2(tx, input), async (_tx, before) => ({
|
|
24275
|
+
action: "delete",
|
|
24276
|
+
before,
|
|
24277
|
+
after: null
|
|
24278
|
+
}));
|
|
24279
|
+
}
|
|
24280
|
+
|
|
24281
|
+
// src/editor/views.ts
|
|
24282
|
+
var EDITOR_VIEW_EMBED_DEFAULT_LIMIT = 20;
|
|
24283
|
+
var EDITOR_VIEW_EMBED_MAX_LIMIT = 50;
|
|
24284
|
+
var SNIPPET_CHARS = 160;
|
|
24285
|
+
async function listEditorViews(db, userId) {
|
|
24286
|
+
const views = await listSavedViews(db, { userId });
|
|
24287
|
+
return views.map((view) => ({ id: view.id, name: view.name ?? "", emoji: view.emoji?.trim() || null }));
|
|
24288
|
+
}
|
|
24289
|
+
async function fetchEditorViewEmbed(db, userId, request) {
|
|
24290
|
+
const [embed] = await fetchDomainReadModel(db, "savedViews.embed", {
|
|
24291
|
+
userId,
|
|
24292
|
+
limit: request.limit,
|
|
24293
|
+
...request.timeZone ? { timeZone: request.timeZone } : {},
|
|
24294
|
+
...request.noteId ? { noteId: request.noteId } : {},
|
|
24295
|
+
...request.viewId !== void 0 ? { viewId: request.viewId } : { definition: request.definition }
|
|
24296
|
+
});
|
|
24297
|
+
if (!embed) return { status: "missing", name: "", emoji: null, total: 0, rows: [] };
|
|
24298
|
+
const ids = embed.rows.map((row) => row.id);
|
|
24299
|
+
const snippets = /* @__PURE__ */ new Map();
|
|
24300
|
+
if (ids.length) {
|
|
24301
|
+
const notes = await db.getAll(
|
|
24302
|
+
`SELECT id, summary, content_text FROM c_note WHERE id IN (${ids.map(() => "?").join(",")})`,
|
|
24303
|
+
ids
|
|
24304
|
+
);
|
|
24305
|
+
for (const note of notes) snippets.set(note.id, snippet(resolveSummary(note.summary, note.content_text)));
|
|
24306
|
+
}
|
|
24307
|
+
return {
|
|
24308
|
+
status: embed.status,
|
|
24309
|
+
name: embed.name ?? "",
|
|
24310
|
+
emoji: embed.emoji ?? null,
|
|
24311
|
+
total: Number(embed.total_count) || 0,
|
|
24312
|
+
rows: embed.rows.map((row) => ({
|
|
24313
|
+
id: row.id,
|
|
24314
|
+
title: row.title?.trim() ?? "",
|
|
24315
|
+
updatedAt: row.updated_at ?? null,
|
|
24316
|
+
snippet: snippets.get(row.id) ?? ""
|
|
24317
|
+
}))
|
|
24318
|
+
};
|
|
24319
|
+
}
|
|
24320
|
+
function snippet(text) {
|
|
24321
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
24322
|
+
const chars = Array.from(flat);
|
|
24323
|
+
return chars.length > SNIPPET_CHARS ? `${chars.slice(0, SNIPPET_CHARS - 1).join("")}\u2026` : flat;
|
|
24324
|
+
}
|
|
24325
|
+
|
|
23734
24326
|
// src/editor/schema.ts
|
|
23735
24327
|
import { getSchema as getSchema2 } from "@tiptap/core";
|
|
24328
|
+
import { CodeBlock } from "@tiptap/extension-code-block";
|
|
23736
24329
|
import { Highlight as Highlight2 } from "@tiptap/extension-highlight";
|
|
23737
24330
|
import { TextAlign as TextAlign2 } from "@tiptap/extension-text-align";
|
|
23738
24331
|
|
|
@@ -23899,6 +24492,8 @@ function presented(entries) {
|
|
|
23899
24492
|
})));
|
|
23900
24493
|
}
|
|
23901
24494
|
var EDITOR_PRESENTATION = {
|
|
24495
|
+
// Same node as StarterKit's; standing alone so the panel can give code blocks a view (diagram and mind-map previews).
|
|
24496
|
+
codeBlock: CodeBlock,
|
|
23902
24497
|
noteGlobalAttributes: NoteGlobalAttributes.extend({ addGlobalAttributes() {
|
|
23903
24498
|
return presented(this.parent?.() ?? []);
|
|
23904
24499
|
} }),
|
|
@@ -23969,6 +24564,8 @@ function createEditorStore(db, options2) {
|
|
|
23969
24564
|
meta: meta.meta,
|
|
23970
24565
|
catalog: meta.catalog,
|
|
23971
24566
|
updateMeta: meta.update,
|
|
24567
|
+
views: () => listEditorViews(db, options2.userId),
|
|
24568
|
+
viewEmbed: (request) => fetchEditorViewEmbed(db, options2.userId, request),
|
|
23972
24569
|
async load(noteId) {
|
|
23973
24570
|
return noteFromRow(await readRow(noteId));
|
|
23974
24571
|
},
|
|
@@ -23980,6 +24577,7 @@ function createEditorStore(db, options2) {
|
|
|
23980
24577
|
return { status: result.status, hash: result.hash, version: result.version, updatedAt: result.updatedAt };
|
|
23981
24578
|
},
|
|
23982
24579
|
async search(query, limit) {
|
|
24580
|
+
if (query.trim()) await syncNoteTokenIndex(db);
|
|
23983
24581
|
const { rows } = await searchNotesPage(db, query, { includeDeleted: false, limit, offset: 0 });
|
|
23984
24582
|
if (!rows.length) return [];
|
|
23985
24583
|
const dates = await db.getAll(
|
|
@@ -24264,6 +24862,261 @@ function reconcileBlocks(previous, next, newId) {
|
|
|
24264
24862
|
return { ids: result, changes };
|
|
24265
24863
|
}
|
|
24266
24864
|
|
|
24865
|
+
// src/editor/linkPreview.ts
|
|
24866
|
+
import { lookup as dnsLookup } from "node:dns";
|
|
24867
|
+
import { BlockList, isIP } from "node:net";
|
|
24868
|
+
import { load } from "cheerio";
|
|
24869
|
+
import { Agent, fetch as undiciFetch } from "undici";
|
|
24870
|
+
var TIMEOUT_MS = 15e3;
|
|
24871
|
+
var MAX_BYTES = 2 * 1024 * 1024;
|
|
24872
|
+
var MAX_REDIRECTS = 5;
|
|
24873
|
+
var MAX_URL_LENGTH = 4e3;
|
|
24874
|
+
var USER_AGENT = "Mozilla/5.0 (compatible; DinoxLinkPreview/1.0; +https://dinox.info)";
|
|
24875
|
+
var BLOCKED = new BlockList();
|
|
24876
|
+
for (const [network, prefix] of [
|
|
24877
|
+
["0.0.0.0", 8],
|
|
24878
|
+
["10.0.0.0", 8],
|
|
24879
|
+
["100.64.0.0", 10],
|
|
24880
|
+
["127.0.0.0", 8],
|
|
24881
|
+
["169.254.0.0", 16],
|
|
24882
|
+
["172.16.0.0", 12],
|
|
24883
|
+
["192.0.0.0", 24],
|
|
24884
|
+
["192.0.2.0", 24],
|
|
24885
|
+
["192.88.99.0", 24],
|
|
24886
|
+
["192.168.0.0", 16],
|
|
24887
|
+
["198.51.100.0", 24],
|
|
24888
|
+
["203.0.113.0", 24],
|
|
24889
|
+
["224.0.0.0", 4],
|
|
24890
|
+
["240.0.0.0", 4]
|
|
24891
|
+
]) BLOCKED.addSubnet(network, prefix, "ipv4");
|
|
24892
|
+
for (const [network, prefix] of [
|
|
24893
|
+
["::", 128],
|
|
24894
|
+
["::1", 128],
|
|
24895
|
+
["64:ff9b::", 96],
|
|
24896
|
+
["100::", 64],
|
|
24897
|
+
["2001:db8::", 32],
|
|
24898
|
+
["fc00::", 7],
|
|
24899
|
+
["fe80::", 10],
|
|
24900
|
+
["fec0::", 10],
|
|
24901
|
+
["ff00::", 8]
|
|
24902
|
+
]) BLOCKED.addSubnet(network, prefix, "ipv6");
|
|
24903
|
+
function isBlockedAddress(address) {
|
|
24904
|
+
const bare = address.replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
|
24905
|
+
const family = isIP(bare);
|
|
24906
|
+
if (family === 4) return BLOCKED.check(bare, "ipv4");
|
|
24907
|
+
if (family !== 6) return true;
|
|
24908
|
+
const mapped = /^(?:0*:)*(?:ffff:)?(\d+\.\d+\.\d+\.\d+)$/i.exec(bare)?.[1];
|
|
24909
|
+
if (mapped) return BLOCKED.check(mapped, "ipv4");
|
|
24910
|
+
const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(bare);
|
|
24911
|
+
if (hexMapped) {
|
|
24912
|
+
const high = Number.parseInt(hexMapped[1], 16);
|
|
24913
|
+
const low = Number.parseInt(hexMapped[2], 16);
|
|
24914
|
+
return BLOCKED.check(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`, "ipv4");
|
|
24915
|
+
}
|
|
24916
|
+
return BLOCKED.check(bare, "ipv6");
|
|
24917
|
+
}
|
|
24918
|
+
function blocked(message) {
|
|
24919
|
+
return new DinoxError(message, { code: "EDITOR_LINK_PREVIEW_BLOCKED", recoverable: true });
|
|
24920
|
+
}
|
|
24921
|
+
function failed(message, cause) {
|
|
24922
|
+
return new DinoxError(message, { code: "EDITOR_LINK_PREVIEW_FAILED", recoverable: true, ...cause ? { cause } : {} });
|
|
24923
|
+
}
|
|
24924
|
+
function parsePreviewUrl(raw) {
|
|
24925
|
+
if (typeof raw !== "string" || !raw.trim()) throw blocked("url must be a non-empty string");
|
|
24926
|
+
if (raw.length > MAX_URL_LENGTH) throw blocked("url is too long");
|
|
24927
|
+
let url;
|
|
24928
|
+
try {
|
|
24929
|
+
url = new URL(raw.trim());
|
|
24930
|
+
} catch {
|
|
24931
|
+
throw blocked(`Not a valid URL: ${raw.slice(0, 200)}`);
|
|
24932
|
+
}
|
|
24933
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw blocked("Only http and https links can be previewed");
|
|
24934
|
+
if (url.username || url.password) throw blocked("Links with credentials cannot be previewed");
|
|
24935
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
24936
|
+
if (!host) throw blocked("The link has no host");
|
|
24937
|
+
if (isIP(host) && isBlockedAddress(host)) throw blocked(`${host} is not a public address`);
|
|
24938
|
+
if (/^localhost$|\.localhost$|\.local$|\.internal$/i.test(host)) throw blocked(`${host} is not a public host`);
|
|
24939
|
+
url.hash = "";
|
|
24940
|
+
return url;
|
|
24941
|
+
}
|
|
24942
|
+
var guardedLookup = (hostname, options2, callback) => {
|
|
24943
|
+
dnsLookup(hostname, { ...options2, all: true }, (error, addresses) => {
|
|
24944
|
+
if (error) return callback(error, "", 0);
|
|
24945
|
+
const list = addresses;
|
|
24946
|
+
const bad = list.find((entry) => isBlockedAddress(entry.address));
|
|
24947
|
+
if (!list.length || bad) {
|
|
24948
|
+
return callback(Object.assign(new Error(`${hostname} resolves to a non-public address`), { code: "EDITOR_LINK_PREVIEW_BLOCKED" }), "", 0);
|
|
24949
|
+
}
|
|
24950
|
+
if (options2.all) return callback(null, list);
|
|
24951
|
+
return callback(null, list[0].address, list[0].family);
|
|
24952
|
+
});
|
|
24953
|
+
};
|
|
24954
|
+
var agent = null;
|
|
24955
|
+
function guardedAgent() {
|
|
24956
|
+
agent ??= new Agent({ connect: { lookup: guardedLookup, timeout: TIMEOUT_MS } });
|
|
24957
|
+
return agent;
|
|
24958
|
+
}
|
|
24959
|
+
async function readCapped(body, maxBytes) {
|
|
24960
|
+
if (!body) return new Uint8Array();
|
|
24961
|
+
const reader = body.getReader();
|
|
24962
|
+
const chunks = [];
|
|
24963
|
+
let size = 0;
|
|
24964
|
+
try {
|
|
24965
|
+
while (size < maxBytes) {
|
|
24966
|
+
const { done, value } = await reader.read();
|
|
24967
|
+
if (done) break;
|
|
24968
|
+
const room = maxBytes - size;
|
|
24969
|
+
const chunk = value.byteLength > room ? value.subarray(0, room) : value;
|
|
24970
|
+
chunks.push(chunk);
|
|
24971
|
+
size += chunk.byteLength;
|
|
24972
|
+
}
|
|
24973
|
+
} finally {
|
|
24974
|
+
await reader.cancel().catch(() => void 0);
|
|
24975
|
+
}
|
|
24976
|
+
const out = new Uint8Array(size);
|
|
24977
|
+
let offset = 0;
|
|
24978
|
+
for (const chunk of chunks) {
|
|
24979
|
+
out.set(chunk, offset);
|
|
24980
|
+
offset += chunk.byteLength;
|
|
24981
|
+
}
|
|
24982
|
+
return out;
|
|
24983
|
+
}
|
|
24984
|
+
function decodeHtml(bytes, contentType) {
|
|
24985
|
+
const headerCharset = /charset=["']?([\w-]+)/i.exec(contentType)?.[1];
|
|
24986
|
+
const head = new TextDecoder("latin1").decode(bytes.subarray(0, 4096));
|
|
24987
|
+
const metaCharset = /<meta[^>]+charset=["']?([\w-]+)/i.exec(head)?.[1];
|
|
24988
|
+
for (const label of [headerCharset, metaCharset, "utf-8"]) {
|
|
24989
|
+
if (!label) continue;
|
|
24990
|
+
try {
|
|
24991
|
+
return new TextDecoder(label.toLowerCase()).decode(bytes);
|
|
24992
|
+
} catch {
|
|
24993
|
+
}
|
|
24994
|
+
}
|
|
24995
|
+
return new TextDecoder().decode(bytes);
|
|
24996
|
+
}
|
|
24997
|
+
function previewDomain(url) {
|
|
24998
|
+
try {
|
|
24999
|
+
return new URL(url).hostname.replace(/^www\./i, "");
|
|
25000
|
+
} catch {
|
|
25001
|
+
return "";
|
|
25002
|
+
}
|
|
25003
|
+
}
|
|
25004
|
+
function absolute(value, base) {
|
|
25005
|
+
const trimmed = value?.trim();
|
|
25006
|
+
if (!trimmed) return "";
|
|
25007
|
+
try {
|
|
25008
|
+
const resolved = new URL(trimmed, base);
|
|
25009
|
+
return resolved.protocol === "http:" || resolved.protocol === "https:" ? resolved.href : "";
|
|
25010
|
+
} catch {
|
|
25011
|
+
return "";
|
|
25012
|
+
}
|
|
25013
|
+
}
|
|
25014
|
+
var clean = (value, max) => (value ?? "").replace(/\s+/g, " ").trim().slice(0, max);
|
|
25015
|
+
function parseLinkPreviewHtml(html, pageUrl) {
|
|
25016
|
+
const $ = load(html);
|
|
25017
|
+
const meta = (...keys) => {
|
|
25018
|
+
for (const key of keys) {
|
|
25019
|
+
const value = $(`meta[property="${key}"], meta[name="${key}"]`).first().attr("content");
|
|
25020
|
+
if (value?.trim()) return value;
|
|
25021
|
+
}
|
|
25022
|
+
return "";
|
|
25023
|
+
};
|
|
25024
|
+
const base = absolute($("base[href]").first().attr("href"), pageUrl) || pageUrl;
|
|
25025
|
+
const icon = $("link[rel]").toArray().map((element) => $(element)).find((link) => /(^|\s)icon(\s|$)/i.test(link.attr("rel") ?? "") && link.attr("href")?.trim())?.attr("href");
|
|
25026
|
+
return {
|
|
25027
|
+
url: pageUrl,
|
|
25028
|
+
title: clean(meta("og:title", "twitter:title") || $("title").first().text(), 300),
|
|
25029
|
+
description: clean(meta("og:description", "description", "twitter:description"), 1e3),
|
|
25030
|
+
siteName: clean(meta("og:site_name", "application-name"), 200),
|
|
25031
|
+
domain: previewDomain(pageUrl),
|
|
25032
|
+
imageUrl: absolute(meta("og:image", "og:image:url", "og:image:secure_url", "twitter:image"), base),
|
|
25033
|
+
iconUrl: absolute(icon, base) || absolute("/favicon.ico", pageUrl)
|
|
25034
|
+
};
|
|
25035
|
+
}
|
|
25036
|
+
async function fetchLinkPreview(rawUrl, options2 = {}) {
|
|
25037
|
+
let url = parsePreviewUrl(rawUrl);
|
|
25038
|
+
const signal = AbortSignal.timeout(options2.timeoutMs ?? TIMEOUT_MS);
|
|
25039
|
+
const headers = { "User-Agent": USER_AGENT, Accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.5", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8" };
|
|
25040
|
+
const doFetch = options2.fetchImpl ?? ((target, init) => undiciFetch(target, { ...init, redirect: "manual", dispatcher: guardedAgent() }));
|
|
25041
|
+
try {
|
|
25042
|
+
for (let hop = 0; ; hop++) {
|
|
25043
|
+
const response = await doFetch(url.href, { signal, headers });
|
|
25044
|
+
const location = response.headers.get("location");
|
|
25045
|
+
if (response.status >= 300 && response.status < 400 && location) {
|
|
25046
|
+
await response.body?.cancel().catch(() => void 0);
|
|
25047
|
+
if (hop >= MAX_REDIRECTS) throw failed("Too many redirects");
|
|
25048
|
+
url = parsePreviewUrl(new URL(location, url).href);
|
|
25049
|
+
continue;
|
|
25050
|
+
}
|
|
25051
|
+
if (!response.ok) {
|
|
25052
|
+
await response.body?.cancel().catch(() => void 0);
|
|
25053
|
+
throw failed(`The page answered HTTP ${response.status}`);
|
|
25054
|
+
}
|
|
25055
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
25056
|
+
if (/^image\//i.test(contentType)) {
|
|
25057
|
+
await response.body?.cancel().catch(() => void 0);
|
|
25058
|
+
return { ...emptyPreview(url.href), imageUrl: url.href };
|
|
25059
|
+
}
|
|
25060
|
+
if (contentType && !/html|xml/i.test(contentType)) {
|
|
25061
|
+
await response.body?.cancel().catch(() => void 0);
|
|
25062
|
+
return emptyPreview(url.href);
|
|
25063
|
+
}
|
|
25064
|
+
const bytes = await readCapped(response.body, MAX_BYTES);
|
|
25065
|
+
return parseLinkPreviewHtml(decodeHtml(bytes, contentType), url.href);
|
|
25066
|
+
}
|
|
25067
|
+
} catch (error) {
|
|
25068
|
+
if (error instanceof DinoxError) throw error;
|
|
25069
|
+
if (hasBlockedCause(error)) throw blocked(`${url.hostname} is not a public address`);
|
|
25070
|
+
if (signal.aborted) throw failed("The page took too long to answer", error);
|
|
25071
|
+
throw failed(`Fetching the page failed: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
25072
|
+
}
|
|
25073
|
+
}
|
|
25074
|
+
function emptyPreview(url) {
|
|
25075
|
+
return { url, title: "", description: "", siteName: "", domain: previewDomain(url), imageUrl: "", iconUrl: absolute("/favicon.ico", url) };
|
|
25076
|
+
}
|
|
25077
|
+
function hasBlockedCause(error) {
|
|
25078
|
+
for (let current = error, depth = 0; current && depth < 5; depth++) {
|
|
25079
|
+
if (current.code === "EDITOR_LINK_PREVIEW_BLOCKED") return true;
|
|
25080
|
+
current = current.cause;
|
|
25081
|
+
}
|
|
25082
|
+
return false;
|
|
25083
|
+
}
|
|
25084
|
+
|
|
25085
|
+
// src/editor/upload.ts
|
|
25086
|
+
var MAX_EDITOR_IMAGE_BYTES = 25 * 1024 * 1024;
|
|
25087
|
+
var MAX_EDITOR_FILE_BYTES = 500 * 1024 * 1024;
|
|
25088
|
+
var MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/i;
|
|
25089
|
+
var BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
25090
|
+
function invalid2(message) {
|
|
25091
|
+
return new DinoxError(message, { code: "EDITOR_UPLOAD_INVALID", recoverable: true });
|
|
25092
|
+
}
|
|
25093
|
+
function maxUploadBytes(mediaType) {
|
|
25094
|
+
return mediaType.toLowerCase().startsWith("image/") ? MAX_EDITOR_IMAGE_BYTES : MAX_EDITOR_FILE_BYTES;
|
|
25095
|
+
}
|
|
25096
|
+
function parseEditorUpload(input) {
|
|
25097
|
+
const rawName = typeof input.name === "string" ? input.name : "";
|
|
25098
|
+
const name = rawName.replace(/[\u0000-\u001f\u007f]/g, "").split(/[\\/]/).pop().trim().slice(0, 255);
|
|
25099
|
+
if (!name) throw invalid2("name must be a non-empty file name");
|
|
25100
|
+
const mediaType = typeof input.mediaType === "string" ? input.mediaType.trim().toLowerCase() : "";
|
|
25101
|
+
if (!MEDIA_TYPE.test(mediaType)) throw invalid2("mediaType must be a media type such as image/png");
|
|
25102
|
+
if (typeof input.data !== "string") throw invalid2("data must be a base64 string");
|
|
25103
|
+
const data = input.data.replace(/^data:[^,]*;base64,/i, "").replace(/[\r\n]/g, "");
|
|
25104
|
+
if (!data) throw invalid2("data is empty");
|
|
25105
|
+
if (data.length % 4 !== 0 || !BASE64.test(data)) throw invalid2("data is not valid base64");
|
|
25106
|
+
const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
|
|
25107
|
+
const size = data.length / 4 * 3 - padding;
|
|
25108
|
+
if (size <= 0) throw invalid2("data is empty");
|
|
25109
|
+
const maxBytes = maxUploadBytes(mediaType);
|
|
25110
|
+
if (size > maxBytes) {
|
|
25111
|
+
throw new DinoxError(`${name} is larger than ${Math.round(maxBytes / 1024 / 1024)} MB`, {
|
|
25112
|
+
code: "EDITOR_UPLOAD_TOO_LARGE",
|
|
25113
|
+
recoverable: true,
|
|
25114
|
+
details: { sizeBytes: size, maxBytes }
|
|
25115
|
+
});
|
|
25116
|
+
}
|
|
25117
|
+
return { name, mediaType, data, maxBytes };
|
|
25118
|
+
}
|
|
25119
|
+
|
|
24267
25120
|
// src/editor/service.ts
|
|
24268
25121
|
var MAX_TODO_SUGGESTIONS = 10;
|
|
24269
25122
|
var MAX_KEY_LENGTH = 200;
|
|
@@ -24285,6 +25138,7 @@ var UPLOAD_TIMEOUT_MS = 3e4;
|
|
|
24285
25138
|
function usage2(message, code = "INVALID_ARGUMENT") {
|
|
24286
25139
|
return new DinoxError(message, { code, recoverable: true });
|
|
24287
25140
|
}
|
|
25141
|
+
var BLOCK_ID_TYPE_SET2 = new Set(BLOCK_ID_TYPES2);
|
|
24288
25142
|
function str2(value, name, { optional = false, max = 2e5 } = {}) {
|
|
24289
25143
|
if (value === void 0 && optional) return void 0;
|
|
24290
25144
|
if (typeof value !== "string") throw usage2(`${name} must be a string`);
|
|
@@ -24638,6 +25492,69 @@ var EditorService = class {
|
|
|
24638
25492
|
}
|
|
24639
25493
|
return index;
|
|
24640
25494
|
}
|
|
25495
|
+
/**
|
|
25496
|
+
* Another note's content, for the panel's `@` mention (the desktop's "embed a note"): the
|
|
25497
|
+
* document without block ids, so the copy gets its own when it is inserted.
|
|
25498
|
+
*/
|
|
25499
|
+
async excerpt(input) {
|
|
25500
|
+
const noteId = str2(input.noteId, "noteId", { max: 200 });
|
|
25501
|
+
const note = await this.options.store.load(noteId);
|
|
25502
|
+
const strip = (node) => {
|
|
25503
|
+
const out = { ...node };
|
|
25504
|
+
if (node.attrs && "id" in node.attrs && BLOCK_ID_TYPE_SET2.has(node.type ?? "")) {
|
|
25505
|
+
const { id: _id, ...rest } = node.attrs;
|
|
25506
|
+
out.attrs = rest;
|
|
25507
|
+
}
|
|
25508
|
+
if (node.content) out.content = node.content.map(strip);
|
|
25509
|
+
return out;
|
|
25510
|
+
};
|
|
25511
|
+
return { id: note.noteId, title: note.title, document: strip(note.document) };
|
|
25512
|
+
}
|
|
25513
|
+
/** A file the panel inserts (pasted / dropped), uploaded to Dinox storage. */
|
|
25514
|
+
async upload(input) {
|
|
25515
|
+
const request = parseEditorUpload(input);
|
|
25516
|
+
if (!this.options.upload) {
|
|
25517
|
+
throw new DinoxError("Uploading files needs a signed-in Dinox daemon.", { code: "AUTH_REQUIRED", recoverable: true });
|
|
25518
|
+
}
|
|
25519
|
+
try {
|
|
25520
|
+
return await this.options.upload(request);
|
|
25521
|
+
} catch (error) {
|
|
25522
|
+
if (error instanceof DinoxError) throw error;
|
|
25523
|
+
throw new DinoxError(`Uploading ${request.name} failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
25524
|
+
code: "EDITOR_UPLOAD_FAILED",
|
|
25525
|
+
recoverable: true,
|
|
25526
|
+
cause: error
|
|
25527
|
+
});
|
|
25528
|
+
}
|
|
25529
|
+
}
|
|
25530
|
+
/** Title, description, image and icon of a public web page, for a link card. */
|
|
25531
|
+
async linkPreview(input) {
|
|
25532
|
+
return (this.options.linkPreview ?? fetchLinkPreview)(input.url);
|
|
25533
|
+
}
|
|
25534
|
+
/** The user's saved views, for the view block's picker. */
|
|
25535
|
+
async views() {
|
|
25536
|
+
return this.options.store.views ? this.options.store.views() : [];
|
|
25537
|
+
}
|
|
25538
|
+
/**
|
|
25539
|
+
* One view block's rows: a saved view (`viewId`) or an inline `definition`, with
|
|
25540
|
+
* `$self` conditions bound to the note open in this session.
|
|
25541
|
+
*/
|
|
25542
|
+
async viewEmbed(key, input) {
|
|
25543
|
+
if (!this.options.store.viewEmbed) throw new DinoxError("This editor has no saved views.", { code: "COMMAND_FAILED", recoverable: false });
|
|
25544
|
+
const viewId = str2(input.viewId, "viewId", { optional: true, max: 200 })?.trim() || void 0;
|
|
25545
|
+
const hasDefinition = input.definition !== void 0 && input.definition !== null;
|
|
25546
|
+
if (!viewId && !hasDefinition) throw usage2("Pass viewId or definition");
|
|
25547
|
+
if (viewId && hasDefinition) throw usage2("Pass only one of viewId and definition");
|
|
25548
|
+
const rawLimit = Number(input.limit);
|
|
25549
|
+
const limit = Number.isFinite(rawLimit) && rawLimit >= 1 ? Math.min(EDITOR_VIEW_EMBED_MAX_LIMIT, Math.floor(rawLimit)) : EDITOR_VIEW_EMBED_DEFAULT_LIMIT;
|
|
25550
|
+
const noteId = typeof key === "string" ? this.sessions.get(key)?.noteId ?? void 0 : void 0;
|
|
25551
|
+
return this.options.store.viewEmbed({
|
|
25552
|
+
...noteId ? { noteId } : {},
|
|
25553
|
+
...viewId ? { viewId } : { definition: input.definition },
|
|
25554
|
+
limit,
|
|
25555
|
+
timeZone: this.options.timeZone ?? defaultTimeZone()
|
|
25556
|
+
});
|
|
25557
|
+
}
|
|
24641
25558
|
async search(input) {
|
|
24642
25559
|
const query = str2(input.query ?? "", "query", { max: 500 });
|
|
24643
25560
|
const limit = Math.max(1, Math.min(20, Number(input.limit) || 10));
|
|
@@ -25287,6 +26204,13 @@ var EditorService = class {
|
|
|
25287
26204
|
await this.options.persistence.save(sessions).catch((error) => this.options.log?.("persist failed", { error: String(error) }));
|
|
25288
26205
|
}
|
|
25289
26206
|
};
|
|
26207
|
+
function defaultTimeZone() {
|
|
26208
|
+
try {
|
|
26209
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
|
|
26210
|
+
} catch {
|
|
26211
|
+
return void 0;
|
|
26212
|
+
}
|
|
26213
|
+
}
|
|
25290
26214
|
function describeMetaChange(changed, before, after) {
|
|
25291
26215
|
const parts = [];
|
|
25292
26216
|
if (changed.includes("title")) parts.push({ key: "\u628A\u6A19\u984C\u6539\u6210\u300C{title}\u300D", params: { title: after.title || "\u672A\u547D\u540D\u7B46\u8A18" } });
|
|
@@ -25330,6 +26254,24 @@ async function createDaemonEditorService(db, options2) {
|
|
|
25330
26254
|
append: (items, target) => uploaded(appendTodoTasks(db, { items, userId: options2.userId, ...target })),
|
|
25331
26255
|
restore: (entries) => uploaded(restoreTodoTasks(db, entries))
|
|
25332
26256
|
},
|
|
26257
|
+
...options2.authorization ? {
|
|
26258
|
+
upload: async ({ name, mediaType, data, maxBytes }) => {
|
|
26259
|
+
const sent = await uploadToOfficialStorage(
|
|
26260
|
+
{ db, userId: options2.userId, authorization: options2.authorization },
|
|
26261
|
+
{ kind: "data", data, mediaType, name },
|
|
26262
|
+
{ maxBytes, extraData: { source: "cli-editor" } }
|
|
26263
|
+
);
|
|
26264
|
+
void waitForUploadQueueEmpty(db, 3e4).catch(() => void 0);
|
|
26265
|
+
return {
|
|
26266
|
+
resourceId: sent.resourceId,
|
|
26267
|
+
storageKey: sent.storageKey,
|
|
26268
|
+
url: sent.url,
|
|
26269
|
+
name: sent.name,
|
|
26270
|
+
mediaType: sent.mediaType,
|
|
26271
|
+
sizeBytes: sent.sizeBytes
|
|
26272
|
+
};
|
|
26273
|
+
}
|
|
26274
|
+
} : {},
|
|
25333
26275
|
log: options2.log
|
|
25334
26276
|
});
|
|
25335
26277
|
await service.restore();
|
|
@@ -25346,6 +26288,7 @@ var EDITOR_METHODS = /* @__PURE__ */ new Set([
|
|
|
25346
26288
|
"editor.read",
|
|
25347
26289
|
"editor.suggest",
|
|
25348
26290
|
"editor.search",
|
|
26291
|
+
"editor.excerpt",
|
|
25349
26292
|
"editor.sync",
|
|
25350
26293
|
"editor.save",
|
|
25351
26294
|
"editor.resolve",
|
|
@@ -25359,7 +26302,11 @@ var EDITOR_METHODS = /* @__PURE__ */ new Set([
|
|
|
25359
26302
|
"editor.todoAppend",
|
|
25360
26303
|
"editor.todoRestore",
|
|
25361
26304
|
"editor.todoSuggest",
|
|
25362
|
-
"editor.todoSuggestion"
|
|
26305
|
+
"editor.todoSuggestion",
|
|
26306
|
+
"editor.upload",
|
|
26307
|
+
"editor.linkPreview",
|
|
26308
|
+
"editor.views",
|
|
26309
|
+
"editor.viewEmbed"
|
|
25363
26310
|
]);
|
|
25364
26311
|
async function handleEditorRequest(service, method, params, signal) {
|
|
25365
26312
|
if (!service) {
|
|
@@ -25378,6 +26325,8 @@ async function handleEditorRequest(service, method, params, signal) {
|
|
|
25378
26325
|
return service.suggest(session, input);
|
|
25379
26326
|
case "editor.search":
|
|
25380
26327
|
return service.search(input);
|
|
26328
|
+
case "editor.excerpt":
|
|
26329
|
+
return service.excerpt(input);
|
|
25381
26330
|
case "editor.sync":
|
|
25382
26331
|
return service.sync(session, input, signal);
|
|
25383
26332
|
case "editor.save":
|
|
@@ -25406,6 +26355,14 @@ async function handleEditorRequest(service, method, params, signal) {
|
|
|
25406
26355
|
return service.todoSuggest(session, input);
|
|
25407
26356
|
case "editor.todoSuggestion":
|
|
25408
26357
|
return service.todoSuggestion(session, input);
|
|
26358
|
+
case "editor.upload":
|
|
26359
|
+
return service.upload(input);
|
|
26360
|
+
case "editor.linkPreview":
|
|
26361
|
+
return service.linkPreview(input);
|
|
26362
|
+
case "editor.views":
|
|
26363
|
+
return service.views();
|
|
26364
|
+
case "editor.viewEmbed":
|
|
26365
|
+
return service.viewEmbed(session, input);
|
|
25409
26366
|
default:
|
|
25410
26367
|
throw new DinoxError(`Unknown editor method: ${method}`, { code: "USAGE_ERROR" });
|
|
25411
26368
|
}
|
|
@@ -25413,6 +26370,8 @@ async function handleEditorRequest(service, method, params, signal) {
|
|
|
25413
26370
|
|
|
25414
26371
|
// src/daemon/server.ts
|
|
25415
26372
|
var MAX_DAEMON_REQUEST_BYTES = 1 * 1024 * 1024;
|
|
26373
|
+
var MAX_DAEMON_UPLOAD_REQUEST_BYTES = 511 * 1024 * 1024;
|
|
26374
|
+
var LARGE_BODY_METHODS = /* @__PURE__ */ new Set(["editor.upload"]);
|
|
25416
26375
|
var DAEMON_HEALTH_CHECK_INTERVAL_MS = 6e4;
|
|
25417
26376
|
var DAEMON_STUCK_SYNC_RESTART_MS = 15 * 6e4;
|
|
25418
26377
|
var DAEMON_INTENT_WAIT_CHUNK_MS = 3e4;
|
|
@@ -25422,13 +26381,17 @@ function daemonSupervisor() {
|
|
|
25422
26381
|
return value === "launchd" || value === "systemd" || value === "schtasks" ? value : null;
|
|
25423
26382
|
}
|
|
25424
26383
|
var DAEMON_PROCESS_VERSION = getPackageVersion();
|
|
25425
|
-
|
|
26384
|
+
function requestBodyLimit(req) {
|
|
26385
|
+
const declared = req.headers[DAEMON_METHOD_HEADER];
|
|
26386
|
+
return typeof declared === "string" && LARGE_BODY_METHODS.has(declared) ? MAX_DAEMON_UPLOAD_REQUEST_BYTES : MAX_DAEMON_REQUEST_BYTES;
|
|
26387
|
+
}
|
|
26388
|
+
async function readJsonBody(req, maxBytes = MAX_DAEMON_REQUEST_BYTES) {
|
|
25426
26389
|
return new Promise((resolve, reject) => {
|
|
25427
26390
|
const chunks = [];
|
|
25428
26391
|
let totalBytes = 0;
|
|
25429
26392
|
req.on("data", (chunk) => {
|
|
25430
26393
|
totalBytes += chunk.length;
|
|
25431
|
-
if (totalBytes >
|
|
26394
|
+
if (totalBytes > maxBytes) {
|
|
25432
26395
|
req.destroy(new Error("Request body too large"));
|
|
25433
26396
|
return;
|
|
25434
26397
|
}
|
|
@@ -25530,6 +26493,7 @@ var DaemonServer = class {
|
|
|
25530
26493
|
if (config.auth.userId) {
|
|
25531
26494
|
this.editor = await createDaemonEditorService(db, {
|
|
25532
26495
|
userId: config.auth.userId,
|
|
26496
|
+
...config.auth.authorization ? { authorization: config.auth.authorization } : {},
|
|
25533
26497
|
log: (message, details) => writeDaemonLogLine("dinox-editor", message, details)
|
|
25534
26498
|
}).catch((error) => {
|
|
25535
26499
|
writeDaemonLogLine("dinox-editor", "start failed", { error: String(error) });
|
|
@@ -25568,7 +26532,7 @@ var DaemonServer = class {
|
|
|
25568
26532
|
}
|
|
25569
26533
|
};
|
|
25570
26534
|
const execute = async () => {
|
|
25571
|
-
const { runCli } = await import("./runCli-
|
|
26535
|
+
const { runCli } = await import("./runCli-GKTCIDBF.js");
|
|
25572
26536
|
const exitCode = await requestContext.run(context, () => runCli(input.argv));
|
|
25573
26537
|
return { stdout: context.stdout.join(""), stderr: context.stderr.join(""), exitCode };
|
|
25574
26538
|
};
|
|
@@ -25693,7 +26657,11 @@ var DaemonServer = class {
|
|
|
25693
26657
|
return;
|
|
25694
26658
|
}
|
|
25695
26659
|
try {
|
|
25696
|
-
const
|
|
26660
|
+
const bodyLimit = requestBodyLimit(req);
|
|
26661
|
+
const daemonReq = await readJsonBody(req, bodyLimit);
|
|
26662
|
+
if (bodyLimit > MAX_DAEMON_REQUEST_BYTES && !LARGE_BODY_METHODS.has(daemonReq?.method)) {
|
|
26663
|
+
throw new Error("Request body too large for its method");
|
|
26664
|
+
}
|
|
25697
26665
|
if (isStreamedCommand(daemonReq)) {
|
|
25698
26666
|
res.writeHead(200, { "Content-Type": "application/x-ndjson" });
|
|
25699
26667
|
const daemonRes2 = await this.handleRequest(daemonReq, (progress) => {
|
|
@@ -26933,7 +27901,6 @@ export {
|
|
|
26933
27901
|
normalizeDatePropertyValue,
|
|
26934
27902
|
coercePropertyValue,
|
|
26935
27903
|
normalizePropertyDefConfig,
|
|
26936
|
-
mapPropertyDef,
|
|
26937
27904
|
mapNoteTemplateRow,
|
|
26938
27905
|
getNoteContext,
|
|
26939
27906
|
getNotePreview,
|
|
@@ -27003,24 +27970,9 @@ export {
|
|
|
27003
27970
|
readNoteContentForPatch,
|
|
27004
27971
|
planNoteContentPatch,
|
|
27005
27972
|
applyNoteContentPatch,
|
|
27006
|
-
SAVED_VIEW_SYSTEM_FIELDS,
|
|
27007
|
-
SAVED_VIEW_PRIMARY_RESOURCE_TYPES,
|
|
27008
|
-
isSavedViewDisplayOnlyField,
|
|
27009
|
-
getSavedViewFilterOperatorsForField,
|
|
27010
|
-
canSortSavedViewField,
|
|
27011
|
-
savedViewFilterSchema,
|
|
27012
27973
|
SAVED_VIEW_LAYOUTS,
|
|
27013
|
-
savedViewConfigSchema,
|
|
27014
|
-
createDefaultSavedViewFilter,
|
|
27015
|
-
createDefaultSavedViewConfig,
|
|
27016
|
-
parseSavedViewZettelBoxDetails,
|
|
27017
|
-
resolveSavedViewQueryScope,
|
|
27018
|
-
fetchSavedViewScopedPage,
|
|
27019
|
-
countSavedViewScopedRows,
|
|
27020
|
-
toDinoxError,
|
|
27021
27974
|
runDomainCommand,
|
|
27022
27975
|
fetchDomainReadModel,
|
|
27023
|
-
withReadTransaction,
|
|
27024
27976
|
withNestedWriteTransaction,
|
|
27025
27977
|
previewInRolledBackTransaction,
|
|
27026
27978
|
listProperties,
|
|
@@ -27039,7 +27991,21 @@ export {
|
|
|
27039
27991
|
fillEmptyNoteProperties,
|
|
27040
27992
|
updateNotePropertySlots2 as updateNotePropertySlots,
|
|
27041
27993
|
reorderNotePropertySlots2 as reorderNotePropertySlots,
|
|
27042
|
-
|
|
27994
|
+
listSavedViewFields,
|
|
27995
|
+
validateSavedViewFilter,
|
|
27996
|
+
validateSavedViewConfig,
|
|
27997
|
+
listSavedViews,
|
|
27998
|
+
getSavedView,
|
|
27999
|
+
querySavedView,
|
|
28000
|
+
countSavedViewRows,
|
|
28001
|
+
getSavedViewAnalytics,
|
|
28002
|
+
getNoteDetailSections,
|
|
28003
|
+
createSavedView2 as createSavedView,
|
|
28004
|
+
updateSavedView2 as updateSavedView,
|
|
28005
|
+
deleteSavedView,
|
|
28006
|
+
previewCreateSavedView,
|
|
28007
|
+
previewUpdateSavedView,
|
|
28008
|
+
previewDeleteSavedView,
|
|
27043
28009
|
registerCommandGroup,
|
|
27044
28010
|
registerStandaloneCommand,
|
|
27045
28011
|
commandSchemasFromGroupDescriptor,
|