Initial import of LogDarioSeq baseline

Establishes version control for the personal Logseq DB fork before
starting the server-client architecture migration and domain features
described in docs/agent-guide and the approved implementation plan.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5 committed 2026-08-25 15:32:15 +02:00
commit 40631362b3
2016 files changed
+543898

No files matched your search

+1
View File
@@ -0,0 +1 @@
/.nbb/.cache
+75
View File
@@ -0,0 +1,75 @@
## Description
This is a collection of development related scripts, written as bash scripts, bb/babashka scripts and nbb scripts.
## Usage
### Babashka scripts
Most bb scripts live under `src/` and are defined as bb tasks. See [babashka tasks](../docs/dev-practices.md#babashka-tasks)
### Nbb scripts
Before running [nbb-logseq](https://github.com/logseq/nbb-logseq) scripts, be sure to have node >= 18.14 installed as well as a recent [babashka](https://github.com/babashka/babashka) for managing the dependencies in `nbb.edn`. Then `pnpm install` to install dependencies
#### Create graph scripts
These scripts generate custom database graphs written with nbb-logseq. If this is
your first time generating a DB graph, first try the
`dev:create` bb task in [db graph
tasks](../docs/dev-practices.md#db-graph-tasks) as it only requires writing EDN.
Creating graphs from the commandline using scripts and a concise EDN map is
possible thanks to nbb-logseq and the namespaces
[logseq.outliner.db-pipeline](deps/outliner/src/logseq/outliner/db_pipeline.cljs)
and [logseq.db.sqlite.build](deps/db/src/logseq/db/sqlite/build.cljs). For
example, the `create_graph_with_properties.cljs` script uses this ns to create a
graph with a variety of properties:
```
$ pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_properties.cljs woot
Generating 16 pages and 24 blocks ...
Created graph woot!
```
**NOTE**: To use this created graph, click on the three dots menu in the upper right corner and select `Import`. Then click on the `SQLite` import button and upload the generated graph.
This script creates a DB graph with blocks containing several property types for
both single and many cardinality. It also includes queries for most of these
properties. Read the docs in
[logseq.db.sqlite.build](deps/db/src/logseq/db/sqlite/build.cljs)
for specifics on the EDN map.
To create large graphs with varying size:
```
$ pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_large_sizes.cljs large
Building tx ...
Built 21000 tx, 1000 pages and 20000 blocks ...
Transacting chunk 1 of 21 starting with block: #:block{:name "page-0"}
...
Created graph large with 187810 datoms!
# To see options available
$ pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_large_sizes.cljs -h
Usage: $0 GRAPH-NAME [OPTIONS]
Options:
-h, --help Print help
-p, --pages 1000 Number of pages to create
-b, --blocks 20 Number of blocks to create
```
Another example is the `create_graph_with_schema_org.cljs` script which creates a graph
with the https://schema.org/ ontology with as many of the classes and properties as possible:
```
$ pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_schema_org.cljs schema
Skipping 67 superseded properties
Skipping 25 properties with unsupported data types
Renaming 1 properties due to page name conflicts
Generating 2268 pages with 900 classes and 1368 properties ...
Created graph schema!
```
#### Update graph scripts
For database graphs, it is recommended to use
`logseq.outliner.db-pipeline/add-listener!` when updating graphs. TODO
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
import { promises as fs } from "node:fs";
import { builtinModules } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "vite";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, "..");
const distDir = path.join(repoRoot, "dist");
const shadowEntry = path.join(repoRoot, "static", "db-worker-node.js");
const bundleEntry = path.join(distDir, "db-worker-node.js");
const manifestPath = path.join(distDir, "db-worker-node-assets.json");
const legacyNccOutDir = path.join(distDir, ".db-worker-node-ncc");
const builtinModuleSet = new Set([
...builtinModules,
...builtinModules.map((moduleName) => `node:${moduleName}`),
]);
const externalModuleSet = new Set([
"@zvec/zvec",
"keytar",
"ws",
]);
async function exists(targetPath) {
try {
await fs.access(targetPath);
return true;
} catch {
return false;
}
}
async function listFilesRecursive(baseDir, dir = baseDir) {
const entries = await fs.readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const absolute = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await listFilesRecursive(baseDir, absolute)));
} else if (entry.isFile()) {
files.push(path.relative(baseDir, absolute));
}
}
return files.sort();
}
async function removeIfExists(targetPath) {
if (await exists(targetPath)) {
await fs.rm(targetPath, { recursive: true, force: true });
}
}
async function cleanupPreviousBundle() {
// Remove the legacy ncc output directory if it still exists from older builds.
await removeIfExists(legacyNccOutDir);
await removeIfExists(bundleEntry);
if (await exists(manifestPath)) {
let manifest;
try {
manifest = JSON.parse(await fs.readFile(manifestPath, "utf8"));
} catch (error) {
throw new Error(`failed to read ${manifestPath}: ${error.message}`);
}
const assets = Array.isArray(manifest.assets) ? manifest.assets : [];
for (const relativePath of assets) {
if (typeof relativePath !== "string" || relativePath.length === 0) {
continue;
}
const assetPath = path.join(distDir, relativePath);
await removeIfExists(assetPath);
}
}
await removeIfExists(manifestPath);
}
async function main() {
if (!(await exists(shadowEntry))) {
throw new Error(`missing shadow entry: ${shadowEntry}`);
}
await cleanupPreviousBundle();
await fs.mkdir(distDir, { recursive: true });
const filesBefore = await listFilesRecursive(distDir);
await build({
configFile: false,
publicDir: false,
logLevel: "error",
build: {
codeSplitting: false,
minify: "terser",
target: "node22",
sourcemap: false,
write: true,
emptyOutDir: false,
outDir: distDir,
lib: {
entry: shadowEntry,
formats: ["cjs"],
fileName: () => "db-worker-node.js",
},
rollupOptions: {
external: (id) =>
id.endsWith(".node") ||
id.startsWith("node:") ||
builtinModuleSet.has(id) ||
externalModuleSet.has(id),
output: {
format: "cjs",
exports: "auto",
entryFileNames: "db-worker-node.js",
chunkFileNames: "db-worker-node.js",
},
},
},
});
if (!(await exists(bundleEntry))) {
throw new Error(`vite bundle missing output file: ${bundleEntry}`);
}
const bundleContents = await fs.readFile(bundleEntry, "utf8");
if (bundleContents.includes("node_modules/.pnpm/keytar")) {
throw new Error(
"vite bundle contains a pnpm keytar native path; keytar must stay external"
);
}
if (bundleContents.includes("ws does not work in the browser")) {
throw new Error(
"vite bundle contains the ws browser stub; ws must stay external"
);
}
let filesAfter = await listFilesRecursive(distDir);
if (filesAfter.includes("index.html") && !filesBefore.includes("index.html")) {
await removeIfExists(path.join(distDir, "index.html"));
filesAfter = await listFilesRecursive(distDir);
}
const extraJsFiles = filesAfter.filter(
(relativePath) =>
relativePath.endsWith(".js") &&
relativePath !== "db-worker-node.js" &&
!filesBefore.includes(relativePath)
);
if (extraJsFiles.length > 0) {
throw new Error(
`vite bundle produced unexpected JS outputs: ${extraJsFiles.join(", ")}`
);
}
await fs.writeFile(
manifestPath,
`${JSON.stringify(
{
assets: [],
},
null,
2
)}\n`,
"utf8"
);
}
main().catch((error) => {
console.error(`[db-worker-node-bundle] ${error.message}`);
process.exit(1);
});
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
set -ex
unset LOGSEQ_APP_SERVER_URL
export ENABLE_FILE_SYNC_PRODUCTION=true
# pnpm clean
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 pnpm install --frozen-lockfile
rm -rv public/static || true
rm -rv ios/App/App/public || true
pnpm release-app
rsync -avz --exclude node_modules --exclude '*.js.map' --exclude android ./static/ ./public/static/
pnpm exec cap sync ios
pnpm exec cap open ios
echo "step 1(Xcode). Product > Archive (device should be Any iOS Device)"
echo "step 2(Archive). Distribute App"
echo " - App Store Connect"
echo " - Upload"
echo " - (Default config, all checked)"
echo " - Upload"
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
set -e
if uname -s | grep -q Darwin; then
SED=gsed
else
SED=sed
fi
NOW="$(date +'%B %d, %Y')"
RED="\033[1;31m"
GREEN="\033[0;32m"
YELLOW="\033[1;33m"
BLUE="\033[1;34m"
PURPLE="\033[1;35m"
CYAN="\033[1;36m"
WHITE="\033[1;37m"
RESET="\033[0m"
QUESTION_FLAG="${GREEN}?"
WARNING_FLAG="${YELLOW}!"
NOTICE_FLAG="${CYAN}❯"
LATEST_HASH=`git log --pretty=format:'%h' -n 1`
BASE_VERSION=$(cat resources/package.json | jq '.version' | tr -d '"')
VERSION_CODE=$(cat android/app/build.gradle | grep -oh 'versionCode [[:digit:]]*' | awk '{print $2}')
BASE_LIST=(`echo $BASE_VERSION | tr '.' ' '`)
V_MAJOR=${BASE_LIST[0]}
V_MINOR=${BASE_LIST[1]}
V_PATCH=${BASE_LIST[2]}
echo -e "${NOTICE_FLAG} Current version: ${WHITE}$BASE_VERSION"
echo -e "${NOTICE_FLAG} Latest commit hash: ${WHITE}$LATEST_HASH"
echo -e "${NOTICE_FLAG} Current versionCode(Android): ${WHITE}$VERSION_CODE"
# V_MINOR=$((V_MINOR + 1))
# V_PATCH=0
V_PATCH=$((V_PATCH + 1))
SUGGESTED_VERSION="$V_MAJOR.$V_MINOR.$V_PATCH"
echo -e "${QUESTION_FLAG} ${CYAN}Enter a version number [${WHITE}$SUGGESTED_VERSION${CYAN}]: "
read INPUT_STRING
if [ "$INPUT_STRING" = "" ]; then
INPUT_STRING=$SUGGESTED_VERSION
fi
NEW_VERSION_CODE=$(($VERSION_CODE + 1))
echo -e "${NOTICE_FLAG} Will set new version to be ${WHITE}$INPUT_STRING"
echo -e "${NOTICE_FLAG} Will set new versionCode to be ${WHITE}$NEW_VERSION_CODE"
NEW_VERSION=$INPUT_STRING
$SED -i 's/defonce version ".*"/defonce version "'${NEW_VERSION}'"/g' src/main/frontend/version.cljs
$SED -i 's/"version": ".*"/"version": "'${NEW_VERSION}'"/g' resources/package.json
$SED -i 's/versionName ".*"/versionName "'${NEW_VERSION}'"/g' android/app/build.gradle
$SED -i 's/versionCode .*/versionCode '${NEW_VERSION_CODE}'/g' android/app/build.gradle
$SED -i 's/MARKETING_VERSION = .*;/MARKETING_VERSION = '${NEW_VERSION}';/g' ios/App/App.xcodeproj/project.pbxproj
git --no-pager diff -U0
echo -e "${NOTICE_FLAG} Finished."
+31
View File
@@ -0,0 +1,31 @@
import path from 'node:path'
import { findUnsupportedIOSFontAssets } from './lib/check-ios-web-fonts.mjs'
const repoRoot = path.resolve(import.meta.dirname, '..')
const assetRoots = [
path.join(repoRoot, 'static', 'mobile'),
path.join(repoRoot, 'ios', 'App', 'App', 'public'),
]
const result = findUnsupportedIOSFontAssets({ repoRoot, assetRoots })
if (result.roots.length === 0) {
throw new Error('No iOS web assets found. Run pnpm release-mobile or pnpm sync-ios-release first.')
}
if (result.fontFiles.length > 0) {
console.error('iOS web assets must not include .woff or .woff2 font files:')
for (const filePath of result.fontFiles) {
console.error(`- ${filePath}`)
}
process.exit(1)
}
if (result.cssFiles.length > 0) {
console.error('iOS web CSS must not reference .woff or .woff2 font files:')
for (const filePath of result.cssFiles) {
console.error(`- ${filePath}`)
}
process.exit(1)
}
File diff suppressed because it is too large. Load diff
+683
View File
@@ -0,0 +1,683 @@
import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import {
bootstrapStressPageNames,
blockByUuidQuery,
blockExistsFromQueryResult,
classifyHttpResult,
classifyCliResult,
clientRuntimeOptions,
checksumDiagnosticsMatch,
cliCommand,
graphValidateArgs,
isIdleSyncStatus,
isSettledSyncStatus,
mutableStressPageNames,
offlineTodayJournalClientCount,
operationNames,
operationWeights,
parseArgs,
stressPageNames,
stressConfigText,
stressReferenceViewOrder,
syncDownloadArgs,
syncEnsureKeysArgs,
syncNeedsEnsureKeys,
syncServerStartArgs,
syncStatusUninitialized,
syncUploadArgs,
staleIdsFromContext,
todayJournalPageName,
uniqueOperationPageTitle,
} from "./cli-concurrent-edit-stress.mjs";
test("classifies stale block conflicts as race outcomes", () => {
const parsed = {
status: "error",
error: {
code: "source-not-found",
message: "source block uuid not found",
},
};
assert.deepEqual(classifyCliResult({ code: 1 }, parsed, { id: 1911 }), {
ok: false,
level: "info",
outcome: "race-conflict",
expectedRace: true,
});
});
test("classifies stale task and recycled page conflicts as race outcomes", () => {
for (const code of ["upsert-id-not-found", "recycled-page", "page-not-found"]) {
assert.equal(
classifyCliResult(
{ code: 1 },
{
status: "error",
error: { code, message: "race" },
},
{ id: 42 },
).outcome,
"race-conflict",
);
}
});
test("classifies concurrent volatile property delete as a race outcome", () => {
for (const code of ["property-not-found", "ambiguous-property-name"]) {
assert.equal(
classifyCliResult(
{ code: 1 },
{
status: "error",
error: { code, message: "volatile property race" },
},
{ op: "property-delete-recreate", phase: "delete" },
).outcome,
"race-conflict",
);
}
});
test("classifies concurrent volatile tag delete as a race outcome", () => {
assert.equal(
classifyCliResult(
{ code: 1 },
{
status: "error",
error: { code: "tag-not-found", message: "tag not found" },
},
{ op: "tag-delete-recreate", phase: "delete" },
).outcome,
"race-conflict",
);
});
test("classifies stale raw outliner block property failures as race outcomes", () => {
assert.equal(
classifyHttpResult(
{ ok: false, status: 500 },
{
error: {
code: "exception",
message: "Set block property failed: block or property doesn't exist",
},
},
{ id: 525, op: "http-set-block-property" },
).outcome,
"race-conflict",
);
});
test("classifies stale raw view targets as race outcomes", () => {
for (const message of [
'Nothing found for entity id (:block/uuid #uuid "b5cf1ff2-1403-4eed-9449-d326b1e9efad")',
'Nothing found for entity id [:block/uuid #uuid "b5cf1ff2-1403-4eed-9449-d326b1e9efad"]',
]) {
assert.equal(
classifyHttpResult(
{ ok: false, status: 500 },
{
error: {
code: "exception",
message,
},
},
{ id: 231, op: "http-create-unlinked-references-view" },
).outcome,
"race-conflict",
);
}
});
test("builds block uuid lookup queries for raw view target checks", () => {
assert.equal(
blockByUuidQuery("b5cf1ff2-1403-4eed-9449-d326b1e9efad"),
'[:find ?b . :where [?b :block/uuid #uuid "b5cf1ff2-1403-4eed-9449-d326b1e9efad"]]',
);
});
test("detects existing blocks from uuid lookup query results", () => {
assert.equal(blockExistsFromQueryResult({ parsed: { data: { result: 231 } } }), true);
assert.equal(blockExistsFromQueryResult({ parsed: { data: { result: null } } }), false);
});
test("classifies required outliner no-op results as failures", () => {
assert.deepEqual(
classifyHttpResult(
{ ok: true, status: 200 },
{ result: null },
{ op: "http-recycle-delete-page", phase: "permanent-delete", requireTruthyResult: true },
),
{
ok: false,
level: "error",
outcome: "no-op",
expectedRace: false,
},
);
});
test("keeps created-id resolution failures visible as errors", () => {
const parsed = {
status: "error",
error: {
code: "add-id-resolution-failed",
message: "unable to resolve created ids",
},
};
assert.deepEqual(classifyCliResult({ code: 1 }, parsed, { parentId: 710 }), {
ok: false,
level: "error",
outcome: "failed",
expectedRace: false,
});
});
test("extracts stale ids from operation context", () => {
assert.deepEqual(staleIdsFromContext({ id: 1, targetId: 2, parentId: 3, ids: [4, "x", 5] }), [1, 2, 3, 4, 5]);
});
test("builds local db-sync server start command from sync base", () => {
const args = syncServerStartArgs({
syncBase: "http://127.0.0.1:19090",
authPath: "/tmp/auth.json",
syncServerPidFile: "/tmp/stress/server.pid",
syncServerLogFile: "/tmp/stress/server.log",
syncServerDataDir: "/tmp/stress/server-data",
});
assert.deepEqual(args, [
"cli-e2e/scripts/db_sync_server.py",
"start",
"--repo-root",
process.cwd(),
"--pid-file",
"/tmp/stress/server.pid",
"--log-file",
"/tmp/stress/server.log",
"--data-dir",
"/tmp/stress/server-data",
"--host",
"127.0.0.1",
"--port",
"19090",
"--startup-timeout-s",
"25",
"--auth-path",
"/tmp/auth.json",
]);
});
test("parses isolated local db-sync server paths", () => {
const opts = parseArgs([
"--sync-server-pid-file",
"tmp/stress/server.pid",
"--sync-server-log-file",
"tmp/stress/server.log",
"--sync-server-data-dir",
"tmp/stress/server-data",
]);
assert.equal(opts.syncServerPidFile.endsWith("/tmp/stress/server.pid"), true);
assert.equal(opts.syncServerLogFile.endsWith("/tmp/stress/server.log"), true);
assert.equal(opts.syncServerDataDir.endsWith("/tmp/stress/server-data"), true);
});
test("stress config includes runtime auth to avoid refresh during sync start", () => {
const dir = mkdtempSync(join(tmpdir(), "logseq-stress-auth-"));
const authPath = join(dir, "auth.json");
writeFileSync(
authPath,
JSON.stringify({
"refresh-token": "refresh-1",
"id-token": "id-1",
"access-token": "access-1",
}),
);
const text = stressConfigText({
httpBase: "http://127.0.0.1:18080",
wsUrl: "ws://127.0.0.1:18080/sync/%s",
authPath,
});
assert.match(text, /:auth-path "/);
assert.match(text, /:refresh-token "refresh-1"/);
assert.match(text, /:id-token "id-1"/);
assert.match(text, /:access-token "access-1"/);
});
test("builds sync upload initialization command with e2ee password", () => {
assert.equal(syncNeedsEnsureKeys({ graphE2ee: true }), true);
assert.deepEqual(syncEnsureKeysArgs({ e2eePassword: "11111" }), [
"sync",
"ensure-keys",
"--upload-keys",
"--e2ee-password",
"11111",
]);
assert.deepEqual(syncUploadArgs({ graph: "pi-memory", e2eePassword: "11111" }), [
"sync",
"upload",
"--graph",
"pi-memory",
"--e2ee-password",
"11111",
]);
assert.equal(syncNeedsEnsureKeys({ graphE2ee: false }), false);
assert.deepEqual(syncUploadArgs({ graph: "pi-memory", e2eePassword: "11111", graphE2ee: false }), [
"sync",
"upload",
"--graph",
"pi-memory",
]);
});
test("builds final graph validation command", () => {
assert.deepEqual(graphValidateArgs({ graph: "pi-memory" }), ["graph", "validate", "--graph", "pi-memory"]);
});
test("builds isolated runtime options for additional sync clients", () => {
const seed = clientRuntimeOptions(
{
graph: "pi-memory",
config: "/tmp/stress/cli.edn",
logFile: "/tmp/stress/events.jsonl",
rootDir: "/tmp/stress/root",
homeDir: "/tmp/stress/home",
timeoutMs: 60000,
},
0,
);
const replica = clientRuntimeOptions(seed, 1);
assert.equal(seed.graph, "pi-memory");
assert.equal(replica.graph, "pi-memory");
assert.equal(seed.config, "/tmp/stress/cli.edn");
assert.equal(replica.config, "/tmp/stress/clients/client-2/cli.edn");
assert.equal(seed.env.LOGSEQ_CLI_ROOT_DIR, "/tmp/stress/root");
assert.equal(replica.env.LOGSEQ_CLI_ROOT_DIR, "/tmp/stress/clients/client-2/root");
assert.equal(replica.env.HOME, "/tmp/stress/clients/client-2/home");
});
test("parses isolated root dir for the seed client", () => {
const opts = parseArgs(["--root-dir", "/tmp/stress/root"]);
assert.equal(opts.rootDir, "/tmp/stress/root");
});
test("runs staged JavaScript CLI bundles through node", () => {
assert.deepEqual(cliCommand("/tmp/logseq-cli.js"), {
command: process.execPath,
args: ["/tmp/logseq-cli.js"],
});
assert.deepEqual(cliCommand("/usr/local/bin/logseq"), {
command: "/usr/local/bin/logseq",
args: [],
});
});
test("builds sync download command for replica clients", () => {
assert.deepEqual(syncDownloadArgs({ graph: "pi-memory", graphE2ee: false }), [
"sync",
"download",
"--graph",
"pi-memory",
]);
assert.deepEqual(syncDownloadArgs({ graph: "pi-memory", graphE2ee: true, e2eePassword: "11111" }), [
"sync",
"download",
"--graph",
"pi-memory",
"--e2ee-password",
"11111",
]);
});
test("detects final sync convergence from status checks", () => {
assert.equal(
isSettledSyncStatus({
ok: true,
parsed: {
data: {
"pending-local": 0,
"pending-server": 0,
"local-checksum": "abc",
"remote-checksum": "abc",
},
},
}),
true,
);
assert.equal(
isSettledSyncStatus({
ok: true,
parsed: {
data: {
"pending-local": 1,
"pending-server": 0,
"local-checksum": "abc",
"remote-checksum": "abc",
},
},
}),
false,
);
assert.equal(
isSettledSyncStatus({
ok: true,
parsed: {
data: {
"pending-local": 0,
"pending-server": 0,
"local-checksum": "abc",
"remote-checksum": "def",
},
},
}),
false,
);
});
test("detects idle sync status separately from cached checksums", () => {
assert.equal(
isIdleSyncStatus({
ok: true,
parsed: {
data: {
"last-error": null,
"pending-local": 0,
"pending-server": 0,
"local-tx": 40,
"remote-tx": 40,
"local-checksum": "old",
"remote-checksum": "new",
},
},
}),
true,
);
assert.equal(
isIdleSyncStatus({
ok: true,
parsed: {
data: {
"last-error": null,
"pending-local": 0,
"pending-server": 1,
"local-tx": 40,
"remote-tx": 40,
},
},
}),
false,
);
});
test("matches recomputed checksum diagnostics against remote checksum", () => {
assert.equal(
checksumDiagnosticsMatch(
new Map([
["recomputed-checksum", "abc"],
["remote-checksum", "abc"],
]),
),
true,
);
assert.equal(
checksumDiagnosticsMatch(
new Map([
["recomputed-checksum", "abc"],
["remote-checksum", "def"],
]),
),
false,
);
});
test("does not re-upload when linked graph has no remote tx before websocket start", () => {
assert.equal(
syncStatusUninitialized({
ok: true,
parsed: {
data: {
"graph-id": "ea64137c-e829-49fb-98de-dc83b745377b",
"local-tx": 55,
"remote-tx": null,
},
},
}),
false,
);
assert.equal(
syncStatusUninitialized({
ok: true,
parsed: {
data: {
"graph-id": null,
"local-tx": 55,
"remote-tx": null,
},
},
}),
true,
);
});
test("builds a multi-page stress surface with journal pages", () => {
assert.deepEqual(
stressPageNames({
page: "CLI Concurrent Stress",
extraPages: 2,
journalPages: 2,
journalStart: "2026-07-01",
}),
[
"CLI Concurrent Stress",
"CLI Concurrent Stress page 2",
"CLI Concurrent Stress page 3",
"Jul 1st, 2026",
"Jul 2nd, 2026",
],
);
});
test("mutable stress pages exclude journal pages", () => {
assert.deepEqual(
mutableStressPageNames({
page: "CLI Concurrent Stress",
extraPages: 2,
journalPages: 2,
journalStart: "2026-07-01",
}),
["CLI Concurrent Stress page 2", "CLI Concurrent Stress page 3"],
);
});
test("bootstrap stress pages exclude auto-created journal pages", () => {
assert.deepEqual(
bootstrapStressPageNames({
page: "CLI Concurrent Stress",
extraPages: 2,
journalPages: 2,
journalStart: "2026-07-01",
}),
["CLI Concurrent Stress", "CLI Concurrent Stress page 2", "CLI Concurrent Stress page 3"],
);
});
test("today journal page name uses the local calendar date", () => {
assert.equal(todayJournalPageName({}, new Date("2026-07-01T16:30:00+08:00")), "Jul 1st, 2026");
assert.equal(todayJournalPageName({ todayDate: "2026-07-02" }), "Jul 2nd, 2026");
});
test("reference view stress orders stay in generated fractional-index form", () => {
assert.equal(stressReferenceViewOrder({ seq: 0 }, 0), "a0");
assert.equal(stressReferenceViewOrder({ seq: 30 }, 0), "ay");
assert.equal(stressReferenceViewOrder({ seq: 31 }, 0), "b00");
assert.equal(stressReferenceViewOrder({ seq: 61 }, 1), "b0z");
assert.equal(stressReferenceViewOrder({ seq: 62 }, 0), "b10");
for (let seq = 0; seq < 1000; seq += 1) {
assert.match(stressReferenceViewOrder({ seq }, 0), /^(a[0-9A-Za-z]|b[0-9A-Za-z][0-9A-Za-z])$/);
assert.match(stressReferenceViewOrder({ seq }, 1), /^(a[0-9A-Za-z]|b[0-9A-Za-z][0-9A-Za-z])$/);
assert.notEqual(stressReferenceViewOrder({ seq }, 0), stressReferenceViewOrder({ seq }, 1));
}
});
test("raw page delete/restore uses unique operation-owned page titles", () => {
const state = { runId: "stress-1" };
const first = uniqueOperationPageTitle("CLI HTTP Delete Restore", state, { workerId: 3, seq: 305 });
const second = uniqueOperationPageTitle("CLI HTTP Delete Restore", state, { workerId: 3, seq: 305 });
const third = uniqueOperationPageTitle("CLI HTTP Delete Restore", state, { workerId: 4, seq: 305 });
assert.match(first, /^CLI HTTP Delete Restore stress-1 worker-3 seq-305 /);
assert.notEqual(first, second);
assert.notEqual(first, third);
});
test("operation set covers broad outliner and metadata mutations", () => {
const names = operationNames({ sync: true, offline: true });
for (const name of [
"create-root",
"create-child",
"create-tree",
"update",
"move-child",
"move-page",
"move-sibling",
"block-tags-add",
"block-tags-remove",
"block-properties-add",
"block-properties-remove",
"task-create",
"task-update",
"page-upsert",
"page-properties-add",
"page-properties-remove",
"page-delete-restore",
"tag-upsert",
"tag-delete-recreate",
"property-upsert",
"property-delete-recreate",
"http-insert-blocks",
"http-delete-blocks",
"http-move-blocks",
"http-save-block",
"http-move-up-down",
"http-indent-outdent",
"http-apply-template",
"http-create-page",
"http-rename-page",
"http-delete-restore-page",
"http-recycle-delete-page",
"http-upsert-property",
"http-set-block-property",
"http-remove-block-property",
"http-batch-set-property",
"http-batch-remove-property",
"http-batch-delete-property-value",
"http-create-property-history",
"http-create-linked-references-view",
"http-create-unlinked-references-view",
"http-toggle-reaction",
"http-delete-view-target-with-related-entities",
"http-insert-undo-redo",
"delete-single",
"delete-batch",
"delete-update-race",
"offline-window",
"offline-today-journal-race",
]) {
assert.equal(names.includes(name), true, `${name} should be in the operation set`);
}
});
test("offline operation is available only when sync offline simulation is enabled", () => {
assert.equal(operationNames({ sync: true, offline: true }).includes("offline-window"), true);
assert.equal(operationNames({ sync: true, offline: false }).includes("offline-window"), false);
assert.equal(operationNames({ sync: false, offline: true }).includes("offline-window"), false);
assert.equal(operationNames({ sync: true, offline: true }).includes("offline-today-journal-race"), true);
assert.equal(operationNames({ sync: true, offline: false }).includes("offline-today-journal-race"), false);
assert.equal(operationNames({ sync: false, offline: true }).includes("offline-today-journal-race"), false);
assert.ok(
new Map(operationWeights({ sync: true, offline: true })).get("offline-today-journal-race") >= 8,
"offline today journal race should run often enough to catch page creation conflicts",
);
});
test("offline today journal race uses actual sync clients instead of worker concurrency", () => {
assert.equal(offlineTodayJournalClientCount({ clients: 3, concurrency: 8 }), 3);
assert.equal(offlineTodayJournalClientCount({ clients: 1, concurrency: 8 }), 2);
});
test("multi-client offline operations require sync, offline mode, and more than one client", () => {
assert.equal(operationNames({ sync: true, offline: true, clients: 3 }).includes("multi-client-offline-rebase"), true);
assert.equal(operationNames({ sync: true, offline: true, clients: 3 }).includes("multi-client-today-journal-race"), true);
assert.equal(operationNames({ sync: true, offline: true, clients: 1 }).includes("multi-client-offline-rebase"), false);
assert.equal(operationNames({ sync: true, offline: false, clients: 3 }).includes("multi-client-offline-rebase"), false);
assert.equal(operationNames({ sync: false, offline: true, clients: 3 }).includes("multi-client-offline-rebase"), false);
});
test("3k sync stress includes view-related history references and reactions", () => {
const maxOps = 3000;
const weights = new Map(operationWeights({ sync: true, offline: true, clients: 3 }));
const totalWeight = [...weights.values()].reduce((sum, weight) => sum + weight, 0);
for (const name of [
"http-create-property-history",
"http-create-linked-references-view",
"http-create-unlinked-references-view",
"http-toggle-reaction",
"http-delete-view-target-with-related-entities",
]) {
assert.ok(weights.has(name), `${name} should be in the sync stress operation set`);
assert.ok((weights.get(name) / totalWeight) * maxOps >= 10, `${name} should run often enough in a 3k-op stress run`);
}
});
test("critical outliner mutations dominate the stress distribution", () => {
const weights = new Map(operationWeights({ sync: true, offline: true }));
const criticalOps = [
"create-root",
"create-child",
"create-tree",
"move-child",
"move-page",
"move-sibling",
"http-insert-blocks",
"http-delete-blocks",
"http-move-blocks",
"http-move-up-down",
"http-indent-outdent",
"http-delete-restore-page",
"http-delete-view-target-with-related-entities",
"http-insert-undo-redo",
"delete-single",
"delete-batch",
"delete-update-race",
];
const totalWeight = [...weights.values()].reduce((sum, weight) => sum + weight, 0);
const criticalWeight = criticalOps.reduce((sum, name) => sum + (weights.get(name) || 0), 0);
assert.ok(criticalWeight / totalWeight >= 0.65, "insert/delete/move/undo-redo operations should dominate the run");
assert.ok((weights.get("http-insert-undo-redo") || 0) >= 8, "undo/redo should run often enough to catch regressions");
assert.ok((weights.get("http-insert-blocks") || 0) >= 8, "raw insert should run often enough to catch regressions");
assert.ok((weights.get("http-delete-blocks") || 0) >= 8, "raw delete should run often enough to catch regressions");
assert.ok((weights.get("http-move-blocks") || 0) >= 8, "raw move should run often enough to catch regressions");
});
+34
View File
@@ -0,0 +1,34 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const workflowPath = new URL("../.github/workflows/cli-sync-stress.yml", import.meta.url);
const nodeAdapterPath = new URL("../deps/db-sync/worker/dist/node-adapter.js", import.meta.url);
test("CLI sync stress workflow runs local sync/offline stress and validates the graph", () => {
const workflow = readFileSync(workflowPath, "utf8");
assert.match(workflow, /^name: CLI sync stress$/m);
assert.match(workflow, /pnpm --dir deps\/db-sync build:node-adapter/);
assert.match(workflow, /opam exec -- pnpm cli:release/);
assert.match(workflow, /pnpm db-worker-node:release:bundle/);
assert.match(workflow, /alg: "RS256"/);
assert.match(workflow, /kid: "cli-sync-stress"/);
assert.match(workflow, /generateKeyPairSync/);
assert.match(workflow, /createSign/);
assert.match(workflow, /http:\/\/127\.0\.0\.1:19091/);
assert.match(workflow, /http\.createServer/);
assert.match(workflow, /LOGSEQ_CLI_ROOT_DIR/);
assert.match(workflow, /HOME: \$\{\{ github\.workspace \}\}\/tmp\/cli-sync-stress\/home/);
assert.match(workflow, /node scripts\/cli-concurrent-edit-stress\.mjs/);
assert.match(workflow, /--sync/);
assert.match(workflow, /--offline/);
assert.match(workflow, /--no-e2ee/);
assert.match(workflow, /graph validate --graph "\$GRAPH" --output json/);
});
test("db-sync node adapter does not require Sentry during startup", () => {
const adapter = readFileSync(nodeAdapterPath, "utf8");
assert.doesNotMatch(adapter, /SHADOW_IMPORT\("shadow\.js\.shim\.module\$\$sentry\$node\.js"\)/);
});
+2
View File
@@ -0,0 +1,2 @@
;; Temporarily allow scripts dir to be used as gitlib for logseq.tasks.db-graph.*
{}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import path from "node:path";
export const appleSigningEnvKeys = [
"APPLE_ID",
"APPLE_APP_SPECIFIC_PASSWORD",
"APPLE_TEAM_ID",
"APPLE_API_KEY",
"APPLE_API_KEY_ID",
"APPLE_API_ISSUER",
"APPLE_KEYCHAIN",
"APPLE_KEYCHAIN_PROFILE",
];
export const codeSigningEnvKeys = [
"CSC_LINK",
"CSC_KEY_PASSWORD",
"CSC_NAME",
"WIN_CSC_LINK",
"WIN_CSC_KEY_PASSWORD",
];
const unsignedElectronBuilderBaseArgs = [
"exec",
"electron-builder",
"--config",
"electron-builder.yml",
"--publish",
"never",
"-c.mac.hardenedRuntime=false",
];
export const unsignedElectronBuilderArgs = (extraArgs = []) => [
...unsignedElectronBuilderBaseArgs,
...extraArgs,
];
export const unsignedBuildEnv = (baseEnv = process.env) => {
const env = {
...baseEnv,
CSC_IDENTITY_AUTO_DISCOVERY: "false",
};
for (const key of [...appleSigningEnvKeys, ...codeSigningEnvKeys]) {
delete env[key];
}
return env;
};
export const runUnsignedElectronBuilder = ({
cwd = process.cwd(),
env = process.env,
extraArgs = process.argv.slice(2),
} = {}) => {
const result = spawnSync("pnpm", unsignedElectronBuilderArgs(extraArgs), {
cwd,
env: unsignedBuildEnv(env),
shell: process.platform === "win32",
stdio: "inherit",
});
if (result.error) {
throw result.error;
}
return result.status ?? 1;
};
const isEntrypoint =
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isEntrypoint) {
process.exitCode = runUnsignedElectronBuilder();
}
+28
View File
@@ -0,0 +1,28 @@
// This script file simply outputs the version in the package.json.
// It is used as a helper by the continuous integration
const path = require('path')
const process = require('process')
const fs = require('fs')
const content = fs.readFileSync(
path.join(__dirname, '../src/main/frontend/version.cljs')
)
const pattern = /\(defonce version "(.*?)"\)/g
const match = pattern.exec(content)
let ver = '0.0.1'
if (match) {
ver = match[1]
} else {
console.error('Could not find version in version.cljs')
process.exit(1)
}
if (process.argv[2] === 'nightly' || process.argv[2] === '') {
const today = new Date()
console.log(
ver + '-alpha+nightly.' + today.toISOString().split('T')[0].replaceAll('-', '')
)
} else {
console.log(ver)
}
+352
View File
@@ -0,0 +1,352 @@
#!/bin/bash
# Logseq Linux Installer Script
# This script installs Logseq on Linux systems
# Usage: ./install-linux.sh [version]
set -e # Exit on any error
# Default values
DEFAULT_VERSION="latest"
INSTALL_DIR="/opt/logseq"
BIN_DIR="/usr/local/bin"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Helper functions
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
show_help() {
cat << HELP
Logseq Linux Installer
This script installs Logseq on Linux systems.
USAGE:
$0 [VERSION] [OPTIONS]
$0 uninstall
COMMANDS:
install (default) Install Logseq
uninstall Removes Logseq installation (keeps user data)
ARGUMENTS:
VERSION Version to install (e.g., "0.10.14"). Default: latest
OPTIONS:
--help, -h Show this help message
--prefix DIR Installation prefix (default: /opt/logseq)
--user Install for current user only
--no-desktop Skip desktop integration
--verbose, -v Verbose output
EXAMPLES:
$0 # Install latest version
$0 0.10.14 # Install specific version
$0 --user # Install for current user
$0 --prefix ~/.local/share/logseq # Custom install location
For more information, visit: https://github.com/logseq/logseq
HELP
}
uninstall() {
log_info "Searching for Logseq installations..."
local user_removed=false
local system_removed=false
# User installation paths
local -a user_paths=(
"$HOME/.local/share/logseq"
"$HOME/.local/bin/logseq"
"$HOME/.local/share/applications/logseq.desktop"
"$HOME/.local/share/icons/hicolor/512x512/apps/logseq.png"
)
# System installation paths
local -a system_paths=(
"/opt/logseq"
"/usr/local/bin/logseq"
"/usr/share/applications/logseq.desktop"
"/usr/share/icons/hicolor/512x512/apps/logseq.png"
)
# Remove user installation
log_info "Checking user installation..."
for path in "${user_paths[@]}"; do
if [[ -e "$path" ]] || [[ -L "$path" ]]; then
log_info "Removing: $path"
rm -rf "$path"
user_removed=true
fi
done
# Remove system installation
log_info "Checking system-wide installation..."
for path in "${system_paths[@]}"; do
if [[ -e "$path" ]] || [[ -L "$path" ]]; then
if [[ "$EUID" -ne 0 ]]; then
log_warn "System-wide installation found at $path, but root privileges required"
log_warn "Run with sudo to uninstall system-wide installation"
else
log_info "Removing: $path"
rm -rf "$path"
system_removed=true
fi
fi
done
# Update desktop databases
if [[ "$user_removed" == true ]] && [[ -d "$HOME/.local/share/applications" ]]; then
update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
fi
if [[ "$system_removed" == true ]]; then
update-desktop-database /usr/share/applications 2>/dev/null || true
fi
# Final status message
if [[ "$user_removed" == true ]] || [[ "$system_removed" == true ]]; then
log_info "Logseq has been uninstalled successfully!"
else
log_warn "No Logseq installation found in default locations"
fi
}
# Parse command line arguments
VERSION="$DEFAULT_VERSION"
USER_INSTALL=false
SKIP_DESKTOP=false
VERBOSE=false
while [[ $# -gt 0 ]]; do
case $1 in
--help|-h)
show_help
exit 0
;;
--prefix)
INSTALL_DIR="$2"
shift 2
;;
--user)
USER_INSTALL=true
shift
;;
--no-desktop)
SKIP_DESKTOP=true
shift
;;
--verbose|-v)
VERBOSE=true
shift
;;
uninstall)
uninstall
exit 0
;;
-*)
log_error "Unknown option: $1"
show_help
exit 1
;;
*)
VERSION="$1"
shift
;;
esac
done
# Set installation paths based on user/system install
if [[ "$USER_INSTALL" == true ]]; then
INSTALL_DIR="${INSTALL_DIR/#\/opt\/logseq/$HOME/.local/share/logseq}"
BIN_DIR="$HOME/.local/bin"
mkdir -p "$BIN_DIR"
# Add local bin to PATH if not already there
if ! echo "$PATH" | grep -q "$HOME/.local/bin"; then
log_info "Adding $HOME/.local/bin to PATH..."
export PATH="$HOME/.local/bin:$PATH"
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
fi
fi
log_info "Installing Logseq $VERSION to $INSTALL_DIR"
# Check if running as root for system-wide installation
if [[ "$USER_INSTALL" == false && $EUID -ne 0 ]]; then
log_warn "System-wide installation requires root privileges"
log_warn "Run with sudo or use --user for user-specific installation"
exit 1
fi
# Create temporary directory
TEMP_DIR=$(mktemp -d)
if [[ "$VERBOSE" == true ]]; then
log_info "Using temporary directory: $TEMP_DIR"
fi
cd "$TEMP_DIR"
# Determine download URL
if [[ "$VERSION" == "latest" ]]; then
log_info "Fetching latest release information..."
LATEST_RELEASE=$(curl -s https://api.github.com/repos/logseq/logseq/releases/latest)
DOWNLOAD_URL=$(echo "$LATEST_RELEASE" | grep -o '"browser_download_url": "[^"]*Logseq-linux-x64-[^"]*\.zip"' | cut -d'"' -f4)
if [[ -z "$DOWNLOAD_URL" ]]; then
log_error "Could not find download URL for latest version"
exit 1
fi
else
DOWNLOAD_URL="https://github.com/logseq/logseq/releases/download/${VERSION}/Logseq-linux-x64-${VERSION}.zip"
fi
log_info "Download URL: $DOWNLOAD_URL"
# Download Logseq
log_info "Downloading Logseq..."
if ! wget -q --show-progress -O logseq.zip "$DOWNLOAD_URL"; then
log_error "Failed to download Logseq $VERSION"
log_error "Please check if version $VERSION exists on GitHub releases"
rm -rf "$TEMP_DIR"
exit 1
fi
# Extract archive
log_info "Extracting archive..."
unzip -q logseq.zip
# Find the extracted directory
EXTRACTED_DIR=$(find . -maxdepth 2 -type d -name "Logseq-linux-x64*" | head -1)
if [[ -z "$EXTRACTED_DIR" ]]; then
log_error "Could not find extracted Logseq directory"
rm -rf "$TEMP_DIR"
exit 1
fi
# Install files
log_info "Installing files..."
if [[ "$USER_INSTALL" == false ]]; then
mkdir -p "$INSTALL_DIR"
cp -r "$EXTRACTED_DIR"/* "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR/Logseq"
ln -sf "$INSTALL_DIR/Logseq" "$BIN_DIR/logseq"
else
mkdir -p "$INSTALL_DIR"
cp -r "$EXTRACTED_DIR"/* "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR/Logseq"
ln -sf "$INSTALL_DIR/Logseq" "$BIN_DIR/logseq"
fi
# Fix sandbox permissions
if [[ "$USER_INSTALL" == false && -f "$INSTALL_DIR/chrome-sandbox" ]]; then
log_info "Setting sandbox permissions..."
chown root:root "$INSTALL_DIR/chrome-sandbox"
chmod 4755 "$INSTALL_DIR/chrome-sandbox"
fi
# Desktop integration
if [[ "$SKIP_DESKTOP" == false ]]; then
log_info "Creating desktop integration..."
DESKTOP_FILE="/usr/share/applications/logseq.desktop"
if [[ "$USER_INSTALL" == true ]]; then
mkdir -p ~/.local/share/applications/
DESKTOP_FILE="$HOME/.local/share/applications/logseq.desktop"
fi
# Copy icon to standard location
if [[ "$USER_INSTALL" == true ]]; then
ICON_DIR="$HOME/.local/share/icons/hicolor/512x512/apps"
else
ICON_DIR="/usr/share/icons/hicolor/512x512/apps"
fi
# Ensure the directory exists regardless of install type
mkdir -p "$ICON_DIR"
# Create desktop file
cat > "$DESKTOP_FILE" << DESKTOP_EOF
[Desktop Entry]
Version=1.0
Name=Logseq
Comment=Logseq - A privacy-first, open-source platform for knowledge management and collaboration
Exec=$INSTALL_DIR/Logseq $([ "$USER_INSTALL" = true ] && echo "--no-sandbox") %U
Icon=$ICON_DIR/logseq.png
Terminal=false
Type=Application
Categories=Office;Productivity;Utility;TextEditor;
MimeType=application/x-logseq;
StartupWMClass=Logseq
DESKTOP_EOF
# Make desktop file executable
chmod +x "$DESKTOP_FILE"
# 1. Find and copy the icon (try current paths first, then fallbacks)
if [[ -f "$INSTALL_DIR/resources/app/icons/logseq.png" ]]; then
cp "$INSTALL_DIR/resources/app/icons/logseq.png" "$ICON_DIR/logseq.png"
elif [[ -f "$INSTALL_DIR/resources/app.asar.unpacked/dist/icon.png" ]]; then
cp "$INSTALL_DIR/resources/app.asar.unpacked/dist/icon.png" "$ICON_DIR/logseq.png"
elif [[ -f "$INSTALL_DIR/resources/app/icon.png" ]]; then
cp "$INSTALL_DIR/resources/app/icon.png" "$ICON_DIR/logseq.png"
fi
# 2. Update desktop file to use purely the icon name for system-wide installs
if [[ "$USER_INSTALL" == false ]]; then
sed -i "s|Icon=$ICON_DIR/logseq.png|Icon=logseq|" "$DESKTOP_FILE"
fi
# Update desktop database
if [[ "$USER_INSTALL" == false ]]; then
update-desktop-database /usr/share/applications/ 2>/dev/null || true
else
update-desktop-database ~/.local/share/applications/ 2>/dev/null || true
fi
fi
# Clean up
rm -rf "$TEMP_DIR"
# Verify installation
if command -v logseq >/dev/null 2>&1; then
# Safely extract the version number from `package.json` as a priority, preventing the script from hanging during the launch of the Electron process.
if [[ -f "$INSTALL_DIR/resources/app/package.json" ]]; then
INSTALLED_VERSION=$(grep -m 1 '"version"' "$INSTALL_DIR/resources/app/package.json" | cut -d'"' -f4 || echo "unknown")
else
# Fallback Plan: Add a 2-second timeout to forcibly terminate the process, preventing the application from hanging.
INSTALLED_VERSION=$(timeout 2 logseq --version 2>/dev/null | head -1 || echo "unknown")
fi
log_info "Logseq installed successfully!"
log_info "Version: $INSTALLED_VERSION"
log_info "Location: $INSTALL_DIR"
log_info "Command: logseq"
if [[ "$SKIP_DESKTOP" == false ]]; then
log_info "Desktop integration: Enabled"
log_info "You can find Logseq in your applications menu"
fi
else
log_error "Installation completed but 'logseq' command not found in PATH"
log_info "You may need to restart your terminal or add $BIN_DIR to your PATH"
fi
log_info "Installation completed successfully!"
+41
View File
@@ -0,0 +1,41 @@
import fs from 'node:fs'
import path from 'node:path'
const unsupportedFontFilePattern = /\.(?:woff2|woff)$/
const unsupportedCssFontPattern = /\.woff2?["')]|\bformat\(["']woff2?["']\)/
const walk = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true })
return entries.flatMap((entry) => {
const fullPath = path.join(dir, entry.name)
return entry.isDirectory() ? walk(fullPath) : fullPath
})
}
const relativePath = (repoRoot, filePath) =>
path.relative(repoRoot, filePath).split(path.sep).join('/')
export const existingAssetRoots = (assetRoots) =>
assetRoots.filter((root) => fs.existsSync(root))
export const findUnsupportedIOSFontAssets = ({ repoRoot, assetRoots }) => {
const roots = existingAssetRoots(assetRoots)
const files = roots.flatMap(walk)
return {
fontFiles: files
.filter((filePath) => unsupportedFontFilePattern.test(filePath))
.map((filePath) => relativePath(repoRoot, filePath))
.sort(),
cssFiles: files
.filter((filePath) => filePath.endsWith('.css'))
.flatMap((filePath) => {
const css = fs.readFileSync(filePath, 'utf8')
return unsupportedCssFontPattern.test(css)
? [relativePath(repoRoot, filePath)]
: []
})
.sort(),
roots,
}
}
+109
View File
@@ -0,0 +1,109 @@
'use strict';
const OPERATION_ORDER = Object.freeze([
'add',
'copyPaste',
'copyPasteTreeToEmptyTarget',
'move',
'indent',
'outdent',
'delete',
'undo',
'redo',
]);
function buildOperationPlan(totalOps) {
if (!Number.isInteger(totalOps) || totalOps <= 0) {
throw new Error('totalOps must be a positive integer');
}
const plan = [];
for (let i = 0; i < totalOps; i += 1) {
plan.push(OPERATION_ORDER[i % OPERATION_ORDER.length]);
}
return plan;
}
function chooseRunnableOperation(requestedOperation, managedCount) {
switch (requestedOperation) {
case 'copyPaste':
case 'copyPasteTreeToEmptyTarget':
return managedCount >= 1 ? requestedOperation : 'add';
case 'move':
case 'indent':
case 'delete':
return managedCount >= 2 ? requestedOperation : 'add';
case 'outdent':
case 'add':
case 'undo':
case 'redo':
return requestedOperation;
default:
throw new Error(`Unsupported operation kind: ${requestedOperation}`);
}
}
function parsePositiveInteger(value, flagName) {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new Error(`${flagName} must be a positive integer`);
}
return parsed;
}
function parseNonNegativeInteger(value, flagName) {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed) || parsed < 0) {
throw new Error(`${flagName} must be a non-negative integer`);
}
return parsed;
}
function parseArgs(argv) {
const result = {
ops: 200,
port: 9333,
undoRedoDelayMs: 350,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--help' || arg === '-h') {
return { ...result, help: true };
}
const next = argv[i + 1];
if (arg === '--ops') {
result.ops = parsePositiveInteger(next, '--ops');
i += 1;
continue;
}
if (arg === '--port') {
result.port = parsePositiveInteger(next, '--port');
i += 1;
continue;
}
if (arg === '--undo-redo-delay-ms') {
result.undoRedoDelayMs = parseNonNegativeInteger(next, '--undo-redo-delay-ms');
i += 1;
continue;
}
throw new Error(`Unknown argument: ${arg}`);
}
if (result.ops < 200) {
throw new Error('--ops must be at least 200');
}
return result;
}
module.exports = {
OPERATION_ORDER,
buildOperationPlan,
chooseRunnableOperation,
parseArgs,
};
@@ -0,0 +1,44 @@
const unsupportedIOSWebFontSourcePattern =
/\.woff2?(?:[?#][^"')\s]*)?(?:["')\s]|$)|format\(["']woff2?["']\)/i
const stripUnsupportedIOSWebFontValue = (value) => {
const sources = value.split(/,(?=\s*(?:url|local)\()/)
const supportedSources = sources.filter((source) =>
!unsupportedIOSWebFontSourcePattern.test(source))
return supportedSources.length === 0 ? null : supportedSources.join(',')
}
const stripUnsupportedIOSWebFontSources = (css) =>
css.replace(/@font-face\s*{[^{}]*}/g, (fontFace) => {
let hasSupportedSrc = true
const nextFontFace = fontFace.replace(/src:([^;}]+)([;}])/g, (_match, value, delimiter) => {
const nextValue = stripUnsupportedIOSWebFontValue(value)
hasSupportedSrc = nextValue !== null
return nextValue === null ? '' : `src:${nextValue}${delimiter}`
})
return hasSupportedSrc ? nextFontFace : ''
})
const stripIOSWebFontSourcesPlugin = () => ({
postcssPlugin: 'strip-ios-web-font-sources',
Declaration (decl) {
if (decl.prop.toLowerCase() === 'src') {
const nextValue = stripUnsupportedIOSWebFontValue(decl.value)
if (nextValue === null) {
if (decl.parent?.type === 'atrule' && decl.parent.name === 'font-face') {
decl.parent.remove()
} else {
decl.remove()
}
} else {
decl.value = nextValue
}
}
},
})
module.exports = {
stripIOSWebFontSourcesPlugin,
stripUnsupportedIOSWebFontSources,
}
+11
View File
@@ -0,0 +1,11 @@
{:paths ["src"]
:deps
{logseq/graph-parser
{:local/root "../deps/graph-parser"}
logseq/outliner
{:local/root "../deps/outliner"}
;; for config.edn
logseq/common
{:local/root "../deps/common"}
logseq/publishing
{:local/root "../deps/publishing"}}}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "nbb-dev-scripts",
"version": "1.0.0",
"packageManager": "pnpm@10.33.0",
"private": true,
"scripts": {
"test": "pnpm exec nbb-logseq -cp test -m logseq.tasks.test-runner"
},
"devDependencies": {
"@logseq/nbb-logseq": "git+https://github.com/logseq/nbb-logseq.git#feat-db-v34"
},
"dependencies": {
"better-sqlite3": "12.8.0",
"fs-extra": "^11.3.4",
"mldoc": "^1.5.9"
},
"pnpm": {
"onlyBuiltDependencies": [
"better-sqlite3"
]
}
}
+49
View File
@@ -0,0 +1,49 @@
#!/bin/bash
# This script patches the iOS project to use the correct codesigning and provisioning profiles.
set -e
set -o pipefail
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd ${SCRIPT_DIR}/../ios/App
ls -lah App.xcodeproj/project.pbxproj
FILE="App.xcodeproj/project.pbxproj"
/usr/libexec/PlistBuddy -c 'Set :objects:504EC2FC1FED79650016851F:attributes:TargetAttributes:504EC3031FED79650016851F:ProvisioningStyle Manual' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:504EC2FC1FED79650016851F:attributes:TargetAttributes:5FFF7D6927E343FA00B00DA8:ProvisioningStyle Manual' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:504EC3171FED79650016851F:buildSettings:CODE_SIGN_STYLE Manual' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:504EC3171FED79650016851F:buildSettings:"CODE_SIGN_IDENTITY[sdk=iphoneos*]" String "iPhone Distribution"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:504EC3171FED79650016851F:buildSettings:DEVELOPMENT_TEAM ""' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:504EC3171FED79650016851F:buildSettings:"DEVELOPMENT_TEAM[sdk=iphoneos*]" String K378MFWK59' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:504EC3171FED79650016851F:buildSettings:"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" String "match AppStore com.logseq.logseq"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:504EC3181FED79650016851F:buildSettings:CODE_SIGN_STYLE Manual' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:504EC3181FED79650016851F:buildSettings:"CODE_SIGN_IDENTITY[sdk=iphoneos*]" String "iPhone Distribution"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:504EC3181FED79650016851F:buildSettings:DEVELOPMENT_TEAM ""' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:504EC3181FED79650016851F:buildSettings:"DEVELOPMENT_TEAM[sdk=iphoneos*]" String K378MFWK59' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:504EC3181FED79650016851F:buildSettings:"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" String "match AppStore com.logseq.logseq"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:5FFF7D7627E343FA00B00DA8:buildSettings:CODE_SIGN_STYLE Manual' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:5FFF7D7627E343FA00B00DA8:buildSettings:"CODE_SIGN_IDENTITY[sdk=iphoneos*]" String "iPhone Distribution"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:5FFF7D7627E343FA00B00DA8:buildSettings:DEVELOPMENT_TEAM ""' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:5FFF7D7627E343FA00B00DA8:buildSettings:"DEVELOPMENT_TEAM[sdk=iphoneos*]" String K378MFWK59' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:5FFF7D7627E343FA00B00DA8:buildSettings:"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" String "match AppStore com.logseq.logseq.ShareViewController"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:5FFF7D7727E343FA00B00DA8:buildSettings:CODE_SIGN_STYLE Manual' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:5FFF7D7727E343FA00B00DA8:buildSettings:"CODE_SIGN_IDENTITY[sdk=iphoneos*]" String "iPhone Distribution"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:5FFF7D7727E343FA00B00DA8:buildSettings:DEVELOPMENT_TEAM ""' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:5FFF7D7727E343FA00B00DA8:buildSettings:"DEVELOPMENT_TEAM[sdk=iphoneos*]" String K378MFWK59' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:5FFF7D7727E343FA00B00DA8:buildSettings:"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" String "match AppStore com.logseq.logseq.ShareViewController"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:D3490CD72E7CE9EB00E796A6:buildSettings:CODE_SIGN_STYLE Manual' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:D3490CD72E7CE9EB00E796A6:buildSettings:"CODE_SIGN_IDENTITY[sdk=iphoneos*]" String "iPhone Distribution"' $FILE
/usr/libexec/PlistBuddy -c 'Set :objects:D3490CD72E7CE9EB00E796A6:buildSettings:DEVELOPMENT_TEAM ""' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:D3490CD72E7CE9EB00E796A6:buildSettings:"DEVELOPMENT_TEAM[sdk=iphoneos*]" String K378MFWK59' $FILE
/usr/libexec/PlistBuddy -c 'Add :objects:D3490CD72E7CE9EB00E796A6:buildSettings:"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" String "match AppStore com.logseq.logseq.shortcuts"' $FILE
echo Patch OK!
+724
View File
@@ -0,0 +1,724 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
better-sqlite3:
specifier: 12.8.0
version: 12.8.0
fs-extra:
specifier: ^11.3.4
version: 11.3.4
mldoc:
specifier: ^1.5.9
version: 1.5.9
devDependencies:
'@logseq/nbb-logseq':
specifier: git+https://github.com/logseq/nbb-logseq.git#feat-db-v34
version: https://codeload.github.com/logseq/nbb-logseq/tar.gz/4d9f1382ce2cec6f39bf12df49ba425f1bd5f3fb
packages:
'@logseq/nbb-logseq@https://codeload.github.com/logseq/nbb-logseq/tar.gz/4d9f1382ce2cec6f39bf12df49ba425f1bd5f3fb':
resolution: {tarball: https://codeload.github.com/logseq/nbb-logseq/tar.gz/4d9f1382ce2cec6f39bf12df49ba425f1bd5f3fb}
version: 1.2.173-feat-db-v34
engines: {node: '>=20.10.0'}
hasBin: true
ansi-regex@2.1.1:
resolution: {integrity: sha512-TIGnTpdo+E3+pCyAluZvtED5p5wCqLdezCyhPZzKPcxvFplEt4i+W7OONCKgeZFT3+y5NZZfOOS/Bdcanm1MYA==}
engines: {node: '>=0.10.0'}
ansi-regex@3.0.1:
resolution: {integrity: sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==}
engines: {node: '>=4'}
base64-js@1.5.1:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
better-sqlite3@12.8.0:
resolution: {integrity: sha512-RxD2Vd96sQDjQr20kdP+F+dK/1OUNiVOl200vKBZY8u0vTwysfolF6Hq+3ZK2+h8My9YvZhHsF+RSGZW2VYrPQ==}
engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x}
bindings@1.5.0:
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
bl@4.1.0:
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
buffer@5.7.1:
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
camelcase@5.3.1:
resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
engines: {node: '>=6'}
chownr@1.1.4:
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
cliui@4.1.0:
resolution: {integrity: sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==}
code-point-at@1.1.0:
resolution: {integrity: sha512-RpAVKQA5T63xEj6/giIbUEtZwJ4UFIc3ZtvEkiaUERylqe8xb5IvqcgOurZLahv93CLKfxcw5YI+DZcUBRyLXA==}
engines: {node: '>=0.10.0'}
cross-spawn@6.0.6:
resolution: {integrity: sha512-VqCUuhcd1iB+dsv8gxPttb5iZh/D0iubSP21g36KXdEuf6I5JiioesUVjpCdHV9MZRUfVFlvwtIUyPfxo5trtw==}
engines: {node: '>=4.8'}
decamelize@1.2.0:
resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
engines: {node: '>=0.10.0'}
decompress-response@6.0.0:
resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}
engines: {node: '>=10'}
deep-extend@0.6.0:
resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==}
engines: {node: '>=4.0.0'}
detect-libc@2.0.3:
resolution: {integrity: sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==}
engines: {node: '>=8'}
end-of-stream@1.4.4:
resolution: {integrity: sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==}
execa@1.0.0:
resolution: {integrity: sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==}
engines: {node: '>=6'}
expand-template@2.0.3:
resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}
engines: {node: '>=6'}
file-uri-to-path@1.0.0:
resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}
find-up@3.0.0:
resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==}
engines: {node: '>=6'}
fs-constants@1.0.0:
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
fs-extra@11.3.4:
resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==}
engines: {node: '>=14.14'}
get-caller-file@1.0.3:
resolution: {integrity: sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==}
get-stream@4.1.0:
resolution: {integrity: sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==}
engines: {node: '>=6'}
github-from-package@0.0.0:
resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==}
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
ieee754@1.2.1:
resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
import-meta-resolve@4.1.0:
resolution: {integrity: sha512-I6fiaX09Xivtk+THaMfAwnA3MVA5Big1WHF1Dfx9hFuvNIWpXnorlkzhcQf6ehrqQiiZECRt1poOAkPmer3ruw==}
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
ini@1.3.8:
resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}
invert-kv@2.0.0:
resolution: {integrity: sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==}
engines: {node: '>=4'}
is-fullwidth-code-point@1.0.0:
resolution: {integrity: sha512-1pqUqRjkhPJ9miNq9SwMfdvi6lBJcd6eFxvfaivQhaH3SgisfiuudvFntdKOmxuee/77l+FPjKrQjWvmPjWrRw==}
engines: {node: '>=0.10.0'}
is-fullwidth-code-point@2.0.0:
resolution: {integrity: sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==}
engines: {node: '>=4'}
is-stream@1.1.0:
resolution: {integrity: sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==}
engines: {node: '>=0.10.0'}
isexe@2.0.0:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
jsonfile@6.1.0:
resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==}
lcid@2.0.0:
resolution: {integrity: sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==}
engines: {node: '>=6'}
locate-path@3.0.0:
resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==}
engines: {node: '>=6'}
map-age-cleaner@0.1.3:
resolution: {integrity: sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==}
engines: {node: '>=6'}
mem@4.3.0:
resolution: {integrity: sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==}
engines: {node: '>=6'}
mimic-fn@2.1.0:
resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}
engines: {node: '>=6'}
mimic-response@3.1.0:
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
engines: {node: '>=10'}
minimist@1.2.8:
resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}
mkdirp-classic@0.5.3:
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
mldoc@1.5.9:
resolution: {integrity: sha512-87FQ7hseS87tsk+VdpIigpu8LH+GwmbbFgpxgFwvnbH5oOjmIrc47laH4Dyggzqiy8/vMjDHkl7vsId0eXhCDQ==}
hasBin: true
napi-build-utils@1.0.2:
resolution: {integrity: sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==}
nice-try@1.0.5:
resolution: {integrity: sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==}
node-abi@3.71.0:
resolution: {integrity: sha512-SZ40vRiy/+wRTf21hxkkEjPJZpARzUMVcJoQse2EF8qkUWbbO2z7vd5oA/H6bVH6SZQ5STGcu0KRDS7biNRfxw==}
engines: {node: '>=10'}
npm-run-path@2.0.2:
resolution: {integrity: sha512-lJxZYlT4DW/bRUtFh1MQIWqmLwQfAxnqWG4HhEdjMlkrJYnJn0Jrr2u3mgxqaWsdiBc76TYkTG/mhrnYTuzfHw==}
engines: {node: '>=4'}
number-is-nan@1.0.1:
resolution: {integrity: sha512-4jbtZXNAsfZbAHiiqjLPBiCl16dES1zI4Hpzzxw61Tk+loF+sBDBKx1ICKKKwIqQ7M0mFn1TmkN7euSncWgHiQ==}
engines: {node: '>=0.10.0'}
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
os-locale@3.1.0:
resolution: {integrity: sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==}
engines: {node: '>=6'}
p-defer@1.0.0:
resolution: {integrity: sha512-wB3wfAxZpk2AzOfUMJNL+d36xothRSyj8EXOa4f6GMqYDN9BJaaSISbsk+wS9abmnebVw95C2Kb5t85UmpCxuw==}
engines: {node: '>=4'}
p-finally@1.0.0:
resolution: {integrity: sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==}
engines: {node: '>=4'}
p-is-promise@2.1.0:
resolution: {integrity: sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==}
engines: {node: '>=6'}
p-limit@2.3.0:
resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
engines: {node: '>=6'}
p-locate@3.0.0:
resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==}
engines: {node: '>=6'}
p-try@2.2.0:
resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}
engines: {node: '>=6'}
path-exists@3.0.0:
resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==}
engines: {node: '>=4'}
path-key@2.0.1:
resolution: {integrity: sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==}
engines: {node: '>=4'}
prebuild-install@7.1.2:
resolution: {integrity: sha512-UnNke3IQb6sgarcZIDU3gbMeTp/9SSU1DAIkil7PrqG1vZlBtY5msYccSKSHDqa3hNg436IXK+SNImReuA1wEQ==}
engines: {node: '>=10'}
deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available.
hasBin: true
pump@3.0.2:
resolution: {integrity: sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw==}
rc@1.2.8:
resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}
hasBin: true
readable-stream@3.6.2:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
require-directory@2.1.1:
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
require-main-filename@1.0.1:
resolution: {integrity: sha512-IqSUtOVP4ksd1C/ej5zeEh/BIP2ajqpn8c5x+q99gvcIG/Qf0cud5raVnE/Dwd0ua9TXYDoDc0RE5hBSdz22Ug==}
safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
semver@5.7.2:
resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==}
hasBin: true
semver@7.6.3:
resolution: {integrity: sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==}
engines: {node: '>=10'}
hasBin: true
set-blocking@2.0.0:
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
shebang-command@1.2.0:
resolution: {integrity: sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==}
engines: {node: '>=0.10.0'}
shebang-regex@1.0.0:
resolution: {integrity: sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==}
engines: {node: '>=0.10.0'}
signal-exit@3.0.7:
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
simple-concat@1.0.1:
resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}
simple-get@4.0.1:
resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}
string-width@1.0.2:
resolution: {integrity: sha512-0XsVpQLnVCXHJfyEs8tC0zpTVIr5PKKsQtkT29IwupnPTjtPmQ3xT/4yCREF9hYkV/3M3kzcUTSAZT6a6h81tw==}
engines: {node: '>=0.10.0'}
string-width@2.1.1:
resolution: {integrity: sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==}
engines: {node: '>=4'}
string_decoder@1.3.0:
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
strip-ansi@3.0.1:
resolution: {integrity: sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==}
engines: {node: '>=0.10.0'}
strip-ansi@4.0.0:
resolution: {integrity: sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==}
engines: {node: '>=4'}
strip-eof@1.0.0:
resolution: {integrity: sha512-7FCwGGmx8mD5xQd3RPUvnSpUXHM3BWuzjtpD4TXsfcZ9EL4azvVVUscFYwD9nx8Kh+uCBC00XBtAykoMHwTh8Q==}
engines: {node: '>=0.10.0'}
strip-json-comments@2.0.1:
resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}
engines: {node: '>=0.10.0'}
tar-fs@2.1.1:
resolution: {integrity: sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==}
tar-stream@2.2.0:
resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
engines: {node: '>=6'}
tunnel-agent@0.6.0:
resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==}
universalify@2.0.1:
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
engines: {node: '>= 10.0.0'}
util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
which-module@2.0.1:
resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==}
which@1.3.1:
resolution: {integrity: sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==}
hasBin: true
wrap-ansi@2.1.0:
resolution: {integrity: sha512-vAaEaDM946gbNpH5pLVNR+vX2ht6n0Bt3GXwVB1AuAqZosOvHNF3P7wDnh8KLkSqgUh0uh77le7Owgoz+Z9XBw==}
engines: {node: '>=0.10.0'}
wrappy@1.0.2:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
y18n@4.0.3:
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
yargs-parser@11.1.1:
resolution: {integrity: sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==}
yargs@12.0.5:
resolution: {integrity: sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==}
snapshots:
'@logseq/nbb-logseq@https://codeload.github.com/logseq/nbb-logseq/tar.gz/4d9f1382ce2cec6f39bf12df49ba425f1bd5f3fb':
dependencies:
import-meta-resolve: 4.1.0
ansi-regex@2.1.1: {}
ansi-regex@3.0.1: {}
base64-js@1.5.1: {}
better-sqlite3@12.8.0:
dependencies:
bindings: 1.5.0
prebuild-install: 7.1.2
bindings@1.5.0:
dependencies:
file-uri-to-path: 1.0.0
bl@4.1.0:
dependencies:
buffer: 5.7.1
inherits: 2.0.4
readable-stream: 3.6.2
buffer@5.7.1:
dependencies:
base64-js: 1.5.1
ieee754: 1.2.1
camelcase@5.3.1: {}
chownr@1.1.4: {}
cliui@4.1.0:
dependencies:
string-width: 2.1.1
strip-ansi: 4.0.0
wrap-ansi: 2.1.0
code-point-at@1.1.0: {}
cross-spawn@6.0.6:
dependencies:
nice-try: 1.0.5
path-key: 2.0.1
semver: 5.7.2
shebang-command: 1.2.0
which: 1.3.1
decamelize@1.2.0: {}
decompress-response@6.0.0:
dependencies:
mimic-response: 3.1.0
deep-extend@0.6.0: {}
detect-libc@2.0.3: {}
end-of-stream@1.4.4:
dependencies:
once: 1.4.0
execa@1.0.0:
dependencies:
cross-spawn: 6.0.6
get-stream: 4.1.0
is-stream: 1.1.0
npm-run-path: 2.0.2
p-finally: 1.0.0
signal-exit: 3.0.7
strip-eof: 1.0.0
expand-template@2.0.3: {}
file-uri-to-path@1.0.0: {}
find-up@3.0.0:
dependencies:
locate-path: 3.0.0
fs-constants@1.0.0: {}
fs-extra@11.3.4:
dependencies:
graceful-fs: 4.2.11
jsonfile: 6.1.0
universalify: 2.0.1
get-caller-file@1.0.3: {}
get-stream@4.1.0:
dependencies:
pump: 3.0.2
github-from-package@0.0.0: {}
graceful-fs@4.2.11: {}
ieee754@1.2.1: {}
import-meta-resolve@4.1.0: {}
inherits@2.0.4: {}
ini@1.3.8: {}
invert-kv@2.0.0: {}
is-fullwidth-code-point@1.0.0:
dependencies:
number-is-nan: 1.0.1
is-fullwidth-code-point@2.0.0: {}
is-stream@1.1.0: {}
isexe@2.0.0: {}
jsonfile@6.1.0:
dependencies:
universalify: 2.0.1
optionalDependencies:
graceful-fs: 4.2.11
lcid@2.0.0:
dependencies:
invert-kv: 2.0.0
locate-path@3.0.0:
dependencies:
p-locate: 3.0.0
path-exists: 3.0.0
map-age-cleaner@0.1.3:
dependencies:
p-defer: 1.0.0
mem@4.3.0:
dependencies:
map-age-cleaner: 0.1.3
mimic-fn: 2.1.0
p-is-promise: 2.1.0
mimic-fn@2.1.0: {}
mimic-response@3.1.0: {}
minimist@1.2.8: {}
mkdirp-classic@0.5.3: {}
mldoc@1.5.9:
dependencies:
yargs: 12.0.5
napi-build-utils@1.0.2: {}
nice-try@1.0.5: {}
node-abi@3.71.0:
dependencies:
semver: 7.6.3
npm-run-path@2.0.2:
dependencies:
path-key: 2.0.1
number-is-nan@1.0.1: {}
once@1.4.0:
dependencies:
wrappy: 1.0.2
os-locale@3.1.0:
dependencies:
execa: 1.0.0
lcid: 2.0.0
mem: 4.3.0
p-defer@1.0.0: {}
p-finally@1.0.0: {}
p-is-promise@2.1.0: {}
p-limit@2.3.0:
dependencies:
p-try: 2.2.0
p-locate@3.0.0:
dependencies:
p-limit: 2.3.0
p-try@2.2.0: {}
path-exists@3.0.0: {}
path-key@2.0.1: {}
prebuild-install@7.1.2:
dependencies:
detect-libc: 2.0.3
expand-template: 2.0.3
github-from-package: 0.0.0
minimist: 1.2.8
mkdirp-classic: 0.5.3
napi-build-utils: 1.0.2
node-abi: 3.71.0
pump: 3.0.2
rc: 1.2.8
simple-get: 4.0.1
tar-fs: 2.1.1
tunnel-agent: 0.6.0
pump@3.0.2:
dependencies:
end-of-stream: 1.4.4
once: 1.4.0
rc@1.2.8:
dependencies:
deep-extend: 0.6.0
ini: 1.3.8
minimist: 1.2.8
strip-json-comments: 2.0.1
readable-stream@3.6.2:
dependencies:
inherits: 2.0.4
string_decoder: 1.3.0
util-deprecate: 1.0.2
require-directory@2.1.1: {}
require-main-filename@1.0.1: {}
safe-buffer@5.2.1: {}
semver@5.7.2: {}
semver@7.6.3: {}
set-blocking@2.0.0: {}
shebang-command@1.2.0:
dependencies:
shebang-regex: 1.0.0
shebang-regex@1.0.0: {}
signal-exit@3.0.7: {}
simple-concat@1.0.1: {}
simple-get@4.0.1:
dependencies:
decompress-response: 6.0.0
once: 1.4.0
simple-concat: 1.0.1
string-width@1.0.2:
dependencies:
code-point-at: 1.1.0
is-fullwidth-code-point: 1.0.0
strip-ansi: 3.0.1
string-width@2.1.1:
dependencies:
is-fullwidth-code-point: 2.0.0
strip-ansi: 4.0.0
string_decoder@1.3.0:
dependencies:
safe-buffer: 5.2.1
strip-ansi@3.0.1:
dependencies:
ansi-regex: 2.1.1
strip-ansi@4.0.0:
dependencies:
ansi-regex: 3.0.1
strip-eof@1.0.0: {}
strip-json-comments@2.0.1: {}
tar-fs@2.1.1:
dependencies:
chownr: 1.1.4
mkdirp-classic: 0.5.3
pump: 3.0.2
tar-stream: 2.2.0
tar-stream@2.2.0:
dependencies:
bl: 4.1.0
end-of-stream: 1.4.4
fs-constants: 1.0.0
inherits: 2.0.4
readable-stream: 3.6.2
tunnel-agent@0.6.0:
dependencies:
safe-buffer: 5.2.1
universalify@2.0.1: {}
util-deprecate@1.0.2: {}
which-module@2.0.1: {}
which@1.3.1:
dependencies:
isexe: 2.0.0
wrap-ansi@2.1.0:
dependencies:
string-width: 1.0.2
strip-ansi: 3.0.1
wrappy@1.0.2: {}
y18n@4.0.3: {}
yargs-parser@11.1.1:
dependencies:
camelcase: 5.3.1
decamelize: 1.2.0
yargs@12.0.5:
dependencies:
cliui: 4.1.0
decamelize: 1.2.0
find-up: 3.0.0
get-caller-file: 1.0.3
os-locale: 3.1.0
require-directory: 2.1.1
require-main-filename: 1.0.1
set-blocking: 2.0.0
string-width: 2.1.1
which-module: 2.0.1
y18n: 4.0.3
yargs-parser: 11.1.1
+160
View File
@@ -0,0 +1,160 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageRoot = path.join(repoRoot, "dist", "cli-package");
const cliBundlePath = path.join(
repoRoot,
"cli",
"_build",
"default",
"dist",
"logseq-cli.js",
);
const stagedCliPath = path.join(repoRoot, "static", "logseq-cli.js");
const rootPackage = JSON.parse(
fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"),
);
const packageFiles = [
"dist/logseq.js",
"static/logseq-cli.js",
"static/js/db-worker-node.js",
"static/js/db-worker-node-assets.json",
".agents/skills/logseq-cli/SKILL.md",
];
const copyEntries = [
["dist/logseq.js", "dist/logseq.js"],
["static/logseq-cli.js", "static/logseq-cli.js"],
["dist/db-worker-node.js", "static/js/db-worker-node.js"],
["dist/db-worker-node-assets.json", "static/js/db-worker-node-assets.json"],
[".agents/skills/logseq-cli/SKILL.md", ".agents/skills/logseq-cli/SKILL.md"],
];
const assertReleaseEntrypoint = (content) => {
for (const needle of ["SHADOW_IMPORT", ".shadow-cljs", "cljs-runtime"]) {
if (content.includes(needle)) {
throw new Error(
`static/logseq-cli.js still references Shadow runtime output: ${needle}`,
);
}
}
};
const assertFreshCliRuntime = () => {
if (!fs.existsSync(cliBundlePath)) {
throw new Error(
"Missing CLI package input: cli/_build/default/dist/logseq-cli.js",
);
}
if (!fs.existsSync(stagedCliPath)) {
throw new Error("Missing CLI package input: static/logseq-cli.js");
}
const bundleStats = fs.statSync(cliBundlePath);
const stagedStats = fs.statSync(stagedCliPath);
if (stagedStats.mtimeMs + 1000 < bundleStats.mtimeMs) {
throw new Error(
"static/logseq-cli.js is older than cli/_build/default/dist/logseq-cli.js; run `pnpm cli:release` before preparing the CLI package",
);
}
};
const dependencyNames = [
"@js-joda/core",
"@zvec/bindings-darwin-arm64",
"@zvec/bindings-linux-arm64",
"@zvec/bindings-linux-x64",
"@zvec/bindings-win32-x64",
"@zvec/zvec",
"better-sqlite3",
"fs-extra",
"jszip",
"keytar",
"mldoc",
"picocolors",
"string-width",
"ws",
];
const onlyBuiltDependencies = rootPackage.pnpm.onlyBuiltDependencies.filter(
(name) => dependencyNames.includes(name),
);
const dependencyVersion = (name) =>
rootPackage.dependencies?.[name] ??
rootPackage.optionalDependencies?.[name] ??
rootPackage.devDependencies?.[name];
const dependencyEntries = dependencyNames.map((name) => {
const version = dependencyVersion(name);
if (!version) {
throw new Error(`Missing CLI runtime dependency in package.json: ${name}`);
}
return [name, version];
});
const optionalDependencyNames = new Set(
Object.keys(rootPackage.optionalDependencies ?? {}),
);
const dependencies = Object.fromEntries(
dependencyEntries.filter(([name]) => !optionalDependencyNames.has(name)),
);
const optionalDependencies = Object.fromEntries(
dependencyEntries.filter(([name]) => optionalDependencyNames.has(name)),
);
assertFreshCliRuntime();
assertReleaseEntrypoint(fs.readFileSync(stagedCliPath, "utf8"));
fs.rmSync(packageRoot, { recursive: true, force: true });
for (const [sourcePath, packagePath] of copyEntries) {
const source = path.join(repoRoot, sourcePath);
if (!fs.existsSync(source)) {
throw new Error(`Missing CLI package input: ${sourcePath}`);
}
const destination = path.join(packageRoot, packagePath);
fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.copyFileSync(source, destination);
}
const packageJson = {
name: "@logseq/cli",
version: process.env.CLI_PACKAGE_VERSION ?? rootPackage.version,
packageManager: rootPackage.packageManager,
description: "Logseq CLI",
bin: {
logseq: "dist/logseq.js",
},
engines: rootPackage.engines,
license: "MIT",
repository: {
type: "git",
url: "git+https://github.com/logseq/logseq.git",
directory: ".",
},
keywords: [
"logseq",
"knowledge graph",
"note taking",
"clojurescript",
],
files: packageFiles,
dependencies,
optionalDependencies,
pnpm: {
onlyBuiltDependencies,
},
};
fs.writeFileSync(
path.join(packageRoot, "package.json"),
`${JSON.stringify(packageJson, null, 2)}\n`,
);
console.log(`Prepared ${packageJson.name}@${packageJson.version} in ${packageRoot}`);
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env node
import { promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, "..");
const staticDir = path.join(repoRoot, "static");
const staticJsDir = path.join(staticDir, "js");
const distDir = path.join(repoRoot, "dist");
const skillSourceDir = path.join(repoRoot, ".agents", "skills", "logseq-cli");
const stagedSkillDir = path.join(staticDir, ".agents", "skills", "logseq-cli");
const cliBundleRelativePath = "cli/_build/default/dist/logseq-cli.js";
const stagedCliRelativePath = "static/logseq-cli.js";
const desktopCliRelativePath = "static/js/logseq-cli.js";
const cliBundlePath = path.join(repoRoot, ...cliBundleRelativePath.split("/"));
const copyPairs = [
{
from: path.join(repoRoot, ...stagedCliRelativePath.split("/")),
to: path.join(repoRoot, ...desktopCliRelativePath.split("/")),
generatedFrom: cliBundlePath,
refreshCommand: "pnpm cli:release",
},
{
from: path.join(staticDir, "logseq-cli.js.map"),
to: path.join(staticJsDir, "logseq-cli.js.map"),
optional: true,
},
{
from: path.join(distDir, "db-worker-node.js"),
to: path.join(staticJsDir, "db-worker-node.js"),
generatedFrom: path.join(staticDir, "db-worker-node.js"),
refreshCommand: "pnpm db-worker-node:bundle",
},
{
from: path.join(skillSourceDir, "SKILL.md"),
to: path.join(stagedSkillDir, "SKILL.md"),
},
];
async function exists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
async function copyOne({ from, to, optional = false }) {
if (!(await exists(from))) {
if (optional) return;
throw new Error(`missing required source file: ${from}`);
}
await fs.mkdir(path.dirname(to), { recursive: true });
if (await exists(to)) {
const stats = await fs.stat(to);
await fs.chmod(to, stats.mode | 0o200);
}
await fs.copyFile(from, to);
}
async function assertFreshRuntime({ from, generatedFrom, refreshCommand }) {
if (!generatedFrom || !(await exists(generatedFrom)) || !(await exists(from))) return;
const [sourceStats, generatedStats] = await Promise.all([
fs.stat(from),
fs.stat(generatedFrom),
]);
if (sourceStats.mtimeMs + 1000 < generatedStats.mtimeMs) {
throw new Error(
`${from} is older than ${generatedFrom}; run \`${refreshCommand}\` before preparing desktop runtime JS`
);
}
}
async function main() {
await fs.mkdir(staticJsDir, { recursive: true });
for (const pair of copyPairs) {
await assertFreshRuntime(pair);
await copyOne(pair);
}
// Keep root staged runtime files available for local CLI E2E and npm packaging.
}
main().catch((error) => {
console.error(`[prepare-desktop-runtime-js] ${error.message}`);
process.exit(1);
});
@@ -0,0 +1 @@
{"created-at":1760631833291,"description":"ClojureDocs Data Export","vars":[{"ns":"clojure.core","name":"def","type":"var","see-alsos":[{"created-at":1289040035000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b15"},{"created-at":1289040039000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"fn","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b16"},{"created-at":1289040051000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmacro","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b17"},{"created-at":1289040055000,"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"defmulti","library-url":"https://github.com/clojure/clojure"},"_id":"542692eaf6e94c6970521b18"}],"examples":[{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":"user=\u003E (def my-val 5)\n#'user/my-val\n\nuser=\u003E my-val\n5","created-at":1289040027000,"updated-at":1411962925119,"_id":"542692cfc026201cdc326e95"},{"author":{"login":"boxie","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bfc366066e3c1beee98f3a6666728169?r=PG&default=identicon"},"editors":[],"body":"user=\u003E (def my-function (fn [x] (* x x x)))\n#'user/my-function\nuser=\u003E (my-function 4)\n64","created-at":1289040110000,"updated-at":1289040110000,"_id":"542692cfc026201cdc326e96"},{"author":{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},"editors":[{"login":"puredanger","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/89c8afd032c7b3473f67c9b00d3acd5a?r=PG&default=identicon"},{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},{"login":"pjlegato","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/4ce55cfd8b3ae2f63f5ecbc8fc1c05d4?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; This is an example of setting a docstring during a def.\n;; (Note that the clojure.repl namespace which contains the\n;; doc function is not loaded by default in Emacs' SLIME mode.)\n\nuser\u003E (def ted-nugent \"The nuge rocks\" 123)\n#'user/ted-nugent\nuser\u003E (doc ted-nugent)\n-------------------------\nuser/ted-nugent\n The nuge rocks\nuser\u003E ted-nugent\n123\n","created-at":1300830366000,"updated-at":1411962895678,"_id":"542692cfc026201cdc326e97"},{"author":{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},"editors":[{"login":"jamesqiu","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/bc1268deaa7f2e78fe2b5ea76e6481d8?r=PG&default=identicon"},{"login":"zk","account-source":"github","avatar-url":"https://avatars.githubusercontent.com/u/7194?v=2"}],"body":";; give function another name\nuser=\u003E (def sys-map map)\n\n;; give macro another name\nuser=\u003E (def #^{:macro true} sys-loop #'loop)","created-at":1313515810000,"updated-at":1411962917894,"_id":"542692cfc026201cdc326e9b"}],"notes":null,"arglists":[],"doc":"Creates and interns or locates a global var with the name of symbol and a\nnamespace of the value of the current namespace (*ns*). See\nhttp://clojure.org/special_forms for more information.","library-url":"https://github.com/clojure/clojure","href":"/clojure.core/def"},{"ns":"clojure.core","name":"if","type":"var","see-alsos":[{"created-at":1302510837000,"author":{"login":"Havvy","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/e799a79441c7543be48562403411cd13?r=PG&default=identicon"},"to-var":{"ns":"clojure.core","name":"cond","library-url":"https://github.com/clojure/clojure"},"_id":"542692ebf6e94c6970521e12"},{"created-at":1311797747000,"author":{"login":"OnesimusUnbound","account-source":"clojuredocs","avatar-url":"https://www.gravatar.com/avatar/2fa4c391db0d2d1744cc2cLine truncated
File diff suppressed because it is too large. Load diff
+242
View File
@@ -0,0 +1,242 @@
(ns logseq.libs.sdk-generator
(:refer-clojure :exclude [run!])
(:require [babashka.fs :as fs]
[cheshire.core :as json]
[clojure.string :as string]))
(def default-schema "libs/dist/logseq-sdk-schema.json")
(def default-output-dir "libs/cljs-sdk/src")
(def default-ns-prefix "com.logseq")
(def core-namespace "core")
(def clojure-core-conflict-fns #{"get"})
(defn parse-args
[args]
(loop [opts {}
tokens args]
(if (empty? tokens)
opts
(let [[flag value & more] tokens]
(case flag
"--schema" (recur (assoc opts :schema value) more)
"--out-dir" (recur (assoc opts :out-dir value) more)
"--out" (recur (assoc opts :out-dir value) more)
"--ns-prefix" (recur (assoc opts :ns-prefix value) more)
(throw (ex-info (str "Unknown flag: " flag) {:flag flag})))))))
(defn camel->kebab [s]
(-> s
(string/replace #"([a-z0-9])([A-Z])" "$1-$2")
(string/replace #"([A-Z]+)([A-Z][a-z])" "$1-$2")
(string/lower-case)
(string/replace #"[^a-z0-9]+" "-")
(string/replace #"(^-|-$)" "")))
(defn getter->namespace [ns-prefix getter-name]
(str ns-prefix "." (camel->kebab getter-name)))
(defn getter->interface-name [return-type]
(some->> (re-find #"\.(I[A-Za-z0-9]+)" return-type)
second))
(defn getter->class-name [return-type]
(some->> (re-find #"\.(LSPlugin[A-Za-z0-9]+)" return-type)
second))
(defn format-docstring [doc]
(when (and doc (not (string/blank? doc)))
(str " " (pr-str doc) "\n")))
(defn param->info
[{:keys [name optional rest?] rest-param :rest}]
(let [sym (camel->kebab name)]
{:name name
:sym sym
:optional (boolean optional)
:rest (boolean (or rest-param rest?))}))
(defn emit-rest-binding [{:keys [sym]}]
(let [rest-var (str "rest-" sym)
line (str " " rest-var " (vec " sym ")\n")]
{:binding line
:var rest-var}))
(defn format-param-vector [params]
(str "[" (string/join " " params) "]"))
(defn emit-method-body
[method-name params {:keys [call]}]
(let [rest-param (some #(when (:rest %) %) params)
fixed-params (->> (if rest-param (vec (remove :rest params)) params)
(map :sym))
{:keys [binding var]} (when rest-param (emit-rest-binding rest-param))
rest-lines (if binding [binding] [])
args-expr (if rest-param
(str "(into [" (string/join " " fixed-params) "] " var ")")
(str "[" (string/join " " fixed-params) "]"))]
(str (format " (let [method (aget api-proxy \"%s\")\n" method-name)
(apply str rest-lines)
" args " args-expr "]\n"
" (" call " api-proxy method args)))\n")))
(defn emit-optional-def
[fn-name doc-str params impl-name helpers method-name]
(let [required (take-while (complement :optional) params)
total (count params)
param-syms (map :sym params)
arities (range (count required) (inc total))
header (str "\n(defn " fn-name "\n"
(or doc-str ""))]
(str "\n(defn- " impl-name "\n"
" " (format-param-vector param-syms) "\n"
(emit-method-body method-name params helpers)
header
(apply str
(map-indexed
(fn [idx arity]
(let [provided (take arity param-syms)
missing (- total arity)
call-args (concat provided (repeat missing "nil"))
param-vector (format-param-vector provided)
call-arg-str (string/join " " call-args)
call-arg-str (if (string/blank? call-arg-str) "" (str " " call-arg-str))]
(str " (" param-vector "\n"
" (" impl-name call-arg-str "))"
(when (not= (inc idx) (count arities))
"\n"))))
arities))
")\n")))
(defn emit-method
[{:keys [name documentation signatures]}
helpers]
(let [{:keys [parameters]} (apply max-key #(count (:parameters %)) signatures)
params (map param->info parameters)
fn-name (camel->kebab name)
doc-str (format-docstring documentation)
rest-param (some #(when (:rest %) %) params)
optional-params (filter :optional params)
impl-name (str fn-name "-impl")
method-body (emit-method-body name params helpers)]
(when-not (string/starts-with? name "_") ; system methods
(cond
rest-param
(let [fixed-syms (map :sym (vec (remove :rest params)))
param-vector (format-param-vector (concat fixed-syms ["&" (:sym rest-param)]))]
(str "\n(defn " fn-name "\n"
(or doc-str "")
" " param-vector "\n"
method-body))
(seq optional-params)
(emit-optional-def fn-name doc-str params impl-name helpers name)
:else
(let [param-vector (format-param-vector (map :sym params))]
(str "\n(defn " fn-name "\n"
(or doc-str "")
" " param-vector "\n"
method-body))))))
(defn emit-core-namespace
[ns-prefix {api-methods :methods}]
(let [ns (str ns-prefix "." core-namespace)
header (str ";; Auto-generated via `bb libs:generate-cljs-sdk`\n"
"(ns " ns "\n"
" (:require [\"@logseq/libs\"]
[cljs-bean.core :as bean]
[com.logseq.util :as util]))\n\n"
"(defn- normalize-result [result]\n"
" (if (instance? js/Promise result)\n"
" (.then result (fn [value] (normalize-result value)))\n"
" (util/->clj-tagged result)))\n\n"
"(defn call-method [owner method args]
(when-not method
(throw (js/Error. \"Missing method on logseq namespace\")))
(normalize-result (.apply method owner (bean/->js args))))\n")
helpers {:call "call-method"}
owner "\n(def api-proxy js/logseq)\n"
methods-str (->> api-methods
(map #(emit-method % helpers))
(apply str))]
[ns (str header owner methods-str)]))
(defn emit-getter-namespace
[ns-prefix getter-name api]
(let [ns (getter->namespace ns-prefix getter-name)
owner-expr (format "(aget js/logseq \"%s\")" getter-name)
excluded-core-fns (->> (:methods api)
(map (comp camel->kebab :name))
(filter clojure-core-conflict-fns)
distinct)
header (str ";; Auto-generated via `bb libs:generate-cljs-sdk`\n"
"(ns " ns "\n"
(when (seq excluded-core-fns)
(str " (:refer-clojure :exclude [" (string/join " " excluded-core-fns) "])\n"))
" (:require [com.logseq.core :as core]))\n")
helpers {:call "core/call-method"}
owner (format "\n(def api-proxy %s)\n" owner-expr)
methods-str (->> (:methods api)
(keep #(emit-method % helpers))
(apply str))]
(when-not (string/blank? methods-str)
[ns (str header owner methods-str)])))
(defn namespace->file
[out-dir ns]
(let [parts (string/split ns #"\.")
dir-parts (butlast parts)
file-name (str (last parts) ".cljs")]
(apply fs/path out-dir (concat dir-parts [file-name]))))
(defn ensure-schema! [schema-path]
(when-not (fs/exists? schema-path)
(throw (ex-info (str "Schema not found, run `pnpm --dir libs generate:schema` first: " schema-path)
{:schema schema-path}))))
(defn write-namespaces!
[out-dir namespaces]
(doseq [[ns content] namespaces]
(when ns
(let [file (namespace->file out-dir ns)]
(fs/create-dirs (fs/parent file))
(spit (str file) content)
(println "Generated" (str file))))))
(defn run!
([] (run! {}))
([opts]
(let [schema-path (fs/absolutize (or (:schema opts) default-schema))
out-dir (fs/absolutize (or (:out-dir opts) default-output-dir))
ns-prefix (or (:ns-prefix opts) default-ns-prefix)]
(ensure-schema! schema-path)
(let [schema (json/parse-string (slurp (str schema-path)) true)
interfaces (:interfaces schema)
classes (:classes schema)
ls-user (get-in schema [:classes :LSPluginUser])
_ (when-not ls-user
(throw (ex-info "Missing LSPluginUser metadata in schema" {:schema schema-path})))
getters (:getters ls-user)
modules (->> getters
(remove #(= "Utils" (:name %)))
(keep (fn [{:keys [name returnType]}]
(let [iface-key (some-> (getter->interface-name returnType) keyword)
class-key (some-> (getter->class-name returnType) keyword)
api (or (get interfaces iface-key)
(get classes class-key))]
(when api
{:getter-name name
:api api}))))
distinct)
proxies (keep (fn [{:keys [getter-name api]}]
(emit-getter-namespace ns-prefix getter-name api))
modules)
core (emit-core-namespace ns-prefix ls-user)
namespaces (cons core proxies)]
(fs/create-dirs out-dir)
(write-namespaces! out-dir namespaces)
out-dir))))
(defn -main [& args]
(let [opts (parse-args args)]
(run! opts)))
@@ -0,0 +1,15 @@
(ns logseq.tasks.common-errors
"Task to use AI to detect common errors"
(:require [babashka.fs :as fs]
[babashka.process :refer [shell]]
[clojure.string :as string]))
(defn check-common-errors
[]
(let [prompt (String. (fs/read-all-bytes "prompts/review.md"))
diff (:out (shell {:out :string :shutdown nil} "git diff --no-prefix -U100 -- '*.cljs'"))]
(when-not (string/blank? diff)
(let [command (format "gh models run openai/gpt-5 \"%s\""
(str prompt
(format "\n\n <diff>%s</diff>" diff)))]
(shell {:shutdown nil} command)))))
@@ -0,0 +1,287 @@
(ns logseq.tasks.db-graph.create-graph-with-clojure-irc-history
"Import local #clojure IRC log HTML pages into a Logseq DB graph."
(:require ["fs" :as fs]
["path" :as node-path]
[babashka.cli :as cli]
[clojure.string :as string]
[datascript.core :as d]
[logseq.db.common.sqlite-cli :as sqlite-cli]
[logseq.outliner.cli :as outliner-cli]
[nbb.classpath :as cp]
[nbb.core :as nbb]))
(def ^:private default-base-url "https://chouser.us/clojure-log/")
(def ^:private default-source-dir
(or (.. js/process -env -CLOJURE_LOG_SOURCE_DIR)
"/Users/tiensonqin/Codes/projects/clojure-irc-history"))
(def spec
"Options spec"
{:help {:alias :h
:desc "Print help"}
:base-url {:alias :u
:default default-base-url
:desc "Base URL for log pages"}
:source-dir {:alias :m
:default default-source-dir
:desc "Local mirror root or clojure-log directory containing index.html and year folders"}
:limit-days {:alias :l
:desc "Maximum number of day pages to import"}
:batch-days {:alias :b
:default 200
:desc "Number of day pages transacted per batch"}
:verbose {:alias :v
:desc "Verbose mode"}})
(def ^:private html-entity-map
{"&quot;" "\""
"&amp;" "&"
"&lt;" "<"
"&gt;" ">"
"&apos;" "'"
"&#39;" "'"
"&nbsp;" " "})
(defn- parse-long-option
[value]
(if (string? value)
(js/parseInt value 10)
value))
(defn- normalize-base-url
[base-url]
(if (string/ends-with? base-url "/")
base-url
(str base-url "/")))
(defn- normalize-options
[options]
(-> options
(update :limit-days parse-long-option)
(update :batch-days parse-long-option)
(update :base-url normalize-base-url)))
(defn parse-args
[args]
{:graph-dir (first args)
:options (normalize-options (cli/parse-opts (rest args) {:spec spec}))})
(defn- decode-html-entity
[entity]
(or (html-entity-map entity)
(when-let [[_ code] (re-matches #"&#(\d+);" entity)]
(js/String.fromCodePoint (js/parseInt code 10)))
(when-let [[_ code] (re-matches #"&#x([0-9a-fA-F]+);" entity)]
(js/String.fromCodePoint (js/parseInt code 16)))
entity))
(defn- decode-html-entities
[s]
(string/replace s #"&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z]+);" decode-html-entity))
(defn- strip-html
[s]
(-> s
(string/replace #"(?is)<a[^>]*>(.*?)</a>" "$1")
(string/replace #"(?is)<[^>]+>" "")
decode-html-entities
string/trim))
(defn extract-day-paths
[index-html]
(->> (re-seq #"href=\"((\d{4})/\2-\d{2}-\d{2}\.html)\"" index-html)
(map second)
distinct
sort
vec))
(defn- day-path->date
[day-path]
(some-> (re-find #"\d{4}-\d{2}-\d{2}" day-path)
str))
(defn select-day-paths
[day-paths {:keys [limit-days]}]
(->> day-paths
(take (or limit-days js/Number.MAX_SAFE_INTEGER))
vec))
(defn- date->journal-day
[date]
(some-> date
(string/replace "-" "")
(js/parseInt 10)))
(defn extract-chat-rows
[day-html]
(->> (re-seq #"(?s)<tr[^>]*>\s*<td><a[^>]*>([^<]+)</a></td><td[^>]*>(.*?)</td><td>(.*?)</td></tr>" day-html)
(map (fn [[_ time nick-html message-html]]
{:time (string/trim time)
:nick (strip-html nick-html)
:message (strip-html message-html)}))
vec))
(defn date-time->timestamp-ms
[date time]
(let [[_ year month day] (re-matches #"(\d{4})-(\d{2})-(\d{2})" date)
[_ hour minute] (re-matches #"(\d{1,2}):(\d{2})" time)]
(when (and year month day hour minute)
(js/Date.UTC (js/parseInt year 10)
(dec (js/parseInt month 10))
(js/parseInt day 10)
(js/parseInt hour 10)
(js/parseInt minute 10)
0
0))))
(defn build-user-pages
[user->uuid]
(->> user->uuid
(sort-by key)
(mapv (fn [[user-name user-uuid]]
{:page {:block/uuid user-uuid
:build/keep-uuid? true
:block/title user-name
:build/properties {:logseq.property.user/name user-name}}
:blocks []}))))
(defn build-page-and-blocks
[{:keys [date day-path base-url user->uuid chat-rows]}]
{:page {:build/journal (date->journal-day date)}
:blocks
(mapv (fn [{:keys [time nick message]}]
(let [timestamp (date-time->timestamp-ms date time)
user-uuid (get user->uuid nick)]
{:block/title (str time " " nick ": " message)
:block/created-at timestamp
:block/updated-at timestamp
:build/properties {:logseq.property/created-by-ref [:block/uuid user-uuid]}}))
chat-rows)})
(defn- extract-day-date
[day-html day-path]
(or (some-> (re-find #"<p class=\"dh\">([^<]+)</p>" day-html)
second)
(day-path->date day-path)))
(defn- read-text-file
[path]
(str (fs/readFileSync path "utf8")))
(defn- error-message
[error]
(or (ex-message error)
(some-> error .-message)
(str error)))
(defn resolve-source-dir
[source-dir]
(let [candidates [source-dir
(node-path/join source-dir "clojure-log")
(node-path/join source-dir "chouser.github.io-master" "clojure-log")]
found (some (fn [candidate]
(when (fs/existsSync (node-path/join candidate "index.html"))
candidate))
candidates)]
(or found
(throw (ex-info (str "Could not find clojure-log source directory from: " source-dir)
{:source-dir source-dir
:candidates candidates})))))
(defn- fetch-day-page-data
[base-url day-path day-html]
(let [day-url (str base-url day-path)
date (extract-day-date day-html day-path)
chat-rows (extract-chat-rows day-html)]
{:date date
:day-path day-path
:base-url base-url
:chat-rows chat-rows}))
(defn- load-source-day-page-data
[base-url source-dir day-path]
(fetch-day-page-data base-url
day-path
(read-text-file (node-path/join source-dir day-path))))
(defn- ensure-user!
[user->uuid* new-users* user-name]
(if-let [user-uuid (get @user->uuid* user-name)]
user-uuid
(let [user-uuid (random-uuid)]
(swap! user->uuid* assoc user-name user-uuid)
(swap! new-users* conj user-name)
user-uuid)))
(defn- transact-batch!
[conn pages-and-blocks]
(let [{:keys [init-tx block-props-tx]}
(outliner-cli/build-blocks-tx {:pages-and-blocks pages-and-blocks})]
(d/transact! conn init-tx)
(when (seq block-props-tx)
(d/transact! conn block-props-tx))))
(defn -main [args]
(let [{:keys [graph-dir options]} (parse-args args)
_ (when (or (nil? graph-dir) (:help options))
(println (str "Usage: $0 GRAPH-NAME [OPTIONS]\nOptions:\n"
(cli/format-opts {:spec spec})))
(js/process.exit 1))
{:keys [base-url source-dir batch-days verbose]} options
resolved-source-dir (resolve-source-dir source-dir)
index-html (read-text-file (node-path/join resolved-source-dir "index.html"))
all-day-paths (extract-day-paths index-html)
selected-day-paths (select-day-paths all-day-paths options)
init-conn-args (sqlite-cli/->open-db-args graph-dir)
db-name (if (= 1 (count init-conn-args))
(first init-conn-args)
(second init-conn-args))
conn (apply outliner-cli/init-conn
(conj init-conn-args {:classpath (cp/get-classpath)}))
total-day-count (count selected-day-paths)
total-batches (js/Math.ceil (/ total-day-count batch-days))
user->uuid* (atom {})
imported-stats (atom {:days 0 :messages 0})]
(println "Found" (count all-day-paths) "day pages in index")
(println "Using source directory:" resolved-source-dir)
(println "Importing" total-day-count "day pages to graph" (str "'" db-name "'")
"in" total-batches "batch(es)")
(doseq [[batch-index day-path-batch] (map-indexed vector (partition-all batch-days selected-day-paths))]
(println "Processing batch" (inc batch-index) "of" total-batches
"with" (count day-path-batch) "day pages")
(let [new-users* (atom #{})
day-pages-and-blocks
(->> day-path-batch
(map (fn [day-path]
(try
(when verbose
(println "Loading source log" day-path "..."))
(let [day-page-data (load-source-day-page-data base-url resolved-source-dir day-path)
_ (doseq [{:keys [nick]} (:chat-rows day-page-data)]
(ensure-user! user->uuid* new-users* nick))]
(when (seq (:chat-rows day-page-data))
(build-page-and-blocks (assoc day-page-data
:user->uuid @user->uuid*))))
(catch :default e
(println "Skipping" day-path ":" (error-message e))
nil))))
(remove nil?)
vec)
new-user-pages-and-blocks (build-user-pages (select-keys @user->uuid* @new-users*))
pages-and-blocks (vec (concat new-user-pages-and-blocks day-pages-and-blocks))]
(swap! imported-stats
(fn [{:keys [days messages]}]
{:days (+ days (count day-pages-and-blocks))
:messages (+ messages
(reduce
(fn [acc {:keys [blocks]}]
(+ acc (count blocks)))
0
day-pages-and-blocks))}))
(when (seq pages-and-blocks)
(transact-batch! conn pages-and-blocks))))
(let [{:keys [days messages]} @imported-stats]
(println "Imported" days "pages and" messages "chat messages into graph" (str "'" db-name "'") "."))))
(when (= nbb/*file* (nbb/invoked-file))
(-main *command-line-args*))
@@ -0,0 +1,200 @@
(ns logseq.tasks.db-graph.create-graph-with-clojuredocs
"Script that convert clojuredocs-export.json into logseq graph data."
(:require ["fs" :as fs]
[babashka.cli :as cli]
[cljs.pprint :as pp]
[clojure.edn :as edn]
[clojure.string :as string]
[datascript.core :as d]
[logseq.db.common.sqlite-cli :as sqlite-cli]
[logseq.outliner.cli :as outliner-cli]
[nbb.classpath :as cp]
[nbb.core :as nbb]))
(def spec
"Options spec"
{:help {:alias :h
:desc "Print help"}
:config {:alias :c
:coerce edn/read-string
:desc "EDN map to add to config.edn"}
:export {:alias :e
:desc "Exports graph to clojuredocs.edn"}
:verbose {:alias :v
:desc "Verbose mode"}})
(defn example=>block
[author->block-uuid example]
(when-let [body (:body example)]
(let [author-block-uuid (author->block-uuid (:login (:author example)))]
{:block/title body
:build/tags [:logseq.class/Code-block]
:build/properties (cond-> {:logseq.property.node/display-type :code
:logseq.property.code/lang "Clojure"}
author-block-uuid
(assoc :user.property/author-X_lTJqwD [:block/uuid author-block-uuid]))})))
(defn convert-var-to-page
[type->block-uuid author->block-uuid
{:keys [ns name type see-alsos examples notes arglists doc library-url] :as _clj-var}]
{:page
{:build/properties
{:user.property/library-url-ip8W5T7M library-url
:user.property/type-Un-Aypix
[:block/uuid (type->block-uuid type)]},
:block/title (str "`" name "` (" ns ")")}
:blocks
[{:block/title "Doc",
:build/properties {:logseq.property/heading 3},
:build/children
(mapv
(fn [line]
{:block/title line
:build/properties {}})
(string/split-lines doc))}
{:block/title "Examples",
:build/properties {:logseq.property/heading 3},
:build/children
(vec (keep (partial example=>block author->block-uuid) examples))}
{:block/title "Notes",
:build/properties {:logseq.property/heading 3}
:build/children
(mapv
(fn [note]
(let [body (or (:body note) "")
author-block-uuid (author->block-uuid (:login (:author note)))]
{:block/title body
:build/tags [:logseq.class/Quote-block]
:build/properties (cond-> {:logseq.property.node/display-type :quote}
author-block-uuid
(assoc :user.property/author-X_lTJqwD [:block/uuid author-block-uuid]))}))
notes)}
{:block/title "Arglists",
:build/properties {:logseq.property/heading 3}
:build/children
(vec
(when-let [arglists-content (with-out-str (pp/pprint arglists))]
[{:block/title arglists-content
:build/tags [:logseq.class/Code-block]
:build/properties {:logseq.property.node/display-type :code
:logseq.property.code/lang "Clojure"}}]))}
;; {:block/title "See also",
;; :build/properties {:logseq.property/heading 3}
;; :build/children
;; (vec
;; (when-let [arglists-content (with-out-str (pp/pprint see-alsos))]
;; [{:block/title arglists-content
;; :build/tags [:logseq.class/Code-block]
;; :build/properties {:logseq.property.node/display-type :code
;; :logseq.property.code/lang "Clojure"}}]))}
]})
(defn convert-type-pages
"return {:pages ..., :type->block-uuid ...}"
[clj-vars]
(let [all-types (set (map :type clj-vars))
type->block-uuid
(into {} (map (fn [tp] [tp (random-uuid)])) all-types)
pages
(map
(fn [[tp block-uuid]]
{:page
{:block/uuid block-uuid
:build/keep-uuid? true
:block/title tp},
:blocks
[]})
type->block-uuid)]
{:pages pages :type->block-uuid type->block-uuid}))
(defn convert-author-pages
"return {:pages ..., :author->block-uuid ...}"
[clj-vars]
(let [author-name (comp :login :author)
author-names
(set
(mapcat
(fn [clj-var]
(set
(map
author-name
(concat (:see-alsos clj-var)
(:examples clj-var)
(:notes clj-var)))))
clj-vars))
author->block-uuid
(into {} (map (fn [author] [author (random-uuid)])) author-names)
pages
(map
(fn [[author block-uuid]]
{:page
{:block/uuid block-uuid
:build/keep-uuid? true
:block/title author}
:blocks
[]})
author->block-uuid)]
{:pages pages :author->block-uuid author->block-uuid}))
(def properties
{:user.property/type-Un-Aypix
{:logseq.property/type :node,
:block/title "type",
:db/cardinality :db.cardinality/one},
:user.property/library-url-ip8W5T7M
{:db/cardinality :db.cardinality/one,
:logseq.property/type :url,
:block/title "library-url"}
:user.property/author-X_lTJqwD
{:logseq.property/type :node
:block/title "author"
:db/cardinality :db.cardinality/one}})
(defn convert
[clj-vars]
(let [{type-pages :pages type->block-uuid :type->block-uuid} (convert-type-pages clj-vars)
{author-pages :pages author->block-uuid :author->block-uuid} (convert-author-pages clj-vars)]
{:properties properties
:classes {}
:pages-and-blocks
(vec
(concat
type-pages
author-pages
(map (partial convert-var-to-page type->block-uuid author->block-uuid) clj-vars)))}))
(comment
(def clojuredocs-json (js->clj (js/JSON.parse (fs/readFileSync "resources/clojuredocs-export.json"))
:keywordize-keys true))
(def result (convert (filter #(= "clojure.core" (:ns %)) (:vars clojuredocs-json))))
(fs/writeFileSync "cljdocs.edn" (with-out-str (pp/pprint result))))
(defn -main [args]
(let [[graph-dir] args
options (cli/parse-opts args {:spec spec})
_ (when (or (nil? graph-dir) (:help options))
(println (str "Usage: $0 GRAPH-NAME [OPTIONS]\nOptions:\n"
(cli/format-opts {:spec spec})))
(js/process.exit 1))
init-conn-args (sqlite-cli/->open-db-args graph-dir)
db-name (if (= 1 (count init-conn-args)) (first init-conn-args) (second init-conn-args))
conn (apply outliner-cli/init-conn
(conj init-conn-args {:additional-config (:config options)
:classpath (cp/get-classpath)}))
clojuredocs-json (js->clj (js/JSON.parse (fs/readFileSync "resources/clojuredocs-export.json"))
:keywordize-keys true)
clj-vars (:vars clojuredocs-json)
result-edn (convert clj-vars)]
(println "Generating" (count (:pages-and-blocks result-edn)) "pages")
(if (:export options)
(do (println "Generating clojuredocs.edn ...")
(fs/writeFileSync "clojuredocs.edn" (with-out-str (pp/pprint result-edn))))
(do (println "Transacting to graph ...")
(let [{:keys [init-tx block-props-tx]} (outliner-cli/build-blocks-tx result-edn)]
(d/transact! conn init-tx)
(d/transact! conn block-props-tx)
(println "Transacted" (count (d/datoms @conn :eavt)) "datoms")
(println "Created graph " (str "'" db-name "'") "!"))))))
(when (= nbb/*file* (nbb/invoked-file))
(-main *command-line-args*))
@@ -0,0 +1,142 @@
(ns logseq.tasks.db-graph.create-graph-with-large-sizes
"Script that generates graphs at large sizes"
(:require ["os" :as os]
["path" :as node-path]
[babashka.cli :as cli]
[clojure.string :as string]
[datascript.core :as d]
[logseq.outliner.cli :as outliner-cli]
[nbb.classpath :as cp]
[nbb.core :as nbb]))
(def ^:private target-entities-per-batch 25000)
(def ^:private max-pages-per-batch 1000)
(def ^:private min-block-title-length 24)
(def ^:private max-block-title-length 256)
(def ^:private block-title-fragment
"captures project updates, implementation details, follow-up notes, and review context ")
(defn- parse-long-option
[value]
(if (string? value)
(js/parseInt value 10)
value))
(defn- normalize-options
[options]
(update-vals options parse-long-option))
(defn default-batch-pages
[blocks-per-page]
(-> (quot target-entities-per-batch (max 1 (inc blocks-per-page)))
(max 1)
(min max-pages-per-batch)))
(defn- build-block-title
[page-idx block-idx]
(let [target-length (+ min-block-title-length
(mod (+ (* page-idx 17) (* block-idx 31))
(inc (- max-block-title-length min-block-title-length))))
prefix (str "Page " page-idx " block " block-idx " summary ")
raw-title (str prefix
(apply str (repeat (inc (quot target-length (count block-title-fragment)))
block-title-fragment)))]
(subs raw-title 0 target-length)))
(defn- build-blocks
[page-idx blocks-per-page next-id]
(loop [block-idx 0
blocks (transient [])]
(if (= block-idx blocks-per-page)
(persistent! blocks)
(recur (inc block-idx)
(conj! blocks
{:block/uuid (next-id)
:block/title (build-block-title page-idx block-idx)})))))
(defn build-page-and-blocks-batch
([start-idx page-count blocks-per-page]
(build-page-and-blocks-batch start-idx page-count blocks-per-page random-uuid))
([start-idx page-count blocks-per-page next-id]
(loop [page-idx 0
pages-and-blocks (transient [])]
(if (= page-idx page-count)
(persistent! pages-and-blocks)
(recur (inc page-idx)
(conj! pages-and-blocks
{:page {:block/uuid (next-id)
:block/title (str "Page-" (+ start-idx page-idx))}
:blocks (build-blocks (+ start-idx page-idx) blocks-per-page next-id)}))))))
(defn page-and-block-batches
([{:keys [pages blocks batch-pages]}]
(page-and-block-batches {:pages pages
:blocks blocks
:batch-pages batch-pages}
random-uuid))
([{:keys [pages blocks batch-pages]} next-id]
(let [batch-pages' (or batch-pages (default-batch-pages blocks))]
((fn step [start-idx]
(lazy-seq
(when (< start-idx pages)
(cons (build-page-and-blocks-batch start-idx
(min batch-pages' (- pages start-idx))
blocks
next-id)
(step (+ start-idx batch-pages'))))))
0))))
(defn- transact-batch!
[conn pages-and-blocks]
(let [{:keys [init-tx block-props-tx]} (outliner-cli/build-blocks-tx {:pages-and-blocks pages-and-blocks})]
(d/transact! conn init-tx)
(when (seq block-props-tx)
(d/transact! conn block-props-tx))))
(defn- total-batches
[{:keys [pages blocks batch-pages]}]
(let [batch-pages' (or batch-pages (default-batch-pages blocks))]
(js/Math.ceil (/ pages batch-pages'))))
(def spec
"Options spec"
{:help {:alias :h
:desc "Print help"}
:pages {:alias :p
:default 1000
:desc "Number of pages to create"}
:blocks {:alias :b
:default 20
:desc "Number of blocks to create per page"}
:batch-pages {:alias :t
:desc "Number of pages to build and transact per batch"}})
(defn parse-args
[args]
{:graph-dir (first args)
:options (normalize-options (cli/parse-opts (rest args) {:spec spec}))})
(defn -main [args]
(let [{:keys [graph-dir options]} (parse-args args)
_ (when (or (nil? graph-dir) (:help options))
(println (str "Usage: $0 GRAPH-NAME [OPTIONS]\nOptions:\n"
(cli/format-opts {:spec spec})))
(js/process.exit 1))
{:keys [pages blocks batch-pages]} options
[dir db-name] (if (string/includes? graph-dir "/")
((juxt node-path/dirname node-path/basename) graph-dir)
[(node-path/join (os/homedir) "logseq" "graphs") graph-dir])
conn (outliner-cli/init-conn dir db-name {:classpath (cp/get-classpath)})
total-batches' (total-batches options)
pages-per-batch (or batch-pages (default-batch-pages blocks))
total-blocks (* pages blocks)]
(println "Creating graph with" pages "pages and" total-blocks "blocks"
"using" total-batches' "batch(es) of up to" pages-per-batch "pages ...")
(doseq [[batch-num pages-and-blocks] (map-indexed vector (page-and-block-batches options))]
(println "Transacting batch" (inc batch-num) "of" total-batches'
"with" (count pages-and-blocks) "pages")
(transact-batch! conn pages-and-blocks))
(println "Created graph" db-name "with" pages "pages and" total-blocks "blocks.")))
(when (= nbb/*file* (nbb/invoked-file))
(-main *command-line-args*))
@@ -0,0 +1,237 @@
(ns logseq.tasks.db-graph.create-graph-with-properties
"Script that generates all the permutations of property types and cardinality.
Also creates a page of queries that exercises most properties
NOTE: This script is also used in CI to confirm graph creation works"
(:require ["fs" :as fs]
["fs-extra$default" :as fse]
["path" :as node-path]
[babashka.cli :as cli]
[cljs.pprint :as pprint]
[clojure.edn :as edn]
[clojure.set :as set]
[clojure.string :as string]
[datascript.core :as d]
[logseq.common.util :as common-util]
[logseq.common.util.date-time :as date-time-util]
[logseq.common.util.page-ref :as page-ref]
[logseq.db.common.sqlite-cli :as sqlite-cli]
[logseq.db.frontend.property.type :as db-property-type]
[logseq.outliner.cli :as outliner-cli]
[nbb.classpath :as cp]
[nbb.core :as nbb]))
(defn- date-journal-title [date]
(date-time-util/int->journal-title (date-time-util/date->int date) "MMM do, yyyy"))
(defn- subtract-days
[date days]
(new js/Date (- (.getTime date) (* days 24 60 60 1000))))
(defn- build-closed-values-config
[]
{:default-closed
(mapv #(hash-map :value %
:uuid (random-uuid)
:icon {:id % :type :emoji})
["joy" "sob" "upside_down_face"])
:url-closed
(mapv #(hash-map :value %
:uuid (random-uuid))
["https://logseq.com" "https://docs.logseq.com" "https://github.com/logseq/logseq"])
:number-closed
(mapv #(hash-map :value %
:uuid (random-uuid))
[10 42 (rand 100)])})
(defn- query [query-string]
{:block/title query-string
:build/properties {:logseq.property/query query-string}
:block/tags [{:db/ident :logseq.class/Query}]})
(defn- create-init-data
[]
(let [today (new js/Date)
yesterday (subtract-days today 1)
[today-int yesterday-int] (map date-time-util/date->int [today yesterday])
two-days-ago (subtract-days today 2)
closed-values-config (build-closed-values-config)
;; Stores random closed values for use with queries
closed-values (atom {})
random-closed-value #(let [val (-> closed-values-config % rand-nth)]
(swap! closed-values assoc % val)
[:block/uuid (:uuid val)])
object-uuid (random-uuid)
get-closed-value #(:value (get @closed-values %))
get-closed-value-ref #(vector :block/uuid (:uuid (get @closed-values %)))
timestamp (common-util/time-ms)]
{:pages-and-blocks
(vec
(concat
;; Page property values needs to be before b/c they are referenced by everything else
[{:page {:block/title "Page 1"}}]
;; Objects
[{:page {:block/title "Page object"
:build/tags [:TestClass]}}
{:page {:block/title "Blocks"}
:blocks
[{:block/title "block object"
:block/uuid object-uuid
:build/tags [:TestClass]}]}]
;; Journals
[{:page
{:build/journal today-int}
:blocks
[{:block/title "[[Block Properties]]"}
{:block/title "[[Property Queries]]"}
{:block/title "[[Has Property Queries]]"}]}
{:page {:build/journal yesterday-int}}
{:page {:build/journal (date-time-util/date->int two-days-ago)}}
;; Block property blocks and queries
{:page {:block/title "Block Properties"
:build/properties
{:logseq.property/description "This page demonstrates all the combinations of property types and single/multiple values that are possible."}}
:blocks
[{:block/title "default property block" :build/properties {:default "haha"}}
{:block/title "default property block" :build/properties {:default-many #{"yee" "haw" "sir"}}}
{:block/title "default-closed property block" :build/properties {:default-closed (random-closed-value :default-closed)}}
{:block/title "url property block" :build/properties {:url "https://logseq.com"}}
{:block/title "url-many property block" :build/properties {:url-many #{"https://logseq.com" "https://docs.logseq.com"}}}
{:block/title "url-closed property block" :build/properties {:url-closed (random-closed-value :url-closed)}}
{:block/title "checkbox property block" :build/properties {:checkbox true}}
{:block/title "number property block" :build/properties {:number 5}}
{:block/title "number-many property block" :build/properties {:number-many #{5 10}}}
{:block/title "number-closed property block" :build/properties {:number-closed (random-closed-value :number-closed)}}
{:block/title "node property block" :build/properties {:node [:block/uuid object-uuid]}}
{:block/title "node without classes property block" :build/properties {:node-without-classes [:build/page {:block/title "Page 1"}]}}
{:block/title "node-many property block" :build/properties {:node-many #{[:block/uuid object-uuid] [:build/page {:block/title "Page object"}]}}}
{:block/title "date property block" :build/properties {:date [:build/page {:build/journal today-int}]}}
{:block/title "date-many property block" :build/properties {:date-many #{[:build/page {:build/journal today-int}]
[:build/page {:build/journal yesterday-int}]}}}
{:block/title "datetime property block" :build/properties {:datetime timestamp}}]}
{:page {:block/title "Property Queries"
:build/properties
{:logseq.property/description "This page demonstrates all property type combinations being queried for a specific value. There should be 2 results for each query, one block and one page."}}
:blocks
[(query "(property default \"haha\")")
(query "(property default-many \"haw\")")
(query (str "(property default-closed " (pr-str (get-closed-value :default-closed)) ")"))
(query "(property url \"https://logseq.com\")")
(query "(property url-many \"https://logseq.com\")")
(query (str "(property url-closed " (pr-str (get-closed-value :url-closed)) ")"))
(query "(property checkbox true)")
(query "(property number 5)")
(query "(property number-many 10)")
(query (str "(property number-closed " (pr-str (get-closed-value :number-closed)) ")"))
(query "(property node \"block object\")")
(query "(property node-without-classes [[Page 1]])")
(query "(property node-many [[Page object]])")
(query (str "(property date " (page-ref/->page-ref (string/capitalize (date-journal-title today))) ")"))
(query (str "(property date-many " (page-ref/->page-ref (string/capitalize (date-journal-title yesterday))) ")"))
(query (str "(property datetime " timestamp ")"))]}
;; Page property pages and queries
{:page {:block/title "default page" :build/properties {:default "haha"}}}
{:page {:block/title "default-many page" :build/properties {:default-many #{"yee" "haw" "sir"}}}}
{:page {:block/title "default-closed page" :build/properties {:default-closed (get-closed-value-ref :default-closed)}}}
{:page {:block/title "url page" :build/properties {:url "https://logseq.com"}}}
{:page {:block/title "url-many page" :build/properties {:url-many #{"https://logseq.com" "https://docs.logseq.com"}}}}
{:page {:block/title "url-closed page" :build/properties {:url-closed (get-closed-value-ref :url-closed)}}}
{:page {:block/title "checkbox page" :build/properties {:checkbox true}}}
{:page {:block/title "number page" :build/properties {:number 5}}}
{:page {:block/title "number-many page" :build/properties {:number-many #{5 10}}}}
{:page {:block/title "number-closed page" :build/properties {:number-closed (get-closed-value-ref :number-closed)}}}
{:page {:block/title "node page" :build/properties {:node [:block/uuid object-uuid]}}}
{:page {:block/title "node without classes page" :build/properties {:node-without-classes [:build/page {:block/title "Page 1"}]}}}
{:page {:block/title "node-many page" :build/properties {:node-many #{[:block/uuid object-uuid] [:build/page {:block/title "Page object"}]}}}}
{:page {:block/title "date page" :build/properties {:date [:build/page {:build/journal today-int}]}}}
{:page {:block/title "date-many page" :build/properties {:date-many #{[:build/page {:build/journal today-int}]
[:build/page {:build/journal yesterday-int}]}}}}
{:page {:block/title "datetime page" :build/properties {:datetime timestamp}}}
{:page {:block/title "Has Property Queries"
:build/properties
{:logseq.property/description "This page demonstrates all property type combinations being queried for having a specific property. There should be 2 results for each query, one block and one page."}}
:blocks
[(query "(property default)")
(query "(property default-many)")
(query "(property default-closed)")
(query "(property url)")
(query "(property url-many)")
(query "(property url-closed)")
(query "(property checkbox)")
(query "(property number)")
(query "(property number-many)")
(query "(property number-closed)")
(query "(property node)")
(query "(property node-without-classes)")
(query "(property node-many)")
(query "(property date)")
(query "(property date-many)")
(query "(property datetime)")]}]))
:classes {:TestClass {}}
;; Properties
:properties
(->> db-property-type/user-built-in-property-types
(mapcat #(cond-> (if (= :node %)
[[% {:logseq.property/type % :build/property-classes [:TestClass]}]
[:node-without-classes {:logseq.property/type %}]]
[[% {:logseq.property/type %}]])
(contains? db-property-type/cardinality-property-types %)
(conj [(keyword (str (name %) "-many"))
(cond-> {:logseq.property/type %
:db/cardinality :many}
(= :node %)
(assoc :build/property-classes [:TestClass]))])))
(into (mapv #(vector (keyword (str (name %) "-closed"))
{:logseq.property/type %
:build/closed-values (closed-values-config (keyword (str (name %) "-closed")))})
[:default :url :number]))
(into {}))}))
(def spec
"Options spec"
{:help {:alias :h
:desc "Print help"}
:file {:alias :f
:desc "File to save generated sqlite.build EDN"}
:config {:alias :c
:coerce edn/read-string
:desc "EDN map to add to config.edn"}})
(defn -main [args]
(let [graph-dir (first args)
options (cli/parse-opts args {:spec spec})
_ (when (or (nil? graph-dir) (:help options))
(println (str "Usage: $0 GRAPH-NAME [OPTIONS]\nOptions:\n"
(cli/format-opts {:spec spec})))
(js/process.exit 1))
init-conn-args (sqlite-cli/->open-db-args graph-dir)
db-name (if (= 1 (count init-conn-args)) (first init-conn-args) (second init-conn-args))
db-path (apply node-path/join init-conn-args)
;; Only remove the directory if the directory is being overwritten
_ (when (and (= 2 (count init-conn-args)) (fs/existsSync db-path))
(fse/removeSync db-path))
conn (apply outliner-cli/init-conn
(conj init-conn-args {:additional-config (:config options)
:classpath (cp/get-classpath)}))
init-data (create-init-data)
_ (when (:file options) (fs/writeFileSync (:file options) (with-out-str (pprint/pprint init-data))))
{:keys [init-tx block-props-tx]} (outliner-cli/build-blocks-tx init-data)
existing-names (set (map :v (d/datoms @conn :avet :block/title)))
conflicting-names (set/intersection existing-names (set (keep :block/title init-tx)))]
(when (seq conflicting-names)
(println "Error: Following names conflict -" (string/join "," conflicting-names))
(js/process.exit 1))
(println "Generating" (count (filter :block/name init-tx)) "pages and"
(count (filter :block/title init-tx)) "blocks ...")
(d/transact! conn init-tx)
(d/transact! conn block-props-tx)
(println "Created graph" (str db-name " with " (count (d/datoms @conn :eavt)) " datoms!"))))
(when (= nbb/*file* (nbb/invoked-file))
(-main *command-line-args*))
@@ -0,0 +1,366 @@
(ns logseq.tasks.db-graph.create-graph-with-schema-org
"Script that converts the jsonld version of schema.org into Logseq classes and
properties. Initially works with 900 classes and 1368 properties! The script
currently provides the following in a Logseq graph:
* All schema.org classes with their name, url, parent class (namespace) and properties
* Some classes are renamed due to naming conflicts
* All properties with their property type, url, description
* Property type is determined by looking for the first range value that is
a subclass of https://schema.org/DataType and then falling back to :node.
* Some properties are skipped because they are superseded/deprecated or because they have a property
type logseq doesnt' support yet
* schema.org assumes no cardinality. For now, only :node properties are given a :cardinality :many"
(:require ["fs" :as fs]
[babashka.cli :as cli]
[clojure.edn :as edn]
[clojure.pprint :as pprint]
[clojure.set :as set]
[clojure.string :as string]
[clojure.walk :as w]
[datascript.core :as d]
[logseq.db.common.sqlite-cli :as sqlite-cli]
[logseq.db.sqlite.export :as sqlite-export]
[logseq.outliner.cli :as outliner-cli]
[nbb.classpath :as cp]
[nbb.core :as nbb]))
(defn- get-comment-string
[rdfs-comment renamed-pages]
(let [desc* (if (map? rdfs-comment)
(get rdfs-comment "@value")
rdfs-comment)
;; Update refs to renamed classes
regex (re-pattern (str "\\[\\[(" (string/join "|" (keys renamed-pages)) ")\\]\\]"))
desc (string/replace desc* regex #(str "[[" (get renamed-pages (second %)) "]]"))]
;; Fix markdown and html links to schema website docs
(string/replace desc #"(\(|\")/docs" "$1https://schema.org/docs")))
(defn- strip-schema-prefix [s]
(string/replace-first s "schema:" ""))
(defn- ->class-page [class-m class-properties {:keys [renamed-classes renamed-pages]}]
(let [parent-classes* (class-m "rdfs:subClassOf")
parent-classes (cond
(map? parent-classes*)
[(parent-classes* "@id")]
(vector? parent-classes*)
(mapv #(get % "@id") parent-classes*)
;; DataTypes are weird in that they are subclassed from
;; rdfs:class but that info is omitted. It seems schema
;; does this on purpose to display it as a separate tree but
;; we want all classes under one tree
(contains? (set (as-> (class-m "@type") type'
(if (string? type') [type'] type')))
"schema:DataType")
["schema:DataType"])
;; Map of owl:equivalentClass exceptions
parent-classes' (mapv #(get {"rdfs:Class" "Class"} % %) parent-classes)
properties (class-properties (class-m "@id"))
inverted-renamed-classes (set/map-invert renamed-classes)
class-name (strip-schema-prefix (class-m "@id"))
url (str "https://schema.org/" (get inverted-renamed-classes class-name class-name))]
(cond-> {:block/title class-name
:build/properties (cond-> {:url url}
(class-m "rdfs:comment")
(assoc :logseq.property/description (get-comment-string (class-m "rdfs:comment") renamed-pages)))}
(seq parent-classes')
(assoc :build/class-extends (mapv #(keyword (strip-schema-prefix %)) parent-classes'))
(seq properties)
(assoc :build/class-properties (mapv (comp keyword strip-schema-prefix) properties)))))
(def schema->logseq-data-types
"Schema datatypes, https://schema.org/DataType, mapped to their Logseq equivalents"
{"schema:Integer" :number
"schema:Float" :number
"schema:Number" :number
"schema:Text" :default
"schema:URL" :url
"schema:Boolean" :checkbox
"schema:Date" :date
"schema:DateTime" :datetime})
(def unsupported-data-types
"Schema datatypes, https://schema.org/DataType, that don't have Logseq equivalents"
#{"schema:Time"})
(defn- get-range-includes [property-m]
(let [range-includes (as-> (property-m "schema:rangeIncludes") range-includes*
(map (fn [m] (m "@id"))
(if (map? range-includes*) [range-includes*] range-includes*)))]
;; Prioritize (sort first) DataType subclasses because they are easier to enter in the app
(sort-by #(if (schema->logseq-data-types %) -1 1) range-includes)))
(defn- get-schema-type [range-includes class-map]
(some #(or (schema->logseq-data-types %)
(when (class-map %) :node))
range-includes))
(defn- ->property-page [property-m class-map {:keys [verbose renamed-pages]}]
(let [range-includes (get-range-includes property-m)
schema-type (get-schema-type range-includes class-map)
;; Notify when a property is only using one of the available property types (rangeIncludes)
;; Doesn't apply to :node since they do include all rangeIncludes
_ (when (and verbose (> (count range-includes) 1) (not= schema-type :node))
(println "Picked property type:"
{:property (property-m "@id") :type schema-type :range-includes (vec range-includes)}))
_ (assert schema-type (str "No schema found for property " (property-m "@id")))
_ (when (= schema-type :node)
(when-let [datatype-classes (not-empty (set/intersection (set range-includes)
(set (keys schema->logseq-data-types))))]
(throw (ex-info (str "property " (pr-str (property-m "@id"))
" with type :node has DataType class values which aren't supported: " datatype-classes) {}))))
url (str "https://schema.org/" (strip-schema-prefix (property-m "@id")))]
{(keyword (strip-schema-prefix (property-m "@id")))
(cond-> {:logseq.property/type schema-type
:build/properties (cond-> {:url url}
(property-m "rdfs:comment")
(assoc :logseq.property/description (get-comment-string (property-m "rdfs:comment") renamed-pages)))}
;; This cardinality rule should be adjusted as we use schema.org more
(= schema-type :node)
(assoc :db/cardinality :many)
(= schema-type :node)
(assoc :build/property-classes (mapv (comp keyword strip-schema-prefix) range-includes)))}))
(defn- get-class-to-properties
"Given a vec of class ids and a vec of properties map to process, return a map of
class ids to their property ids"
[all-classes all-properties]
(let [;; build map of class id to all their properties
all-class-properties (reduce
(fn [acc prop]
(let [domains* (prop "schema:domainIncludes")
domains (if (map? domains*) [domains*] domains*)]
(merge-with into
acc
(->> domains
(map (fn [class] (vector (class "@id") [(prop "@id")])))
(into {})))))
{}
all-properties)]
(->> all-classes
(map #(vector % (vec (all-class-properties %))))
(into {}))))
(defn property-with-unsupported-type? [prop]
(let [range-includes
(as-> (prop "schema:rangeIncludes") range-includes*
(set (map (fn [m] (m "@id")) (if (map? range-includes*) [range-includes*] range-includes*))))
unsupported-data-types'
(set/intersection range-includes unsupported-data-types)]
(and (seq range-includes)
(every? (fn [x] (contains? unsupported-data-types' x)) range-includes))))
(defn- get-vector-conflicts
"Given a seq of tuples returns a seq of tuples that conflict i.e. their first element
has a case sensitive conflict/duplicate with another. An example conflict:
[[\"schema:status\" :property] [\"schema:status\" :node]]"
[tuples-seq]
(->> tuples-seq
(group-by first)
(filter #(> (count (val %)) 1))
vals))
(defn- detect-final-conflicts
"Does one final detection for conflicts after everything has been renamed"
[all-classes page-tuples]
(let [class-ids (map #(vector (% "@id") :class) all-classes)
existing-conflicts (get-vector-conflicts (concat class-ids page-tuples))]
(when (seq existing-conflicts) (prn :CONFLICTS existing-conflicts))
(assert (empty? existing-conflicts)
"There are no conflicts between existing pages, schema classes and properties")))
;; NOTE: There are currently no class conflicts but if some come up this fn can be updated to exclude built-in properties
(defn- detect-id-conflicts-and-get-renamed-classes
"Detects conflicts between classes AND properties and existing
pages. Renames any detected conflicts. Properties and class names conflict in
Logseq because schema.org names are case sensitive whereas Logseq's
:block/name is case insensitive. This is dealt with by appending a '_Class'
suffix to conflicting classes. If this strategy changes, be sure to update
schema->logseq-data-types"
[property-ids class-ids existing-pages {:keys [verbose]}]
(let [conflicts (get-vector-conflicts (concat property-ids class-ids))
;; If this assertion fails then renamed-classes approach to resolving
;; conflicts may need to be revisited
_ (assert (every? #(= 2 (count %)) conflicts) "All conflicts must only be between two elements")
existing-conflicts (get-vector-conflicts (concat class-ids existing-pages))
_ (when (seq existing-conflicts) (prn :EXISTING-CLASS-CONFLICTS existing-conflicts))
;; Add existing-conflicts to conflicts if this ever fails
_ (assert (empty? existing-conflicts)
"There are no conflicts between existing pages and schema classes and properties")
renamed-classes (->> conflicts
(map #(-> % second first))
;; Renaming classes with '_Class' suffix guarantees uniqueness
;; b/c schema.org doesn't use '_' in their names
(map #(vector % (str % "_Class")))
(into {}))]
(when (seq renamed-classes)
(if verbose
(println "Renaming the following classes because they have names that conflict with Logseq's case insensitive :block/name:"
(keys renamed-classes) "\n")
(when (pos? (count renamed-classes))
(println "Renaming" (count renamed-classes) "classes due to page name conflicts"))))
renamed-classes))
(defn- get-all-properties [schema-data {:keys [verbose]}]
(let [all-properties** (filter #(= "rdf:Property" (% "@type")) schema-data)
[superseded-properties all-properties*] ((juxt filter remove) #(% "schema:supersededBy") all-properties**)
_ (if verbose
(println "Skipping the following superseded properties:" (mapv #(% "@id") superseded-properties) "\n")
(println "Skipping" (count superseded-properties) "superseded properties"))
[unsupported-properties all-properties] ((juxt filter remove) property-with-unsupported-type? all-properties*)
_ (if verbose
(println "Skipping the following unsupported properties:" (mapv #(% "@id") unsupported-properties) "\n")
(println "Skipping" (count unsupported-properties) "properties with unsupported data types"))]
all-properties))
(defn- generate-classes
[select-classes class-to-properties options]
(let [classes (->> select-classes
(map #(vector (keyword (strip-schema-prefix (get % "@id")))
(->class-page % class-to-properties options)))
(into {}))]
(assert (= ["Thing"] (keep #(when-not (:build/class-extends %)
(:block/title %))
(vals classes)))
"Thing is the only class that doesn't have a schema.org parent class")
classes))
(defn- generate-properties
[select-properties class-map options]
(when (:verbose options)
(println "Properties by type:"
(->> select-properties
(mapv (fn [property-m]
(get-schema-type (get-range-includes property-m) class-map)))
frequencies)
"\n"))
(assoc
(apply merge
(mapv #(->property-page % class-map options) select-properties))
;; Have to update schema for now as validation doesn't take into account existing properties
:logseq.property/description {:logseq.property/public? true
:logseq.property/type :default
:build/properties {:url "https://schema.org/description"
:logseq.property/description "A description of the item."}}))
(defn- get-all-classes-and-properties
"Get all classes and properties from raw json file"
[schema-data existing-pages options]
(let [;; TODO: See if it's worth pulling in non-types like schema:MusicReleaseFormatType
all-classes* (filter #(contains? (set (as-> (% "@type") type'
(if (string? type') [type'] type')))
"rdfs:Class")
schema-data)
;; Use built-in description
all-properties (remove #(= "schema:description" (% "@id")) (get-all-properties schema-data options))
property-tuples (map #(vector (% "@id") :property) all-properties)
class-tuples (map #(vector (% "@id") :class) all-classes*)
page-tuples (map #(vector (str "schema:" %) :node) existing-pages)
renamed-classes (detect-id-conflicts-and-get-renamed-classes
property-tuples class-tuples page-tuples options)
;; Note: schema:description refs don't get renamed but they aren't used
;; Updates keys like @id, @subClassOf
rename-class-ids (fn [m]
(w/postwalk (fn [x]
(if-let [new-page (and (map? x) (renamed-classes (x "@id")))]
(merge x {"@id" new-page})
x)) m))
;; Updates keys like @id, @rangeIncludes, @domainIncludes
all-classes (map rename-class-ids all-classes*)]
(detect-final-conflicts all-classes page-tuples)
{:all-classes all-classes
:all-properties all-properties
:renamed-classes (->> renamed-classes
(map (fn [[k v]] [(strip-schema-prefix k) (strip-schema-prefix v)]))
(into {}))}))
(defn- create-init-data [existing-pages options]
(let [schema-data (-> (str (fs/readFileSync "resources/schemaorg-current-https.json"))
js/JSON.parse
(js->clj)
(get "@graph"))
{:keys [all-classes all-properties renamed-classes]}
(get-all-classes-and-properties schema-data existing-pages options)
;; Generate data shared across pages and properties
class-map (->> all-classes
(map #(vector (% "@id") %))
(into {}))
select-class-ids
(if (:subset options)
["schema:Person" "schema:CreativeWorkSeries" "schema:Organization"
"schema:Intangible" "schema:Series" "schema:TVSeries" ; Test class multiple inheritance
"schema:Movie" "schema:CreativeWork" "schema:Thing" "schema:Comment"]
(keys class-map))
class-to-properties (get-class-to-properties select-class-ids all-properties)
select-properties (set (mapcat val class-to-properties))
options' (assoc options
:renamed-classes renamed-classes
:renamed-pages renamed-classes)
;; Generate pages and properties
properties (generate-properties
(filter #(contains? select-properties (% "@id")) all-properties)
class-map options')
properties'
(if (:subset options)
;; only keep classes that are in subset to keep graph valid
(let [select-class-ids' (->> select-class-ids (map (comp keyword strip-schema-prefix)) set)]
(-> properties
(update-vals (fn [m]
(if (:build/property-classes m)
(update m :build/property-classes
(fn [cs] (vec (set (filter #(contains? select-class-ids' %) cs)))))
m)))))
properties)
classes (generate-classes
(map #(class-map %) select-class-ids)
class-to-properties options')]
{:graph-namespace :schema
:classes classes
:properties properties'}))
(def spec
"Options spec"
{:help {:alias :h
:desc "Print help"}
:config {:alias :c
:coerce edn/read-string
:desc "EDN map to add to config.edn"}
:export {:alias :e
:desc "Exports graph to schema.edn"}
:subset {:alias :s
:desc "Only generate a subset of data for testing purposes"}
:verbose {:alias :v
:desc "Verbose mode"}})
(defn- write-export-file [db]
(let [export-map (sqlite-export/build-export db {:export-type :graph-ontology})]
(fs/writeFileSync "schema.edn"
(with-out-str (pprint/pprint export-map)))))
(defn -main [args]
(let [[graph-dir] args
options (cli/parse-opts args {:spec spec})
_ (when (or (nil? graph-dir) (:help options))
(println (str "Usage: $0 GRAPH-NAME [OPTIONS]\nOptions:\n"
(cli/format-opts {:spec spec})))
(js/process.exit 1))
init-conn-args (sqlite-cli/->open-db-args graph-dir)
db-name (if (= 1 (count init-conn-args)) (first init-conn-args) (second init-conn-args))
conn (apply outliner-cli/init-conn
(conj init-conn-args {:additional-config (:config options)
:classpath (cp/get-classpath)}))
init-data (create-init-data (d/q '[:find [?name ...] :where [?b :block/name ?name]] @conn)
options)
{:keys [init-tx block-props-tx]} (outliner-cli/build-blocks-tx init-data)]
(println "Generating" (str (count (filter :block/name init-tx)) " pages with "
(count (:classes init-data)) " tags and "
(count (:properties init-data)) " properties ..."))
(d/transact! conn init-tx)
(d/transact! conn block-props-tx)
(when (:verbose options) (println "Transacted" (count (d/datoms @conn :eavt)) "datoms"))
(when (:export options) (write-export-file @conn))
(println "Created graph" (str db-name "!"))))
(when (= nbb/*file* (nbb/invoked-file))
(-main *command-line-args*))
+251
View File
@@ -0,0 +1,251 @@
(ns logseq.tasks.dev
"Tasks for general development. For desktop or mobile development see their
namespaces"
(:refer-clojure :exclude [test])
(:require [babashka.cli :as cli]
[babashka.fs :as fs]
[babashka.process :refer [shell]]
[babashka.tasks :refer [clojure]]
[clojure.data :as data]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[clojure.string :as string]
[logseq.tasks.dev.lint :as dev-lint]
[logseq.tasks.util :as task-util]))
(defn run-shell
[& args]
(apply shell args))
(defn test
"Run tests. Pass args through to cmd 'pnpm cljs:run-test'"
[& args]
(shell {:shutdown nil} "pnpm cljs:test")
(apply shell {:shutdown nil} "pnpm cljs:run-test" args))
(defn test-no-worker
"Run tests without compiling worker namespaces. Pass args through to cmd 'pnpm cljs:run-test-no-worker'"
[& args]
(shell "pnpm cljs:test-no-worker")
(apply shell "pnpm cljs:run-test-no-worker" args))
(def test-jobs (min 5 (.availableProcessors (Runtime/getRuntime))))
(def test-batches-per-job 6)
(def default-test-args ["-r" "^(?!logseq.db-sync.).*"])
(def isolated-test-namespaces
#{"frontend.components.block.drop-boundary-test"
"frontend.handler.db-based.page-test"
"frontend.handler.editor-async-test"
"frontend.handler.editor-lifecycle-test"
"frontend.handler.editor-test"
"frontend.handler.route-test"
"frontend.rfx-test"
"frontend.worker.db-core-test"})
(def serial-test-namespaces
#{"frontend.db.query-dsl-test"
"frontend.worker.search-test"})
(defn isolated-test-namespace?
[test-ns]
(contains? isolated-test-namespaces test-ns))
(defn- run-parallel!
([tasks]
(run-parallel! (count tasks) tasks))
([jobs tasks]
(let [tasks (vec tasks)]
(when (seq tasks)
(let [task-queue (atom (seq tasks))
next-task! (fn []
(loop []
(let [tasks @task-queue]
(when (seq tasks)
(if (compare-and-set! task-queue tasks (rest tasks))
(first tasks)
(recur))))))
worker (fn []
(loop [error nil]
(if-let [task (next-task!)]
(recur (try
(task)
error
(catch Throwable e
(or error e))))
error)))
results (->> #(future (worker))
(repeatedly (min jobs (count tasks)))
doall)]
(when-let [error (some deref results)]
(throw error)))))))
(defn- selected-test-namespaces
[args]
(->> (:out (apply run-shell {:out :string
:shutdown nil
:extra-env {"LOGSEQ_STABLE_IDENTS" "1"}}
"node" "static/tests.js" "--list-namespaces" args))
string/split-lines
(remove string/blank?)
vec))
(defn- round-robin-batches
[items batch-count]
(when (pos? batch-count)
(->> items
(map-indexed (fn [idx item]
[(mod idx batch-count) item]))
(group-by first)
(sort-by first)
(mapv (fn [[_ indexed-items]]
(mapv second indexed-items))))))
(defn- namespace-batches
[test-namespaces]
(let [priority-namespaces ["frontend.handler.editor-test"
"frontend.worker.db-core-test"
"frontend.handler.editor-async-test"]
priority-set (set priority-namespaces)
priority (->> priority-namespaces
(filter (set test-namespaces))
(mapv vector))
isolated (->> test-namespaces
(filter isolated-test-namespace?)
(remove priority-set)
(mapv vector))
shared (remove isolated-test-namespace? test-namespaces)
batch-count (min (* test-jobs test-batches-per-job) (count shared))
batches (round-robin-batches shared batch-count)]
(into priority
(loop [batches (seq batches)
isolated (seq isolated)
result []]
(if (or batches isolated)
(recur (next batches)
(next isolated)
(cond-> result
batches (conj (first batches))
isolated (conj (first isolated))))
result)))))
(defn- namespace-args
[test-namespaces]
(mapcat (fn [test-ns] ["-n" test-ns]) test-namespaces))
(defn run-test-namespaces
"Run compiled tests in isolated Node processes, in parallel by namespace."
[& args]
(let [test-namespaces (selected-test-namespaces args)
parallel-namespaces (remove serial-test-namespaces test-namespaces)
serial-namespaces (filter serial-test-namespaces test-namespaces)
run-namespaces! (fn [namespaces]
(apply run-shell {:shutdown nil
:extra-env {"LOGSEQ_STABLE_IDENTS" "1"}}
"node" "static/tests.js"
(concat (namespace-args namespaces) args)))]
(run-parallel! test-jobs
(mapv (fn [test-namespaces]
#(run-namespaces! test-namespaces))
(namespace-batches parallel-namespaces)))
(doseq [test-ns serial-namespaces]
(run-namespaces! [test-ns]))))
(defn parallel-test
"Compile tests, then run them in parallel by namespace."
[& args]
(run-shell {:shutdown nil} "pnpm cljs:test")
(apply run-test-namespaces (concat default-test-args args)))
(defn lint-and-test
"Run all lint tasks and tests excluding testcases tagged by :long and :fix-me."
[]
(run-parallel! [dev-lint/dev
#(parallel-test "-e" "long" "-e" "fix-me")]))
(defn e2e-basic-test
"Run e2e basic tests. HTTP server should be available at localhost:3001"
[& _]
(clojure {:dir "clj-e2e"} "-X:dev-run-all-basic-test"))
(defn e2e-rtc-extra-test
"Run e2e rtc extra tests. HTTP server should be available at localhost:3001"
[& _]
(clojure {:dir "clj-e2e"} "-X:dev-run-rtc-extra-test"))
(defn gen-malli-kondo-config
"Generate clj-kondo type-mismatch config from malli schema
.clj-kondo/metosin/malli-types/config.edn"
[]
(let [config-edn ".clj-kondo/metosin/malli-types/config.edn"
compile-cmd "clojure -M:cljs compile gen-malli-kondo-config"]
(println compile-cmd)
(shell {:shutdown nil} compile-cmd)
(println "generate kondo config: " config-edn)
(io/make-parents config-edn)
(let [config (with-out-str
(pp/pprint (edn/read-string (:out (shell {:out :string :shutdown nil}
"node ./static/gen-malli-kondo-config.js")))))]
(spit config-edn config))))
(defn diff-datoms
"Runs data/diff on two edn files written by dev:datoms"
[file1 file2 & args]
(let [spec {:ignored-attributes
;; Ignores some attributes by default that are expected to change often
{:alias :i :coerce #{:keyword} :default #{:block/tx-id :block/order :block/updated-at}}}
{{:keys [ignored-attributes]} :opts} (cli/parse-args args {:spec spec})
datom-filter (fn [[_e a _ _ _]] (contains? ignored-attributes a))
data-diff* (apply data/diff (map (fn [x] (->> x slurp edn/read-string (remove datom-filter))) [file1 file2]))
data-diff (->> data-diff*
;; Drop common as we're only interested in differences
drop-last
;; Remove nils as we're only interested in diffs
(mapv #(vec (remove nil? %))))]
(pp/pprint data-diff)))
(defn build-publishing-frontend
"Builds frontend release publishing asset when files have changed"
[& _args]
(if-let [_files (and (not (System/getenv "SKIP_ASSET"))
(seq (set (fs/modified-since (fs/file "static/js/publishing/main.js")
(fs/glob "." "{src/main,deps/graph-parser/src}/**")))))]
(do
(println "Building publishing js asset...")
(shell {:shutdown nil} "clojure -M:cljs release publishing db-worker"))
(println "Publishing js asset is up to date")))
(defn publishing-backend
"Builds publishing backend and copies over supporting frontend assets"
[& args]
(apply shell {:dir "deps/publishing" :extra-env {"ORIGINAL_PWD" (fs/cwd)} :shutdown nil}
"pnpm exec nbb-logseq -cp src:../graph-parser/src script/publishing.cljs"
(into ["static"] args)))
(defn watch-publishing-frontend
[& _args]
(shell {:shutdown nil} "pnpm exec shadow-cljs watch publishing"))
(defn watch-publishing-backend
"Builds publishing backend once watch-publishing-frontend has built initial frontend"
[& args]
(let [start-time (java.time.Instant/now)]
(Thread/sleep 3000)
(loop [n 1000]
(if (and (fs/exists? "static/js/publishing/main.js")
(task-util/file-modified-later-than? "static/js/publishing/main.js" start-time))
(apply publishing-backend args)
(do (println "Waiting for publishing frontend to build...")
(Thread/sleep 1000)
(recur (inc n)))))))
(defn db-import-many
[& args]
(let [parent-graph-dir "./out"
[file-graphs import-options] (split-with #(not (string/starts-with? % "-")) args)]
(doseq [file-graph file-graphs]
(let [db-graph (fs/path parent-graph-dir (fs/file-name file-graph))]
(println "Importing" (str db-graph) "...")
(apply shell {:shutdown nil} "bb" "dev:db-import" file-graph db-graph (concat import-options ["--validate"]))))))
+25
View File
@@ -0,0 +1,25 @@
(ns logseq.tasks.dev.db-sync
"Tasks for db-sync dev processes"
(:require [babashka.process :refer [process]]))
(def processes
[{:name "db-sync-watch"
:dir "deps/db-sync"
:cmd "clojure -M:cljs watch db-sync"}
{:name "wrangler-dev"
:dir "deps/db-sync/worker"
:cmd "wrangler dev"}
{:name "pnpm-watch"
:dir "."
:cmd "ENABLE_DB_SYNC_LOCAL=true pnpm watch"}])
(defn start
[]
(println "Starting db-sync processes in foreground.")
(println "Use Ctrl-C to stop.")
(let [procs (mapv (fn [{:keys [name dir cmd]}]
(println "Running:" name "-" cmd)
(process ["bash" "-lc" cmd] {:dir dir :inherit true}))
processes)]
(doseq [proc procs]
@proc)))
+21
View File
@@ -0,0 +1,21 @@
(ns logseq.tasks.dev.desktop
"Tasks for desktop (electron) development"
(:require [babashka.tasks :refer [shell]]
[babashka.fs :as fs]
[logseq.tasks.util :as task-util]))
(defn watch
"Watches environment to reload cljs, css and other assets"
[]
(shell {:shutdown nil} "pnpm electron-watch"))
(defn open-dev-electron-app
"Opens dev-electron-app when watch process has built main.js"
[]
(let [start-time (java.time.Instant/now)]
(dotimes [_n 1000]
(if (and (fs/exists? "static/js/main.js")
(task-util/file-modified-later-than? "static/js/main.js" start-time))
(shell {:shutdown nil} "pnpm dev-electron-app")
(println "Waiting for app to build..."))
(Thread/sleep 1000))))
+93
View File
@@ -0,0 +1,93 @@
(ns logseq.tasks.dev.lint
(:require [babashka.process :refer [shell]]
[clojure.string :as string]))
(defn dev
"Run all lint tasks
- clj-kondo lint
- carve lint for unused vars
- lint for vars that are too large
- lint invalid translation entries
- lint to ensure file and db graph remain separate
- lint to ensure worker and frontend are separate"
[]
(doseq [cmd ["clojure -M:clj-kondo --parallel --lint src --cache false"
"bb lint:carve"
"bb lint:large-vars"
"bb lint:worker-and-frontend-separate"
"bb lang:validate-translations"
"bb lint:ns-docstrings"]]
(println cmd)
(shell {:shutdown nil} cmd)))
(defn kondo-git-changes
"Run clj-kondo across dirs and only for files that git diff detects as unstaged changes"
[]
(let [kondo-dirs ["src" "deps/common" "deps/db" "deps/graph-parser" "deps/outliner" "deps/publishing" "deps/publish"]
dir-regex (re-pattern (str "^(" (string/join "|" kondo-dirs) ")"))
dir-to-files (->> (shell {:out :string :shutdown nil} "git diff --name-only")
:out
string/split-lines
(filter #(re-find #"\.(cljs|clj|cljc)$" %))
(group-by #(first (re-find dir-regex %)))
;; remove files that aren't in a kondo dir
((fn [x] (dissoc x nil))))]
(if (seq dir-to-files)
(doseq [[dir* files*] dir-to-files]
(let [dir (if (= dir* "src") "." dir*)
files (mapv #(string/replace-first % (str dir "/") "") files*)
cmd (str "cd " dir " && clj-kondo --lint " (string/join " " files))
_ (println cmd)
res (apply shell {:dir dir :continue :true :shutdown nil} "clj-kondo --lint" files)]
(when (pos? (:exit res)) (System/exit (:exit res)))))
(println "No clj* files have changed to lint."))))
(defn- validate-frontend-not-in-workers
[]
(let [res (shell {:out :string :shutdown nil}
"git grep -h" "\\[frontend.*:as"
"src/main/frontend/worker" "src/main/frontend/worker_common")
allowed-export-requires #{" [frontend.handler.export.common-impl :as common-impl]"
" [frontend.handler.export.html :as export-html]"
" [frontend.handler.export.opml :as export-opml]"
" [frontend.handler.export.text-impl :as export-text]"}
req-lines (->> (:out res)
string/split-lines
(remove #(re-find #"frontend\.worker|frontend\.common" %))
(remove allowed-export-requires))]
(if (seq req-lines)
(do
(println "The following frontend requires should not be in worker namespaces:")
(println (string/join "\n" req-lines))
(System/exit 1))
(println "Valid worker namespaces!"))))
(defn- validate-workers-not-in-frontend
[]
(let [res (shell {:out :string :continue true :shutdown nil}
"git grep --untracked --exclude-standard"
"\\[frontend.worker.*:" "--" "src/main/frontend")
;; allow reset-file b/c it's only affects tests
allowed-exceptions #{"src/main/frontend/handler/file_based/file.cljs: [frontend.worker.file.reset :as file-reset]"}
excluded-path-prefixes ["src/main/frontend/worker/"]
invalid-lines (when (= 0 (:exit res))
(->> (:out res)
string/split-lines
(remove (fn [line]
(let [path (first (string/split line #":" 2))]
(or (contains? allowed-exceptions line)
(some #(string/starts-with? path %)
excluded-path-prefixes)))))))
_ (when (> (:exit res) 1) (System/exit 1))]
(if (and (= 0 (:exit res)) (seq invalid-lines))
(do (println "The following worker requires should not be in frontend namespaces:")
(println (string/join "\n" invalid-lines))
(System/exit 1))
(println "Valid frontend namespaces!"))))
(defn worker-and-frontend-separate
"Ensures workers are independent of frontend"
[]
(validate-frontend-not-in-workers)
(validate-workers-not-in-frontend))
@@ -0,0 +1,111 @@
(ns logseq.tasks.dev.lint-test-deps
"Runs lint/test tasks for selected deps with readable progress output."
(:require [babashka.process :refer [shell]]))
(def ^:private kondo-src-test-step
{:runner :cmd :name "clj-kondo (src test)" :cmd "clojure -M:clj-kondo --lint src test --cache false"})
(def ^:private dep-plan
[{:dep "deps/common"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
{:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
{:runner :cmd :name "pnpm exec nbb-logseq (-e long)" :cmd "pnpm exec nbb-logseq -cp test -m nextjournal.test-runner -e long"}]}
{:dep "deps/db"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
{:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
{:runner :bb :name "lint:rules" :cmd "lint:rules"}
{:runner :cmd :name "pnpm exec nbb-logseq (-e long)" :cmd "pnpm exec nbb-logseq -cp test -m nextjournal.test-runner -e long"}]}
{:dep "deps/db-sync"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
;; {:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
;; {:runner :bb :name "lint:minimize-public-vars" :cmd "lint:minimize-public-vars"}
]}
{:dep "."
:steps [{:runner :bb :name "dev:db-sync-test" :cmd "dev:db-sync-test"}]}
{:dep "deps/outliner"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
{:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
{:runner :bb :name "lint:minimize-public-vars" :cmd "lint:minimize-public-vars"}
{:runner :cmd :name "pnpm exec nbb-logseq (-e long)" :cmd "pnpm exec nbb-logseq -cp test -m nextjournal.test-runner -e long"}]}
{:dep "deps/graph-parser"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
{:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
;; {:runner :bb :name "lint:minimize-public-vars" :cmd "lint:minimize-public-vars"}
{:runner :cmd :name "pnpm exec nbb-logseq (-e long)" :cmd "pnpm exec nbb-logseq -cp test -m nextjournal.test-runner -e long"}]}
{:dep "deps/publish"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
{:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
{:runner :cmd :name "pnpm test" :cmd "pnpm test"}]}
{:dep "deps/publishing"
:steps [kondo-src-test-step
{:runner :bb :name "lint:large-vars" :cmd "lint:large-vars"}
{:runner :bb :name "lint:carve" :cmd "lint:carve"}
{:runner :bb :name "lint:ns-docstrings" :cmd "lint:ns-docstrings"}
{:runner :bb :name "lint:minimize-public-vars" :cmd "lint:minimize-public-vars"}]}])
(defn- run-step!
[dep {:keys [runner name cmd reason]}]
(case runner
:skip
(do
(println (str "\n==> [" dep "] " name " (skip)"))
(println (str "SKIP[" dep "] " name " - " reason))
{:dep dep :task name :exit 0 :skipped true})
:bb
(do
(println (str "\n==> [" dep "] bb " cmd))
(let [result (shell {:dir dep :continue true} (str "bb " cmd))
success? (zero? (:exit result))]
(println (str (if success? "OK " "ERR ")
"[" dep "] "
name
(when-not success?
(str " (exit " (:exit result) ")"))))
{:dep dep :task name :exit (:exit result)}))
:cmd
(do
(println (str "\n==> [" dep "] " cmd))
(let [result (shell {:dir dep :continue true} cmd)
success? (zero? (:exit result))]
(println (str (if success? "OK " "ERR ")
"[" dep "] "
name
(when-not success?
(str " (exit " (:exit result) ")"))))
{:dep dep :task name :exit (:exit result)}))))
(defn run
"Lint and test selected deps projects with per-step progress and summary."
[& _]
(println "Starting deps lint/test suite...")
(let [results (vec
(mapcat (fn [{:keys [dep steps]}]
(map #(run-step! dep %) steps))
dep-plan))
skipped-count (count (filter :skipped results))
failures (filter #(pos? (:exit %)) results)]
(println "\nSummary:")
(println (str " Total tasks: " (count results)))
(println (str " Passed: " (- (count results) skipped-count (count failures))))
(println (str " Skipped: " skipped-count))
(println (str " Failed: " (count failures)))
(when (seq failures)
(println "\nFailed tasks:")
(doseq [{:keys [dep task exit]} failures]
(println (str " - [" dep "] " task " (exit " exit ")")))
(System/exit 1))
(println "\nAll deps lint/test tasks passed.")))
+223
View File
@@ -0,0 +1,223 @@
(ns logseq.tasks.dev.mobile
"Tasks for mobile development"
(:require [babashka.fs :as fs]
[babashka.tasks :refer [shell]]
[clojure.string :as string]
[logseq.tasks.util :as task-util])
(:import [java.nio.file FileAlreadyExistsException]))
(def ^:private dev-server-port "3002")
(def ^:private ssl-dir "ssl/mobile-dev")
(def ^:private ssl-lock-file "ssl/mobile-dev/.cert.lock")
(def ^:private ssl-ca-keystore "ssl/mobile-dev/ca-keystore.jks")
(def ^:private ssl-ca-cert "ssl/mobile-dev/logseq-dev-ca.cer")
(def ^:private ssl-keystore "ssl/mobile-dev/keystore.jks")
(def ^:private ssl-server-cert "ssl/mobile-dev/logseq-dev-server.cer")
(def ^:private ssl-server-csr "ssl/mobile-dev/logseq-dev-server.csr")
(def ^:private ssl-password "shadow-cljs")
(defn- local-ip
[]
(letfn [(interface-ip [interface]
(let [{:keys [exit out]} (shell {:out :string
:err :string
:continue true
:shutdown nil}
(str "ipconfig getifaddr " interface))
ip (string/trim (or out ""))]
(when (and (zero? exit) (not (string/blank? ip)))
ip)))]
(or (interface-ip "en0")
(interface-ip "en1")
(throw (ex-info "Failed to detect local network IP" {})))))
(defn dev-server-url
[ip]
(format "https://%s:%s/mobile/" ip dev-server-port))
(defn- with-ssl-cert-lock!
[f]
(fs/create-dirs ssl-dir)
(loop [attempt 0]
(let [locked? (try
(fs/create-file ssl-lock-file)
true
(catch FileAlreadyExistsException _
false))]
(when-not locked?
(when (> attempt 600)
(throw (ex-info "Timed out waiting for mobile HTTPS certificate lock"
{:lock-file ssl-lock-file})))
(Thread/sleep 100)
(recur (inc attempt)))))
(try
(f)
(finally
(fs/delete-if-exists ssl-lock-file))))
(defn- usable-keystore?
[]
(and (fs/exists? ssl-keystore)
(fs/exists? ssl-ca-keystore)
(fs/exists? ssl-ca-cert)
(zero? (:exit (shell {:continue true :out :string :err :string :shutdown nil}
(str "keytool -list"
" -keystore " ssl-keystore
" -storepass " ssl-password
" -alias logseq-dev"))))
(zero? (:exit (shell {:continue true :out :string :err :string :shutdown nil}
(str "keytool -list"
" -keystore " ssl-ca-keystore
" -storepass " ssl-password
" -alias logseq-dev-ca"))))))
(defn- backup-existing-ssl-files!
[]
(when (and (fs/exists? ssl-keystore)
(not (usable-keystore?)))
(let [backup (str ssl-keystore ".bak." (System/currentTimeMillis))]
(println "Backing up incompatible HTTPS keystore to" backup)
(fs/move ssl-keystore backup {:replace-existing true})))
(when-not (usable-keystore?)
(doseq [path [ssl-ca-keystore ssl-ca-cert ssl-server-cert ssl-server-csr]]
(fs/delete-if-exists path))))
(defn- generate-dev-ssl-cert!
[ip]
(let [san (str "SAN=ip:" ip ",dns:localhost,ip:127.0.0.1")]
(shell {:shutdown nil}
(str "keytool -genkeypair"
" -alias logseq-dev-ca"
" -keyalg RSA"
" -keysize 2048"
" -validity 3650"
" -keystore " ssl-ca-keystore
" -storepass " ssl-password
" -keypass " ssl-password
" -dname \"CN=Logseq Mobile Dev CA, OU=Logseq Development, O=Logseq, L=Local, ST=Local, C=US\""
" -ext bc=ca:true"
" -ext ku=keyCertSign,cRLSign"))
(shell {:shutdown nil}
(str "keytool -exportcert"
" -rfc"
" -alias logseq-dev-ca"
" -keystore " ssl-ca-keystore
" -storepass " ssl-password
" -file " ssl-ca-cert))
(shell {:shutdown nil}
(str "keytool -genkeypair"
" -alias logseq-dev"
" -keyalg RSA"
" -keysize 2048"
" -validity 365"
" -keystore " ssl-keystore
" -storepass " ssl-password
" -keypass " ssl-password
" -dname \"CN=" ip ", OU=Logseq Development, O=Logseq, L=Local, ST=Local, C=US\""
" -ext " san))
(shell {:shutdown nil}
(str "keytool -certreq"
" -alias logseq-dev"
" -keystore " ssl-keystore
" -storepass " ssl-password
" -file " ssl-server-csr))
(shell {:shutdown nil}
(str "keytool -gencert"
" -alias logseq-dev-ca"
" -keystore " ssl-ca-keystore
" -storepass " ssl-password
" -infile " ssl-server-csr
" -outfile " ssl-server-cert
" -rfc"
" -validity 365"
" -ext " san
" -ext KU=digitalSignature,keyEncipherment"
" -ext EKU=serverAuth"))
(shell {:shutdown nil}
(str "keytool -importcert"
" -noprompt"
" -trustcacerts"
" -alias logseq-dev-ca"
" -file " ssl-ca-cert
" -keystore " ssl-keystore
" -storepass " ssl-password))
(shell {:shutdown nil}
(str "keytool -importcert"
" -noprompt"
" -trustcacerts"
" -alias logseq-dev"
" -file " ssl-server-cert
" -keystore " ssl-keystore
" -storepass " ssl-password))))
(defn ensure-dev-ssl-cert!
"Creates the local Shadow CLJS dev HTTPS keystore and exported iOS trust CA."
[]
(with-ssl-cert-lock!
(fn []
(let [ip (local-ip)]
(backup-existing-ssl-files!)
(when-not (usable-keystore?)
(generate-dev-ssl-cert! ip))
(println "Shadow CLJS HTTPS keystore:" ssl-keystore)
(println "Install and fully trust this CA certificate on iOS:" ssl-ca-cert)
(println "Mobile dev server URL:" (dev-server-url ip))))))
(defn ensure-dev-ssl-cert-task
[]
(ensure-dev-ssl-cert!))
(defn- open-dev-app
"Opens mobile app when watch process has built main.js"
[shell-opts cmd]
(let [start-time (java.time.Instant/now)]
(loop [n 1000]
(if (and (fs/exists? "static/mobile/js/main.js")
(task-util/file-modified-later-than? "static/mobile/js/main.js" start-time))
(shell (merge {:shutdown nil} shell-opts) cmd)
(println "Waiting for app to build..."))
(Thread/sleep 1000)
(when-not (or (and (fs/exists? "ios/App/App/public/js/main.js")
(task-util/file-modified-later-than? "ios/App/App/public/js/main.js" start-time))
(and (fs/exists? "android/App/src/main/assets/public/js/main.js")
(task-util/file-modified-later-than? "android/App/src/main/assets/public/js/main.js" start-time)))
(recur (dec n))))))
(defn app-watch
"Watches environment to reload cljs, css and other assets for mobile"
[]
(ensure-dev-ssl-cert!)
(doseq [cmd ["pnpm clean"
"pnpm mobile-watch"]]
(println cmd)
(shell {:shutdown nil
:extra-env {"LOGSEQ_SHADOW_HTTPS" "true"}}
cmd)))
(defn cap-run-ios
"Copy assets files to iOS build directory, and run app in Xcode"
[]
(ensure-dev-ssl-cert!)
(open-dev-app {:extra-env {"LOGSEQ_APP_SERVER_URL" (dev-server-url (local-ip))}}
"pnpm exec cap sync ios")
(shell {:shutdown nil} "pnpm exec cap open ios"))
(defn cap-run-android
"Copy assets files to Android build directory, and run app in Android Studio"
[]
(ensure-dev-ssl-cert!)
(open-dev-app {:extra-env {"LOGSEQ_APP_SERVER_URL" (dev-server-url (local-ip))}}
"pnpm exec cap sync android")
(shell {:shutdown nil} "pnpm exec cap open android"))
(defn run-ios-release
"Build iOS app release"
[]
(shell {:shutdown nil} "git checkout capacitor.config.ts")
(shell {:shutdown nil} "pnpm run-ios-release"))
(defn run-android-release
"Build Android app release"
[]
(shell {:shutdown nil} "git checkout capacitor.config.ts")
(shell {:shutdown nil} "pnpm run-android-release"))
+334
View File
@@ -0,0 +1,334 @@
(ns logseq.tasks.lang
"Tasks related to language translations"
(:require [babashka.cli :as cli]
[babashka.fs :as fs]
[babashka.process :refer [shell]]
[borkdude.rewrite-edn :as rewrite]
[clojure.set :as set]
[clojure.string :as string]
[frontend.dicts :as dicts]
[logseq.tasks.lang-lint :as lang-lint]
[logseq.tasks.util :as task-util]
[rewrite-clj.node :as node]))
(defn- get-dicts
[]
dicts/dicts)
(defn- get-languages
[]
(->> dicts/languages
(map (juxt :value :label))
(into {})))
(defn- shorten [s length]
(if (< (count s) length)
s
(string/replace (str (subs s 0 length) "...")
;; Keep shortened table rows single-line for multi-line translations.
"\n" "\\n")))
(defn list-langs
"List translated languages with their number of translations"
[]
(let [dicts (get-dicts)
langs (get-languages)]
(->> (lang-lint/translation-summary-stats dicts)
(lang-lint/sort-translation-summary-stats)
(map (fn [{:keys [lang translation-count untranslated-count same-as-en-count]}]
{:locale lang
:translation-count translation-count
:untranslated-count (if (= lang :en) "-" untranslated-count)
:same-as-en-count (if (= lang :en) "-" same-as-en-count)
:language (langs lang)}))
task-util/print-table)))
(defn list-pseudo
"List translations for LOCALE whose localized value is identical to English."
[& args]
(let [lang (or (some-> (first args) keyword)
(task-util/print-usage "LOCALE"))
langs (get-languages)
dicts (get-dicts)]
(when-not (contains? langs lang)
(println "Language" lang "does not have an entry in frontend.dicts/languages")
(System/exit 1))
(let [findings (->> (lang-lint/identical-translation-findings dicts lang)
(map (fn [{:keys [translation-key default-value]}]
{:translation-key translation-key
:same-as-en-value default-value
:file (str "dicts/" (-> lang name string/lower-case) ".edn")}))
(sort-by (juxt :file :translation-key)))]
(if (empty? findings)
(println "Language" lang "does not contain translations identical to English!")
(task-util/print-table
(map #(update % :same-as-en-value shorten 50) findings))))))
(defn list-missing
"List missing translations for a given language"
[& args]
(let [lang (or (keyword (first args))
(task-util/print-usage "LOCALE [--copy]"))
options (cli/parse-opts (rest args) {:coerce {:copy :boolean}})
_ (when-not (contains? (get-languages) lang)
(println "Language" lang "does not have an entry in frontend.dicts/languages")
(System/exit 1))
dicts (get-dicts)
all-missing (select-keys (dicts :en)
(set/difference (set (keys (dicts :en)))
(set (keys (dicts lang)))))]
(if (-> all-missing count zero?)
(println "Language" lang "is fully translated!")
(let [sorted-missing (->> all-missing
(map (fn [[k v]]
{:translation-key k
:string-to-translate v
:file (str "dicts/" (-> lang name string/lower-case) ".edn")}))
(sort-by (juxt :file :translation-key)))]
(if (:copy options)
(doseq [[file missing-for-file] (group-by :file sorted-missing)]
(println "\n;; For" file)
(doseq [{:keys [translation-key string-to-translate]} missing-for-file]
(println translation-key (pr-str string-to-translate))))
(task-util/print-table
;; Shorten values
(map #(update % :string-to-translate shorten 50) sorted-missing)))))))
(defn- delete-invalid-non-default-languages
[invalid-keys-by-lang]
(doseq [[lang invalid-keys] invalid-keys-by-lang]
(let [path (fs/path "src/resources/dicts" (str (name lang) ".edn"))
result (rewrite/parse-string (String. (fs/read-all-bytes path)))
new-content (str (reduce
(fn [result k]
(rewrite/dissoc result k))
result invalid-keys))]
(spit (fs/file path) new-content))))
(def ^:private dicts-dir
(fs/path "src/resources/dicts"))
(def ^:private ignored-dict-node-tags
#{:comment :newline :whitespace})
(defn- ignored-dict-node?
[node]
(contains? ignored-dict-node-tags (node/tag node)))
(defn- dict-map-node
[root]
(->> (:children root)
(remove ignored-dict-node?)
first))
(defn- parse-dict-entries
[text]
(let [root (rewrite/parse-string text)
map-node (dict-map-node root)]
(when-not (= :map (node/tag map-node))
(println "Expected a top-level map in dictionary file.")
(System/exit 1))
(let [entry-nodes (->> (:children map-node)
(remove ignored-dict-node?))]
(when (odd? (count entry-nodes))
(println "Encountered an uneven number of top-level dictionary nodes.")
(System/exit 1))
(mapv (fn [[key-node value-node]]
{:key (rewrite/sexpr key-node)
:value-node value-node})
(partition 2 entry-nodes)))))
(defn- render-dict-entry
[{:keys [key value-node]}]
(str " " key " " value-node))
(defn- key-namespace-root
[key]
(some-> key namespace (string/split #"\.") first))
(defn- key-leaf
[key]
(name key))
(defn- compare-dict-keys
[key-a key-b]
(let [namespace-a (namespace key-a)
namespace-b (namespace key-b)
root-a (key-namespace-root key-a)
root-b (key-namespace-root key-b)
root-diff (compare root-a root-b)]
(cond
(not= 0 root-diff)
root-diff
(not= namespace-a root-a)
(if (= namespace-b root-b) 1
(let [namespace-diff (compare namespace-a namespace-b)]
(if (zero? namespace-diff)
(compare (key-leaf key-a) (key-leaf key-b))
namespace-diff)))
(not= namespace-b root-b)
-1
:else
(compare (key-leaf key-a) (key-leaf key-b)))))
(defn- render-dict
[entries]
(let [sorted-entries (sort #(neg? (compare-dict-keys (:key %1) (:key %2))) entries)
lines (loop [remaining sorted-entries
previous-namespace nil
acc ["{"]]
(if-let [{:keys [key] :as entry} (first remaining)]
(let [current-namespace (namespace key)
acc (cond-> acc
(and previous-namespace
(not= previous-namespace current-namespace))
(conj "")
true
(conj (render-dict-entry entry)))]
(recur (next remaining) current-namespace acc))
(conj acc "}")))]
(str (string/join "\n" lines) "\n")))
(defn- dict-file-paths
[]
(->> (fs/list-dir dicts-dir)
(filter #(string/ends-with? (str %) ".edn"))
(sort-by fs/file-name)))
(defn format-dicts
"Formats dictionary files by full-key sort order and inserts a blank line
between namespace groups. Use --check to fail when any file would change."
[& args]
(let [check? (contains? (set args) "--check")
changed? (volatile! false)]
(doseq [path (dict-file-paths)]
(let [file-name (fs/file-name path)
current-text (slurp (str path))
output-text (-> current-text
parse-dict-entries
render-dict)]
(if (= current-text output-text)
(println file-name ": already formatted")
(do
(vreset! changed? true)
(if check?
(println file-name "would change")
(do
(spit (str path) output-text)
(println file-name ": formatted")))))))
(when (and check? @changed?)
(System/exit 1))))
(defn- validate-non-default-languages
"This validation finds any translation keys that don't exist in the default
language English. Logseq needs to work out of the box with its default
language. This catches mistakes where another language has accidentally typoed
keys or added ones without updating :en"
[fix?]
(let [dicts (get-dicts)
;; For now defined as :en but clj-kondo analysis could be more thorough
valid-keys (set (keys (dicts :en)))
invalid-dicts
(->> (dissoc dicts :en)
(mapcat (fn [[lang lang-dicts]]
(map
#(hash-map :language lang :invalid-key %)
(set/difference (set (keys lang-dicts))
valid-keys)))))]
(if (empty? invalid-dicts)
(println "All non-default translations have valid keys!")
(do
(println "\nThese translation keys are invalid because they don't exist in English:")
(task-util/print-table invalid-dicts)
(when fix?
(delete-invalid-non-default-languages
(update-vals (group-by :language invalid-dicts) #(map :invalid-key %)))
(println "These invalid translation keys have been removed from non-default dictionaries."))
(System/exit 1)))))
(def ^:private i18n-lint-launcher-path
(fs/absolutize "bin/logseq-i18n-lint"))
(def ^:private i18n-lint-config-path
(fs/absolutize ".i18n-lint.toml"))
(defn- ensure-i18n-lint-ready!
[]
(when-not (fs/exists? i18n-lint-launcher-path)
(println "logseq-i18n-lint launcher not found at" (str i18n-lint-launcher-path))
(System/exit 1))
(when-not (fs/exists? i18n-lint-config-path)
(println "i18n lint config not found at" (str i18n-lint-config-path))
(System/exit 1)))
(defn- run-i18n-lint-command!
[subcommand cli-args]
(ensure-i18n-lint-ready!)
(let [cmd (into ["bash"
(str i18n-lint-launcher-path)
"-c"
(str i18n-lint-config-path)
subcommand]
cli-args)
result (apply shell {:continue true
:out :inherit
:err :inherit}
cmd)]
(when (pos? (:exit result))
(System/exit (:exit result)))))
(defn- check-missing-translations
"Use logseq-i18n-lint to fail fast on missing translations before other checks."
[]
(run-i18n-lint-command! "check-missing" []))
(defn- check-translation-keys
"Use logseq-i18n-lint to detect unused translation keys."
[args]
(run-i18n-lint-command! "check-keys" args))
(defn- validate-rich-translations
"Checks that localized rich translations remain rich zero-arg functions.
Missing translations are allowed, but once a locale defines a rich key it
must preserve the same renderable contract as English."
[]
(let [invalid-dicts (lang-lint/rich-translation-mismatch-findings (get-dicts))]
(if (empty? invalid-dicts)
(println "All rich translations preserve English render contracts!")
(do
(println "These translation keys are invalid because they no longer preserve English rich render contracts:")
(task-util/print-table invalid-dicts)
(System/exit 1)))))
(defn- validate-translation-placeholders
"Checks that every localized string uses the same placeholder set as English.
Missing translations are allowed because Tongue falls back to :en, but once
a locale defines a string it must preserve the placeholder contract."
[]
(let [invalid-dicts (lang-lint/placeholder-mismatch-findings (get-dicts))]
(if (empty? invalid-dicts)
(println "All translations preserve English placeholder contracts!")
(do
(println "These translation keys are invalid because their placeholders do not match English:")
(task-util/print-table
(map #(dissoc % :default-value :localized-value) invalid-dicts))
(System/exit 1)))))
(defn validate-translations
"Runs multiple translation validations that fail fast if one of them is invalid"
[& args]
(check-missing-translations)
(validate-non-default-languages (contains? (set args) "--fix"))
(check-translation-keys args)
(validate-rich-translations)
(validate-translation-placeholders))
(defn lint-hardcoded
"Run logseq-i18n-lint to lint likely hardcoded user-facing strings in UI-oriented source files.
Use -w or --warn-only to report findings without failing and -g or --git-changed to scan
only files changed in git status."
[& args]
(run-i18n-lint-command! "lint" args))
+149
View File
@@ -0,0 +1,149 @@
(ns logseq.tasks.lang-lint)
;; Matches numbered placeholders like `{1}` in translation strings.
(def ^:private translation-placeholder-pattern
#"\{(\d+)\}")
(defn translation-placeholders
"Return the placeholder indexes referenced by translation string `value`.
Non-string values return an empty set."
[value]
(if (string? value)
(->> (re-seq translation-placeholder-pattern value)
(map second)
set)
#{}))
(defn- placeholders-compatible?
[default-value localized-value]
(or (not (string? default-value))
(not (string? localized-value))
(= (translation-placeholders default-value)
(translation-placeholders localized-value))))
(defn placeholder-mismatch-findings
"Return localized string findings whose placeholder set diverges from
English."
[dicts]
(let [en-dicts (:en dicts)]
(->> (dissoc dicts :en)
(mapcat
(fn [[lang lang-dicts]]
(keep (fn [[translation-key localized-value]]
(let [default-value (get en-dicts translation-key)]
(when (and (string? default-value)
(string? localized-value)
(not (placeholders-compatible? default-value localized-value)))
{:lang lang
:translation-key translation-key
:expected-placeholders (sort (translation-placeholders default-value))
:actual-placeholders (sort (translation-placeholders localized-value))
:default-value default-value
:localized-value localized-value})))
lang-dicts)))
(sort-by (juxt :lang :translation-key))
vec)))
(defn- rich-translation-value?
"Return true when `value` preserves the rich zero-arg translation contract.
Babashka reads dictionary `fn` forms as lists, while tests may pass actual
function values, so both representations are treated as rich translations."
[value]
(or (fn? value)
(and (seq? value)
(= 'fn (first value))
(= [] (second value)))))
(defn- value-kind
[value]
(cond
(rich-translation-value? value) :fn
(string? value) :string
(nil? value) :nil
:else :other))
(defn rich-translation-mismatch-findings
"Return localized rich-translation findings whose value kind no longer
matches the English zero-arg function contract."
[dicts]
(let [en-dicts (:en dicts)]
(->> (dissoc dicts :en)
(mapcat
(fn [[lang lang-dicts]]
(keep (fn [[translation-key default-value]]
(let [localized-present? (contains? lang-dicts translation-key)
localized-value (get lang-dicts translation-key)]
(when (and localized-present?
(rich-translation-value? default-value)
(not (rich-translation-value? localized-value)))
{:lang lang
:translation-key translation-key
:expected-value-kind :fn
:actual-value-kind (value-kind localized-value)})))
en-dicts)))
(sort-by (juxt :lang :translation-key))
vec)))
(defn identical-translation-findings
"Return localized translation findings whose defined value is identical to
English for the same key."
[dicts lang]
(let [en-dicts (:en dicts)
lang-dicts (get dicts lang)]
(->> lang-dicts
(keep (fn [[translation-key localized-value]]
(let [default-value (get en-dicts translation-key ::missing)]
(when (= default-value localized-value)
{:lang lang
:translation-key translation-key
:default-value default-value}))))
(sort-by :translation-key)
vec)))
(defn identical-translation-stats
"Return per-locale identical-to-English counts for defined translations."
[dicts]
(let [en-dicts (:en dicts)]
(->> dicts
(map (fn [[lang lang-dicts]]
{:lang lang
:translation-count (count lang-dicts)
:same-as-en-count
(count
(filter (fn [[translation-key localized-value]]
(= (get en-dicts translation-key ::missing)
localized-value))
lang-dicts))}))
(sort-by (juxt (comp - :same-as-en-count) (comp - :translation-count) :lang))
vec)))
(defn translation-summary-stats
"Return per-locale translation summary stats for overview tables."
[dicts]
(let [en-count (count (:en dicts))
same-as-en-counts (->> (identical-translation-stats dicts)
(map (juxt :lang :same-as-en-count))
(into {}))]
(->> dicts
(map (fn [[lang lang-dicts]]
{:lang lang
:translation-count (count lang-dicts)
:untranslated-count (when-not (= lang :en)
(max 0 (- en-count (count lang-dicts))))
:same-as-en-count (when-not (= lang :en)
(get same-as-en-counts lang 0))}))
vec)))
(defn sort-translation-summary-stats
"Sort translation summary stats with English first, then by untranslated
count descending, then by identical-to-English count descending."
[stats]
(let [en-stats (filter #(= :en (:lang %)) stats)
other-stats (remove #(= :en (:lang %)) stats)]
(into (vec en-stats)
(sort-by (juxt (comp - :untranslated-count)
(comp - :same-as-en-count)
:lang)
other-stats))))
+72
View File
@@ -0,0 +1,72 @@
(ns logseq.tasks.malli
"Malli related tasks"
(:require [malli.core :as m]
[malli.error :as me]
[frontend.schema.handler.plugin-config :as plugin-config-schema]
[frontend.schema.handler.global-config :as global-config-schema]
[frontend.schema.handler.repo-config :as repo-config-schema]
[logseq.graph-parser.schema.mldoc :as mldoc-schema]
[babashka.fs :as fs]
[clojure.pprint :as pprint]
[clojure.edn :as edn]))
(defn validate-plugins-edn
"Validate a plugins.edn file"
[file]
(if-let [errors (->> file
slurp
edn/read-string
(m/explain plugin-config-schema/Plugins-edn)
me/humanize)]
(do
(println "Found errors:")
(pprint/pprint errors))
(println "Valid!")))
(defn- validate-file-with-schema
"Validate a file given its schema"
[file schema]
(if-let [errors (->> file
slurp
edn/read-string
(m/explain schema)
me/humanize)]
(do
(println "Found errors:")
(pprint/pprint errors))
(println "Valid!")))
(defn validate-repo-config-edn
"Validate a repo config.edn"
[file]
(validate-file-with-schema file global-config-schema/Config-edn))
(defn validate-global-config-edn
"Validate a global config.edn"
[file]
(validate-file-with-schema file repo-config-schema/Config-edn))
(defn validate-ast
"Validate mldoc ast(s) in a file or as an EDN arg"
[file-or-edn]
(let [edn (edn/read-string
(if (fs/exists? file-or-edn) (slurp file-or-edn) file-or-edn))]
(if (and (sequential? edn) (:ast (first edn)))
;; Validate multiple asts in the format [{:file "" :ast []} ...]
;; Produced by https://github.com/logseq/nbb-logseq/tree/main/examples/from-js#graph_astmjs
(do
(println "Validating" (count edn) "files...")
(if-let [errors-by-file (seq (keep
#(when-let [errors (m/explain mldoc-schema/block-ast-with-pos-coll-schema (:ast %))]
{:file (:file %)
:errors errors})
edn))]
(do
(println "Found errors:")
(pprint/pprint errors-by-file))
(println "All files valid!")))
(if-let [errors (m/explain mldoc-schema/block-ast-with-pos-coll-schema edn)]
(do
(println "Found errors:")
(pprint/pprint errors))
(println "Valid!")))))
+19
View File
@@ -0,0 +1,19 @@
(ns logseq.tasks.spec
"Clojure spec related tasks"
(:require [clojure.spec.alpha :as s]
[cheshire.core :as json]
[frontend.spec.storage :as storage-spec]
[clojure.edn :as edn]))
;; To create file for validation, `JSON.stringify(localStorage)` in the js
;; console and copy string to file
(defn validate-local-storage
"Validate a localStorage json file"
[file]
(let [local-storage
(update-vals (json/parse-string (slurp file) keyword)
;; Not all localStorage values are edn so gracefully return.
;; For example, logseq-plugin-tabs stores data as json
#(try (edn/read-string %) (catch Throwable _ %)))]
(s/assert ::storage-spec/local-storage local-storage)
(println "Success!")))
+123
View File
@@ -0,0 +1,123 @@
(ns logseq.tasks.util
"Utils for tasks"
(:require [clojure.string :as string]
#?(:clj [babashka.fs :as fs])))
(defn- in-range?
[code-point [start end]]
(<= start code-point end))
(def ^:private zero-width-ranges
[[0x0300 0x036F]
[0x1AB0 0x1AFF]
[0x1DC0 0x1DFF]
[0x200C 0x200F]
[0x202A 0x202E]
[0x2060 0x206F]
[0x20D0 0x20FF]
[0xFE00 0xFE0F]
[0xFE20 0xFE2F]])
(def ^:private wide-ranges
[[0x1100 0x115F]
[0x2329 0x232A]
[0x2E80 0xA4CF]
[0xAC00 0xD7A3]
[0xF900 0xFAFF]
[0xFE10 0xFE19]
[0xFE30 0xFE6F]
[0xFF00 0xFF60]
[0xFFE0 0xFFE6]
[0x1F300 0x1FAFF]
[0x20000 0x3FFFD]])
(defn- code-point-width
[code-point]
(cond
(or (<= 0x0000 code-point 0x001F)
(<= 0x007F code-point 0x009F)
(some #(in-range? code-point %) zero-width-ranges))
0
(some #(in-range? code-point %) wide-ranges)
2
:else
1))
(defn display-width
[value]
(let [text (str value)]
(loop [index 0
width 0]
(if (< index #?(:clj (.length text) :cljs (.-length text)))
(let [code-point #?(:clj (.codePointAt text index)
:cljs (.codePointAt text index))]
(recur (+ index #?(:clj (Character/charCount code-point)
:cljs (if (> code-point 0xFFFF) 2 1)))
(+ width (code-point-width code-point))))
width))))
(defn- pad-left
[text width]
(let [padding (- width (display-width text))]
(str (apply str (repeat (max 0 padding) " ")) text)))
(defn- column-widths
[columns rows]
(reduce
(fn [widths column]
(assoc widths
column
(apply max
(display-width (str column))
(map #(display-width (str (get % column ""))) rows))))
{}
columns))
(defn- render-separator
[columns widths]
(str "|" (string/join "+" (map #(apply str (repeat (+ 2 (get widths %)) "-")) columns)) "|"))
(defn- render-row
[columns widths row]
(str "|"
(string/join "|" (map #(str " "
(pad-left (str (get row % "")) (get widths %))
" ")
columns))
"|"))
(defn render-table
[rows]
(when-let [columns (seq (keys (first rows)))]
(let [rows (vec rows)
widths (column-widths columns rows)
header-row (zipmap columns columns)]
(str (string/join
"\n"
(concat [(render-row columns widths header-row)
(render-separator columns widths)]
(map #(render-row columns widths %) rows)))
"\n"))))
#?(:clj
(defn file-modified-later-than?
[file comparison-instant]
(pos? (.compareTo (fs/file-time->instant (fs/last-modified-time file))
comparison-instant))))
(defn print-usage [arg-str]
(println (str "Usage: bb "
#?(:clj (System/getProperty "babashka.task")
:cljs "task")
" "
arg-str))
#?(:clj (System/exit 1)
:cljs (js/process.exit 1)))
(defn print-table
[rows]
(when-some [rendered-table (render-table rows)]
(print rendered-table))
(println "Total:" (count rows)))
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot =
process.env.LOGSEQ_STAGE_CLI_RUNTIME_REPO_ROOT ?? path.resolve(__dirname, "..");
const bundleRelativePath = "cli/_build/default/dist/logseq-cli.js";
const stagedRelativePath = "static/logseq-cli.js";
const bundlePath = path.join(repoRoot, ...bundleRelativePath.split("/"));
const bundleMapPath = `${bundlePath}.map`;
const stagedPath = path.join(repoRoot, ...stagedRelativePath.split("/"));
const stagedMapPath = `${stagedPath}.map`;
const shadowRuntimeMarkers = ["SHADOW_IMPORT", ".shadow-cljs", "cljs-runtime"];
function relative(filePath) {
return path.relative(repoRoot, filePath).split(path.sep).join("/");
}
function fail(message) {
throw new Error(message);
}
function assertBundleExists() {
if (!fs.existsSync(bundlePath)) {
fail(
`Missing CLI bundle ${relative(bundlePath)}; run \`pnpm --dir cli bundle\` before staging the CLI runtime`,
);
}
}
function assertNoShadowRuntime(content) {
for (const marker of shadowRuntimeMarkers) {
if (content.includes(marker)) {
fail(`${relative(bundlePath)} contains old Shadow runtime marker: ${marker}`);
}
}
}
function copyReadable(source, destination) {
fs.mkdirSync(path.dirname(destination), { recursive: true });
if (fs.existsSync(destination)) {
fs.chmodSync(destination, fs.statSync(destination).mode | 0o200);
}
fs.copyFileSync(source, destination);
const sourceMode = fs.statSync(source).mode & 0o777;
fs.chmodSync(destination, sourceMode | 0o444);
}
function main() {
assertBundleExists();
const content = fs.readFileSync(bundlePath, "utf8");
assertNoShadowRuntime(content);
copyReadable(bundlePath, stagedPath);
if (fs.existsSync(bundleMapPath)) {
copyReadable(bundleMapPath, stagedMapPath);
} else {
fs.rmSync(stagedMapPath, { force: true });
}
console.log(`Staged ${relative(bundlePath)} to ${relative(stagedPath)}`);
}
try {
main();
} catch (error) {
console.error(`[stage-cli-runtime] ${error.message}`);
process.exit(1);
}
@@ -0,0 +1,182 @@
#!/usr/bin/env node
'use strict';
const fs = require('node:fs/promises');
const path = require('node:path');
function usage() {
return [
'Usage: node scripts/sync-open-chrome-tab-analyze-artifact.cjs --artifact <path>',
'',
'Options:',
' --artifact <path> Path to artifact.json from sync-open-chrome-tab-simulate',
' --pretty Pretty-print JSON output',
' -h, --help Show this message',
].join('\n');
}
function parseArgs(argv) {
const result = {
artifactPath: null,
pretty: false,
help: false,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--help' || arg === '-h') {
result.help = true;
continue;
}
if (arg === '--pretty') {
result.pretty = true;
continue;
}
if (arg === '--artifact') {
const next = argv[i + 1];
if (typeof next !== 'string' || next.length === 0) {
throw new Error('--artifact must be a non-empty path');
}
result.artifactPath = next;
i += 1;
continue;
}
throw new Error('Unknown argument: ' + arg);
}
if (!result.help && !result.artifactPath) {
throw new Error('--artifact is required');
}
return result;
}
function pickFirstMismatchClient(clients) {
for (const client of clients) {
if (client && client.mismatch && typeof client.mismatch === 'object') {
return client;
}
}
return null;
}
function pickFirstTxRejectedClient(clients) {
for (const client of clients) {
if (client && client.txRejected && typeof client.txRejected === 'object') {
return client;
}
}
return null;
}
function compareRequestedPlans(clients) {
const withPlan = clients.filter((client) => Array.isArray(client?.requestedPlan) && client.requestedPlan.length > 0);
if (withPlan.length < 2) {
return { comparable: false, reason: 'not enough clients with requestedPlan' };
}
const base = withPlan[0];
const minLen = withPlan.reduce((acc, client) => Math.min(acc, client.requestedPlan.length), Infinity);
for (let i = 0; i < minLen; i += 1) {
const baseOp = base.requestedPlan[i];
for (let j = 1; j < withPlan.length; j += 1) {
const other = withPlan[j];
if (other.requestedPlan[i] !== baseOp) {
return {
comparable: true,
firstDiffIndex: i,
baseClient: base.instanceIndex,
baseOp,
otherClient: other.instanceIndex,
otherOp: other.requestedPlan[i],
};
}
}
}
return {
comparable: true,
firstDiffIndex: null,
message: 'requestedPlan prefix is identical across clients',
};
}
function summarizeClient(client) {
return {
session: client?.session || null,
instanceIndex: client?.instanceIndex ?? null,
ok: Boolean(client?.ok),
cancelled: client?.cancelled === true,
cancelledReason: client?.cancelledReason || null,
failureType: client?.failureType || null,
mismatch: client?.mismatch || null,
txRejected: client?.txRejected || null,
errorCount: Number(client?.errorCount || 0),
requestedOps: Number(client?.requestedOps || 0),
executedOps: Number(client?.executedOps || 0),
lastOps: Array.isArray(client?.opLogTail) ? client.opLogTail.slice(-20) : [],
errors: Array.isArray(client?.errors) ? client.errors.slice(-20) : [],
};
}
async function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (error) {
console.error(error.message);
console.error('\n' + usage());
process.exit(1);
return;
}
if (args.help) {
console.log(usage());
return;
}
const artifactPath = path.resolve(args.artifactPath);
const content = await fs.readFile(artifactPath, 'utf8');
const artifact = JSON.parse(content);
const clients = Array.isArray(artifact?.clients) ? artifact.clients : [];
const firstMismatch = pickFirstMismatchClient(clients);
const firstTxRejected = pickFirstTxRejectedClient(clients);
const cancelledPeers = clients
.filter((client) =>
client?.cancelledReason === 'cancelled_due_to_peer_checksum_mismatch' ||
client?.cancelledReason === 'cancelled_due_to_peer_tx_rejected'
)
.map((client) => ({
instanceIndex: client.instanceIndex,
session: client.session,
peerInstanceIndex: client.peerInstanceIndex ?? null,
cancelledReason: client.cancelledReason || null,
}));
const report = {
artifactPath,
runId: artifact?.runId || null,
createdAt: artifact?.createdAt || null,
summary: artifact?.summary || {},
failFast: artifact?.failFast || {},
mismatchCount: Number(artifact?.mismatchCount || 0),
txRejectedCount: Number(artifact?.txRejectedCount || 0),
firstMismatch: firstMismatch ? summarizeClient(firstMismatch) : null,
firstTxRejected: firstTxRejected ? summarizeClient(firstTxRejected) : null,
cancelledPeers,
requestedPlanComparison: compareRequestedPlans(clients),
clients: clients.map(summarizeClient),
};
if (args.pretty) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(JSON.stringify(report));
}
}
main().catch((error) => {
console.error(error.stack || String(error));
process.exit(1);
});
@@ -0,0 +1,146 @@
#!/usr/bin/env node
'use strict';
const { spawnSync } = require('node:child_process');
const path = require('node:path');
function usage() {
return [
'Usage: node scripts/sync-open-chrome-tab-replay-local.cjs --artifact <path> [options]',
'',
'Options:',
' --artifact <path> Path to artifact.json produced by sync-open-chrome-tab-simulate',
' --client <n> Replay one client instance index only',
' --round <n> Replay one round only',
' --pretty Pretty-print JSON output',
' -h, --help Show this message',
].join('\n');
}
function parsePositiveInteger(value, flagName) {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new Error(`${flagName} must be a positive integer`);
}
return parsed;
}
function parseArgs(argv) {
const result = {
artifact: null,
client: null,
round: null,
pretty: false,
help: false,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--help' || arg === '-h') {
result.help = true;
continue;
}
if (arg === '--pretty') {
result.pretty = true;
continue;
}
const next = argv[i + 1];
if (arg === '--artifact') {
if (typeof next !== 'string' || next.length === 0) {
throw new Error('--artifact must be a non-empty path');
}
result.artifact = next;
i += 1;
continue;
}
if (arg === '--client') {
result.client = parsePositiveInteger(next, '--client');
i += 1;
continue;
}
if (arg === '--round') {
result.round = parsePositiveInteger(next, '--round');
i += 1;
continue;
}
throw new Error(`Unknown argument: ${arg}`);
}
if (!result.help && !result.artifact) {
throw new Error('--artifact is required');
}
return result;
}
function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (error) {
console.error(error.message);
console.error('\n' + usage());
process.exit(1);
return;
}
if (args.help) {
console.log(usage());
return;
}
const artifactPath = path.resolve(args.artifact);
const dbDir = path.resolve(__dirname, '..', 'deps', 'db');
const scriptPath = 'script/replay_sync_artifact.cljs';
const commandArgs = [
'exec',
'nbb-logseq',
'-cp',
'src:script:../db-sync/src',
scriptPath,
'--artifact',
artifactPath,
];
if (args.client) {
commandArgs.push('--client', String(args.client));
}
if (args.round) {
commandArgs.push('--round', String(args.round));
}
if (args.pretty) {
commandArgs.push('--pretty');
}
const result = spawnSync('pnpm', commandArgs, {
cwd: dbDir,
stdio: ['ignore', 'pipe', 'pipe'],
encoding: 'utf8',
});
if (result.status !== 0) {
const stderr = (result.stderr || '').trim();
const stdout = (result.stdout || '').trim();
const detail = stderr || stdout;
throw new Error(
`Replay command failed (exit ${result.status ?? 'unknown'}): pnpm ${commandArgs.join(' ')}` +
(detail ? `\n${detail}` : '')
);
}
const output = result.stdout || '';
process.stdout.write(output);
}
if (require.main === module) {
try {
main();
} catch (error) {
console.error(error.stack || String(error));
process.exit(1);
}
}
module.exports = {
parseArgs,
};
File diff suppressed because it is too large. Load diff
+793
View File
@@ -0,0 +1,793 @@
#!/usr/bin/env node
'use strict';
const {
buildOperationPlan,
parseArgs,
} = require('./lib/logseq-electron-op-sim.cjs');
const DEFAULT_TARGET_TITLE = 'Logseq';
const WebSocketCtor = globalThis.WebSocket;
const DEBUG_TARGET_WAIT_TIMEOUT_MS = 30000;
const DEBUG_TARGET_RETRY_DELAY_MS = 300;
const RENDERER_READY_TIMEOUT_MS = 30000;
const RENDERER_READY_POLL_DELAY_MS = 250;
const BASE_EVALUATE_TIMEOUT_MS = 120000;
const PER_OP_EVALUATE_TIMEOUT_MS = 250;
const FALLBACK_PAGE_NAME = 'op-sim-scratch';
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function usage() {
return [
'Usage: node scripts/logseq-electron-op-sim.cjs [options]',
'',
'Options:',
' --ops <n> Total operations to execute (must be >= 200, default: 200)',
' --port <n> Electron remote debug port (default: 9333)',
' --undo-redo-delay-ms <n> Wait time after undo/redo command (default: 350)',
' -h, --help Show this message',
'',
'Prerequisite: start Logseq Electron with --remote-debugging-port=<port>.',
].join('\n');
}
function wsAddListener(ws, event, handler) {
if (typeof ws.addEventListener === 'function') {
ws.addEventListener(event, handler);
return;
}
ws.on(event, (...args) => {
if (event === 'message') {
const payload = typeof args[0] === 'string' ? args[0] : args[0].toString();
handler({ data: payload });
return;
}
handler(...args);
});
}
function createCdpClient(ws) {
let id = 0;
const pending = new Map();
wsAddListener(ws, 'message', (event) => {
const message = JSON.parse(event.data);
if (!message.id) return;
const callbacks = pending.get(message.id);
if (!callbacks) return;
pending.delete(message.id);
if (message.error) {
callbacks.reject(new Error(`CDP error on ${callbacks.method}: ${message.error.message}`));
} else {
callbacks.resolve(message.result);
}
});
wsAddListener(ws, 'close', () => {
for (const entry of pending.values()) {
entry.reject(new Error('CDP connection closed before response'));
}
pending.clear();
});
return {
send(method, params = {}, timeoutMs = 20000) {
const requestId = ++id;
const payload = JSON.stringify({ id: requestId, method, params });
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pending.delete(requestId);
reject(new Error(`Timeout waiting for ${method}`));
}, timeoutMs);
pending.set(requestId, {
method,
resolve: (result) => {
clearTimeout(timeout);
resolve(result);
},
reject: (error) => {
clearTimeout(timeout);
reject(error);
},
});
ws.send(payload);
});
},
};
}
function pickPageTarget(targets) {
const pageTargets = targets.filter(
(target) => target.type === 'page' && typeof target.webSocketDebuggerUrl === 'string'
);
if (pageTargets.length === 0) {
throw new Error('No page target found on debug endpoint');
}
return (
pageTargets.find((target) => (target.title || '').includes(DEFAULT_TARGET_TITLE)) ||
pageTargets[0]
);
}
function listPageTargets(targets) {
return targets
.filter((target) => target.type === 'page' && typeof target.webSocketDebuggerUrl === 'string')
.sort((a, b) => {
const aPreferred = (a.title || '').includes(DEFAULT_TARGET_TITLE) ? 1 : 0;
const bPreferred = (b.title || '').includes(DEFAULT_TARGET_TITLE) ? 1 : 0;
return bPreferred - aPreferred;
});
}
function closeWebSocketQuietly(ws) {
if (!ws) return;
try {
ws.close();
} catch (_error) {
// ignore close errors
}
}
async function targetHasLogseqApi(cdp) {
const evaluation = await cdp.send(
'Runtime.evaluate',
{
expression: `(() => {
const api = globalThis.logseq?.api;
return !!(
api &&
typeof api.get_current_block === 'function' &&
(
typeof api.get_current_page === 'function' ||
typeof api.get_today_page === 'function'
) &&
typeof api.append_block_in_page === 'function'
);
})()`,
returnByValue: true,
awaitPromise: false,
},
10000,
);
return evaluation?.result?.value === true;
}
function buildRendererProgram(config) {
return `(() => (async () => {
const config = ${JSON.stringify(config)};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const randomItem = (items) => items[Math.floor(Math.random() * items.length)];
const shuffle = (items) => [...items].sort(() => Math.random() - 0.5);
const describeError = (error) => String(error?.message || error);
const asPageName = (pageLike) => {
if (typeof pageLike === 'string' && pageLike.length > 0) return pageLike;
if (!pageLike || typeof pageLike !== 'object') return null;
if (typeof pageLike.name === 'string' && pageLike.name.length > 0) return pageLike.name;
if (typeof pageLike.originalName === 'string' && pageLike.originalName.length > 0) return pageLike.originalName;
if (typeof pageLike.title === 'string' && pageLike.title.length > 0) return pageLike.title;
return null;
};
const waitForEditorReady = async () => {
const deadline = Date.now() + config.readyTimeoutMs;
let lastError = null;
while (Date.now() < deadline) {
try {
if (
globalThis.logseq?.api &&
typeof logseq.api.get_current_block === 'function' &&
(
typeof logseq.api.get_current_page === 'function' ||
typeof logseq.api.get_today_page === 'function'
) &&
typeof logseq.api.append_block_in_page === 'function'
) {
return;
}
} catch (error) {
lastError = error;
}
await sleep(config.readyPollDelayMs);
}
if (lastError) {
throw new Error('Logseq editor readiness timed out: ' + describeError(lastError));
}
throw new Error('Logseq editor readiness timed out: logseq.api is unavailable');
};
const runPrefix =
typeof config.runPrefix === 'string' && config.runPrefix.length > 0
? config.runPrefix
: config.markerPrefix;
const chooseRunnableOperation = (requestedOperation, operableCount) => {
if (requestedOperation === 'move' || requestedOperation === 'delete') {
return operableCount >= 2 ? requestedOperation : 'add';
}
return requestedOperation;
};
const flattenBlocks = (nodes, acc = []) => {
if (!Array.isArray(nodes)) return acc;
for (const node of nodes) {
if (!node) continue;
acc.push(node);
if (Array.isArray(node.children) && node.children.length > 0) {
flattenBlocks(node.children, acc);
}
}
return acc;
};
const isClientBlock = (block) =>
typeof block?.content === 'string' && block.content.startsWith(config.markerPrefix);
const isOperableBlock = (block) =>
typeof block?.content === 'string' && block.content.startsWith(runPrefix);
const isClientRootBlock = (block) =>
typeof block?.content === 'string' && block.content === (config.markerPrefix + ' client-root');
const listPageBlocks = async () => {
const tree = await logseq.api.get_current_page_blocks_tree();
return flattenBlocks(tree, []);
};
const listOperableBlocks = async () => {
const flattened = await listPageBlocks();
return flattened.filter(isOperableBlock);
};
const listManagedBlocks = async () => {
const operableBlocks = await listOperableBlocks();
return operableBlocks.filter(isClientBlock);
};
const ensureClientRootBlock = async (anchorBlock) => {
const existing = (await listOperableBlocks()).find(isClientRootBlock);
if (existing?.uuid) return existing;
const inserted = await logseq.api.insert_block(anchorBlock.uuid, config.markerPrefix + ' client-root', {
sibling: true,
before: false,
focus: false,
});
if (!inserted?.uuid) {
throw new Error('Failed to create client root block');
}
return inserted;
};
const pickIndentCandidate = async (blocks) => {
for (const candidate of shuffle(blocks)) {
const prev = await logseq.api.get_previous_sibling_block(candidate.uuid);
if (prev?.uuid) return candidate;
}
return null;
};
const pickOutdentCandidate = async (blocks) => {
for (const candidate of shuffle(blocks)) {
const full = await logseq.api.get_block(candidate.uuid, { includeChildren: false });
const parentId = full?.parent?.id;
const pageId = full?.page?.id;
if (parentId && pageId && parentId !== pageId) {
return candidate;
}
}
return null;
};
const getPreviousSiblingUuid = async (uuid) => {
const prev = await logseq.api.get_previous_sibling_block(uuid);
return prev?.uuid || null;
};
const ensureIndentCandidate = async (blocks, anchorBlock, opIndex) => {
const existing = await pickIndentCandidate(blocks);
if (existing?.uuid) return existing;
const baseTarget = blocks.length > 0 ? randomItem(blocks) : anchorBlock;
const base = await logseq.api.insert_block(baseTarget.uuid, config.markerPrefix + ' indent-base-' + opIndex, {
sibling: true,
before: false,
focus: false,
});
if (!base?.uuid) {
throw new Error('Failed to create indent base block');
}
const candidate = await logseq.api.insert_block(base.uuid, config.markerPrefix + ' indent-candidate-' + opIndex, {
sibling: true,
before: false,
focus: false,
});
if (!candidate?.uuid) {
throw new Error('Failed to create indent candidate block');
}
return candidate;
};
const runIndent = async (candidate) => {
const prevUuid = await getPreviousSiblingUuid(candidate.uuid);
if (!prevUuid) {
throw new Error('No previous sibling for indent candidate');
}
await logseq.api.move_block(candidate.uuid, prevUuid, {
before: false,
children: true,
});
};
const ensureOutdentCandidate = async (blocks, anchorBlock, opIndex) => {
const existing = await pickOutdentCandidate(blocks);
if (existing?.uuid) return existing;
const candidate = await ensureIndentCandidate(blocks, anchorBlock, opIndex);
await runIndent(candidate);
return candidate;
};
const runOutdent = async (candidate) => {
const full = await logseq.api.get_block(candidate.uuid, { includeChildren: false });
const parentId = full?.parent?.id;
const pageId = full?.page?.id;
if (!parentId || !pageId || parentId === pageId) {
throw new Error('Outdent candidate is not nested');
}
const parent = await logseq.api.get_block(parentId, { includeChildren: false });
if (!parent?.uuid) {
throw new Error('Cannot resolve parent block for outdent');
}
await logseq.api.move_block(candidate.uuid, parent.uuid, {
before: false,
children: false,
});
};
const pickRandomGroup = (blocks, minSize = 1, maxSize = 3) => {
const pool = shuffle(blocks);
const lower = Math.max(1, Math.min(minSize, pool.length));
const upper = Math.max(lower, Math.min(maxSize, pool.length));
const size = lower + Math.floor(Math.random() * (upper - lower + 1));
return pool.slice(0, size);
};
const toBatchTree = (block) => ({
content: typeof block?.content === 'string' ? block.content : '',
children: Array.isArray(block?.children) ? block.children.map(toBatchTree) : [],
});
const getAnchor = async () => {
const deadline = Date.now() + config.readyTimeoutMs;
let lastError = null;
while (Date.now() < deadline) {
try {
const currentBlock = await logseq.api.get_current_block();
if (currentBlock && currentBlock.uuid) {
return currentBlock;
}
if (typeof logseq.api.get_current_page === 'function') {
const currentPage = await logseq.api.get_current_page();
const currentPageName = asPageName(currentPage);
if (currentPageName) {
const seeded = await logseq.api.append_block_in_page(
currentPageName,
config.markerPrefix + ' anchor',
{}
);
if (seeded?.uuid) return seeded;
}
}
if (typeof logseq.api.get_today_page === 'function') {
const todayPage = await logseq.api.get_today_page();
const todayPageName = asPageName(todayPage);
if (todayPageName) {
const seeded = await logseq.api.append_block_in_page(
todayPageName,
config.markerPrefix + ' anchor',
{}
);
if (seeded?.uuid) return seeded;
}
}
{
const seeded = await logseq.api.append_block_in_page(
config.fallbackPageName,
config.markerPrefix + ' anchor',
{}
);
if (seeded?.uuid) return seeded;
}
} catch (error) {
lastError = error;
}
await sleep(config.readyPollDelayMs);
}
if (lastError) {
throw new Error('Unable to resolve anchor block: ' + describeError(lastError));
}
throw new Error('Unable to resolve anchor block: open a graph and page, then retry');
};
const counts = {
add: 0,
delete: 0,
move: 0,
indent: 0,
outdent: 0,
undo: 0,
redo: 0,
copyPaste: 0,
copyPasteTreeToEmptyTarget: 0,
fallbackAdd: 0,
errors: 0,
};
const errors = [];
const operationLog = [];
await waitForEditorReady();
const anchor = await getAnchor();
await ensureClientRootBlock(anchor);
if (!(await listManagedBlocks()).length) {
await logseq.api.insert_block(anchor.uuid, config.markerPrefix + ' seed', {
sibling: true,
before: false,
focus: false,
});
}
let executed = 0;
for (let i = 0; i < config.plan.length; i += 1) {
const requested = config.plan[i];
const operable = await listOperableBlocks();
let operation = chooseRunnableOperation(requested, operable.length);
if (operation !== requested) {
counts.fallbackAdd += 1;
}
try {
await sleep(Math.floor(Math.random() * 40));
if (operation === 'add') {
const target = operable.length > 0 ? randomItem(operable) : anchor;
const content = Math.random() < 0.2 ? '' : config.markerPrefix + ' add-' + i;
const asChild = operable.length > 0 && Math.random() < 0.35;
await logseq.api.insert_block(target.uuid, content, {
sibling: !asChild,
before: false,
focus: false,
});
}
if (operation === 'copyPaste') {
const pageBlocks = await listPageBlocks();
const copyPool = (operable.length > 0 ? operable : pageBlocks).filter((b) => b?.uuid);
if (copyPool.length === 0) {
throw new Error('No blocks available for copyPaste');
}
const source = randomItem(copyPool);
const target = randomItem(copyPool);
await logseq.api.select_block(source.uuid);
await logseq.api.invoke_external_command('logseq.editor/copy');
const latestSource = await logseq.api.get_block(source.uuid);
const sourceContent = latestSource?.content || source.content || '';
const copiedContent =
config.markerPrefix + ' copy-' + i + (sourceContent ? ' :: ' + sourceContent : '');
await logseq.api.insert_block(target.uuid, copiedContent, {
sibling: true,
before: false,
focus: false,
});
}
if (operation === 'copyPasteTreeToEmptyTarget') {
const pageBlocks = await listPageBlocks();
const treePool = (operable.length >= 2 ? operable : pageBlocks).filter((b) => b?.uuid);
if (treePool.length < 2) {
throw new Error('Not enough blocks available for multi-block copy');
}
const sources = pickRandomGroup(treePool, 2, 4);
const sourceTrees = [];
for (const source of sources) {
const sourceTree = await logseq.api.get_block(source.uuid, { includeChildren: true });
if (sourceTree?.uuid) {
sourceTrees.push(sourceTree);
}
}
if (sourceTrees.length === 0) {
throw new Error('Failed to load source tree blocks');
}
const treeTarget = operable.length > 0 ? randomItem(operable) : anchor;
const emptyTarget = await logseq.api.insert_block(treeTarget.uuid, '', {
sibling: true,
before: false,
focus: false,
});
if (!emptyTarget?.uuid) {
throw new Error('Failed to create empty target block');
}
await logseq.api.update_block(emptyTarget.uuid, '');
const payload = sourceTrees.map((tree, idx) => {
const node = toBatchTree(tree);
const origin = typeof node.content === 'string' && node.content.length > 0
? ' :: ' + node.content
: '';
node.content = config.markerPrefix + ' tree-copy-' + i + '-' + idx + origin;
return node;
});
try {
await logseq.api.insert_batch_block(emptyTarget.uuid, payload, { sibling: false });
} catch (_error) {
for (const tree of sourceTrees) {
await logseq.api.insert_batch_block(emptyTarget.uuid, toBatchTree(tree), { sibling: false });
}
}
}
if (operation === 'move') {
const source = randomItem(operable);
const candidates = operable.filter((block) => block.uuid !== source.uuid);
const target = randomItem(candidates);
await logseq.api.move_block(source.uuid, target.uuid, {
before: Math.random() < 0.5,
children: false,
});
}
if (operation === 'indent') {
const candidate = await ensureIndentCandidate(operable, anchor, i);
await runIndent(candidate);
}
if (operation === 'outdent') {
const candidate = await ensureOutdentCandidate(operable, anchor, i);
await runOutdent(candidate);
}
if (operation === 'delete') {
const candidates = operable.filter((block) => block.uuid !== anchor.uuid && !isClientRootBlock(block));
const victimPool = candidates.length > 0 ? candidates : operable;
const victim = randomItem(victimPool);
if (isClientRootBlock(victim)) {
throw new Error('Skip deleting protected client root block');
}
await logseq.api.remove_block(victim.uuid);
}
if (operation === 'undo') {
await logseq.api.invoke_external_command('logseq.editor/undo');
await sleep(config.undoRedoDelayMs);
}
if (operation === 'redo') {
await logseq.api.invoke_external_command('logseq.editor/redo');
await sleep(config.undoRedoDelayMs);
}
counts[operation] += 1;
executed += 1;
operationLog.push({ index: i, requested, executedAs: operation });
} catch (error) {
counts.errors += 1;
errors.push({
index: i,
requested,
attempted: operation,
message: String(error?.message || error),
});
try {
const recoveryOperable = await listOperableBlocks();
const target = recoveryOperable.length > 0 ? randomItem(recoveryOperable) : anchor;
await logseq.api.insert_block(target.uuid, config.markerPrefix + ' recovery-' + i, {
sibling: true,
before: false,
focus: false,
});
counts.add += 1;
executed += 1;
operationLog.push({ index: i, requested, executedAs: 'add' });
} catch (recoveryError) {
errors.push({
index: i,
requested,
attempted: 'recovery-add',
message: String(recoveryError?.message || recoveryError),
});
break;
}
}
}
const finalManaged = await listManagedBlocks();
return {
ok: true,
requestedOps: config.plan.length,
executedOps: executed,
counts,
markerPrefix: config.markerPrefix,
anchorUuid: anchor.uuid,
finalManagedCount: finalManaged.length,
sampleManaged: finalManaged.slice(0, 5).map((block) => ({
uuid: block.uuid,
content: block.content,
})),
errorCount: errors.length,
errors: errors.slice(0, 20),
opLogSample: operationLog.slice(0, 20),
};
})())()`;
}
async function openWebSocket(url) {
if (!WebSocketCtor) {
throw new Error('Global WebSocket is unavailable in this Node runtime.');
}
const ws = new WebSocketCtor(url);
await new Promise((resolve, reject) => {
wsAddListener(ws, 'open', resolve);
wsAddListener(ws, 'error', reject);
});
return ws;
}
async function fetchDebugTargets(port) {
const endpoint = `http://127.0.0.1:${port}/json/list`;
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`Debug endpoint returned HTTP ${response.status} for ${endpoint}`);
}
const targets = await response.json();
if (!Array.isArray(targets)) {
throw new Error('Debug endpoint returned an invalid target list');
}
return targets;
}
async function connectToLogseqPageWebSocket(port) {
const deadline = Date.now() + DEBUG_TARGET_WAIT_TIMEOUT_MS;
let lastError = null;
while (Date.now() < deadline) {
try {
const targets = await fetchDebugTargets(port);
const pageTargets = listPageTargets(targets);
if (pageTargets.length === 0) {
throw new Error('No page target found on debug endpoint');
}
let lastTargetError = null;
for (const target of pageTargets) {
let ws = null;
try {
ws = await openWebSocket(target.webSocketDebuggerUrl);
const cdp = createCdpClient(ws);
await cdp.send('Runtime.enable');
const hasLogseqApi = await targetHasLogseqApi(cdp);
if (hasLogseqApi) {
return { ws, cdp };
}
closeWebSocketQuietly(ws);
} catch (error) {
lastTargetError = error;
closeWebSocketQuietly(ws);
}
}
throw lastTargetError || new Error('No page target exposes logseq.api yet');
} catch (error) {
lastError = error;
await sleep(DEBUG_TARGET_RETRY_DELAY_MS);
}
}
const suffix = lastError ? ` Last error: ${String(lastError.message || lastError)}` : '';
throw new Error(
`Unable to connect to a Logseq page target within ${DEBUG_TARGET_WAIT_TIMEOUT_MS}ms.` + suffix
);
}
function computeEvaluateTimeoutMs(args) {
return BASE_EVALUATE_TIMEOUT_MS + args.ops * PER_OP_EVALUATE_TIMEOUT_MS;
}
function shuffleOperationPlan(plan) {
const shuffled = Array.isArray(plan) ? [...plan] : [];
for (let i = shuffled.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
const tmp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = tmp;
}
return shuffled;
}
async function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (error) {
console.error(error.message);
console.error('\n' + usage());
process.exit(1);
return;
}
if (args.help) {
console.log(usage());
return;
}
const runPrefix = `op-sim-${Date.now()}-`;
const plan = shuffleOperationPlan(buildOperationPlan(args.ops));
const markerPrefix = `${runPrefix}client-1-`;
const { ws, cdp } = await connectToLogseqPageWebSocket(args.port);
let evaluation;
try {
evaluation = await cdp.send(
'Runtime.evaluate',
{
expression: buildRendererProgram({
runPrefix,
markerPrefix,
plan,
undoRedoDelayMs: args.undoRedoDelayMs,
readyTimeoutMs: RENDERER_READY_TIMEOUT_MS,
readyPollDelayMs: RENDERER_READY_POLL_DELAY_MS,
fallbackPageName: FALLBACK_PAGE_NAME,
}),
awaitPromise: true,
returnByValue: true,
},
computeEvaluateTimeoutMs(args),
);
} finally {
ws.close();
}
if (evaluation?.exceptionDetails) {
const detail = evaluation.exceptionDetails.text || evaluation.exceptionDetails.exception?.description;
throw new Error(`Runtime.evaluate failed: ${detail || 'unknown renderer exception'}`);
}
const value = evaluation?.result?.value;
if (!value) {
throw new Error('Unexpected empty Runtime.evaluate result');
}
console.log(JSON.stringify(value, null, 2));
if (!value.ok || value.executedOps < args.ops) {
process.exitCode = 2;
}
}
main().catch((error) => {
console.error(error.stack || String(error));
process.exit(1);
});
+450
View File
@@ -0,0 +1,450 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync } from "node:fs";
import os from "node:os";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const readText = (relativePath) =>
fs.readFileSync(path.join(repoRoot, relativePath), "utf8");
const readJson = (relativePath) =>
JSON.parse(readText(relativePath));
const rootPackage = readJson("package.json");
const desktopPackage = readJson("resources/package.json");
const zvecOptionalRuntimeDependencies = [
"@zvec/bindings-darwin-arm64",
"@zvec/bindings-linux-arm64",
"@zvec/bindings-linux-x64",
"@zvec/bindings-win32-x64",
"@zvec/zvec",
];
const assertNotContains = (text, needle, label) => {
assert.equal(
text.includes(needle),
false,
`${label} should not contain ${needle}`,
);
};
const assertNoShadowRuntime = (text, label) => {
for (const needle of ["SHADOW_IMPORT", ".shadow-cljs", "cljs-runtime"]) {
assertNotContains(text, needle, label);
}
};
const assertRootScriptDoesNotBuildShadowCli = (scriptName, command) => {
assert.ok(command, `package.json should define ${scriptName}`);
assert.doesNotMatch(
command,
/clojure -[MA]:cljs (?:watch|compile|release)[^"]*\blogseq-cli\b/,
`${scriptName} should not build the old Shadow CLI`,
);
};
const assertCliReleaseCommand = (command, label) => {
assert.match(command, /pnpm --dir cli bundle/, `${label} should bundle cli/`);
assert.match(
command,
/node \.\/scripts\/stage-cli-runtime\.mjs/,
`${label} should stage the cli/ bundle`,
);
};
const filesUnder = (relativePath) => {
const absolutePath = path.join(repoRoot, relativePath);
if (!fs.existsSync(absolutePath)) {
return [];
}
const stat = fs.statSync(absolutePath);
if (stat.isFile()) {
return [relativePath];
}
return fs
.readdirSync(absolutePath, { withFileTypes: true })
.flatMap((entry) => {
const entryPath = path.join(relativePath, entry.name);
return entry.isDirectory() ? filesUnder(entryPath) : [entryPath];
});
};
const assertFilesDoNotMatch = (relativePaths, pattern, label) => {
const matches = relativePaths.flatMap((relativePath) => {
const text = readText(relativePath);
return pattern.test(text) ? [relativePath] : [];
});
assert.deepEqual(matches, [], `${label} should not contain ${pattern}`);
};
const workflow = readText(".github/workflows/deps-cli.yml");
assertNotContains(workflow, "deps/cli", "deps-cli workflow");
assert.match(workflow, /cli\/\*\*/, "workflow should watch cli/ sources");
assert.match(workflow, /pnpm cli:release/, "workflow should build new CLI");
assertNotContains(workflow, "clojure -M:cljs release logseq-cli", "deps-cli workflow");
assert.match(workflow, /pnpm db-worker-node:release:bundle/, "workflow should build bundled db-worker-node runtime");
assert.match(workflow, /node scripts\/prepare-cli-package\.mjs/, "workflow should prepare publish package");
assert.match(workflow, /working-directory: dist\/cli-package/, "workflow should publish prepared package");
const buildWorkflow = readText(".github/workflows/build.yml");
assert.match(buildWorkflow, /pnpm cli:release/, "db graph workflow should build release CLI");
assertNotContains(buildWorkflow, "clojure -M:cljs release logseq-cli", "db graph workflow");
assert.match(buildWorkflow, /pnpm db-worker-node:release:bundle/, "db graph workflow should build release db-worker-node runtime");
assert.match(buildWorkflow, /pnpm --dir dist\/cli-package install --prod --ignore-workspace/, "db graph workflow should install prepared CLI package dependencies");
assert.match(buildWorkflow, /libsecret-1-0/, "db graph workflow should install keytar's Linux runtime dependency");
assert.match(buildWorkflow, /pnpm --dir dist\/cli-package pack --pack-destination \.\.\//, "db graph workflow should verify the prepared CLI package with pnpm pack");
assertNotContains(buildWorkflow, "create_graph_with_schema_org.cljs ./cli-root/graphs/schema-graph --subset", "db graph workflow");
assert.match(buildWorkflow, /node dist\/cli-package\/dist\/logseq\.js --root-dir scripts\/cli-root/, "db graph workflow should test packaged CLI");
assert.match(buildWorkflow, /node dist\/cli-package\/dist\/logseq\.js --root-dir scripts\/cli-root.+--timeout-ms 3000/, "db graph workflow should use a 3s CLI request timeout for packaged CLI graph commands");
assert.match(buildWorkflow, /--graph schema-graph --timeout-ms 120000/, "db graph workflow should allow the full schema graph validation to finish in CI");
assertNotContains(buildWorkflow, "clojure -M:cljs compile logseq-cli", "db graph workflow");
assertNotContains(buildWorkflow, "pnpm db-worker-node:compile:bundle", "db graph workflow");
const desktopReleaseWorkflow = readText(".github/workflows/build-desktop-release.yml");
assert.match(
desktopReleaseWorkflow,
/OCAML_VERSION: '5\.1\.1'/,
"desktop release workflow should define the OCaml version used by cli/",
);
assert.match(
desktopReleaseWorkflow,
/uses: ocaml\/setup-ocaml@v3/,
"desktop release workflow should set up OCaml before building cli/",
);
assert.match(
desktopReleaseWorkflow,
/working-directory: cli\s+run: opam install \. --deps-only --with-test --yes/,
"desktop release workflow should install cli/ OCaml deps",
);
assert.match(
desktopReleaseWorkflow,
/pnpm --dir cli install --frozen-lockfile --ignore-workspace/,
"desktop release workflow should install cli/ pnpm deps",
);
assert.match(
desktopReleaseWorkflow,
/opam exec -- pnpm cli:release/,
"desktop release workflow should build and stage the OCaml CLI",
);
assert.ok(
desktopReleaseWorkflow.indexOf("opam exec -- pnpm cli:release") <
desktopReleaseWorkflow.indexOf("pnpm desktop:prepare-runtime-js"),
"desktop release workflow should stage the CLI before preparing desktop runtime scripts",
);
assertNotContains(
desktopReleaseWorkflow,
"clojure -M:cljs release logseq-cli",
"desktop release workflow",
);
const shadowCljs = readText("shadow-cljs.edn");
assertNotContains(shadowCljs, ":logseq-cli", "shadow-cljs.edn");
assertCliReleaseCommand(rootPackage.scripts?.["cli:release"], "cli:release");
for (const [scriptName, command] of Object.entries(rootPackage.scripts ?? {})) {
assertRootScriptDoesNotBuildShadowCli(scriptName, command);
}
const gulpfile = readText("gulpfile.js");
assert.match(
gulpfile,
/pnpm cli:release/,
"Electron maker preparation should stage the CLI runtime",
);
assert.ok(
gulpfile.indexOf("pnpm cli:release") <
gulpfile.indexOf("pnpm desktop:prepare-runtime-js"),
"Electron maker preparation should stage the CLI before preparing desktop runtime scripts",
);
const stageScriptPath = path.join(repoRoot, "scripts", "stage-cli-runtime.mjs");
assert.equal(
fs.existsSync(stageScriptPath),
true,
"scripts/stage-cli-runtime.mjs should exist",
);
const stageScript = readText("scripts/stage-cli-runtime.mjs");
assert.match(
stageScript,
/cli[\\/]_build[\\/]default[\\/]dist[\\/]logseq-cli\.js/,
"stage script should read cli/_build/default/dist/logseq-cli.js",
);
assert.match(
stageScript,
/static[\\/]logseq-cli\.js/,
"stage script should write static/logseq-cli.js",
);
for (const needle of ["SHADOW_IMPORT", ".shadow-cljs", "cljs-runtime"]) {
assert.match(
stageScript,
new RegExp(needle.replace(".", "\\.")),
`stage script should reject ${needle}`,
);
}
const runStageCliRuntime = (fixtureRoot) =>
execFileSync(process.execPath, ["scripts/stage-cli-runtime.mjs"], {
cwd: repoRoot,
env: {
...process.env,
LOGSEQ_STAGE_CLI_RUNTIME_REPO_ROOT: fixtureRoot,
},
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
const makeStageFixture = () =>
mkdtempSync(path.join(os.tmpdir(), "logseq-stage-cli-"));
{
const fixtureRoot = makeStageFixture();
assert.throws(
() => runStageCliRuntime(fixtureRoot),
/cli\/_build\/default\/dist\/logseq-cli\.js/,
"stage script should fail when the cli/ bundle is missing",
);
}
{
const fixtureRoot = makeStageFixture();
const sourcePath = path.join(
fixtureRoot,
"cli",
"_build",
"default",
"dist",
"logseq-cli.js",
);
fs.mkdirSync(path.dirname(sourcePath), { recursive: true });
fs.writeFileSync(sourcePath, "console.log('SHADOW_IMPORT');\n");
assert.throws(
() => runStageCliRuntime(fixtureRoot),
/SHADOW_IMPORT/,
"stage script should reject Shadow runtime markers",
);
}
{
const fixtureRoot = makeStageFixture();
const sourcePath = path.join(
fixtureRoot,
"cli",
"_build",
"default",
"dist",
"logseq-cli.js",
);
const stagedPath = path.join(fixtureRoot, "static", "logseq-cli.js");
const staleMapPath = path.join(fixtureRoot, "static", "logseq-cli.js.map");
fs.mkdirSync(path.dirname(sourcePath), { recursive: true });
fs.mkdirSync(path.dirname(staleMapPath), { recursive: true });
fs.writeFileSync(sourcePath, "console.log('new cli');\n");
fs.writeFileSync(staleMapPath, "{}\n");
const output = runStageCliRuntime(fixtureRoot);
assert.equal(
fs.readFileSync(stagedPath, "utf8"),
"console.log('new cli');\n",
);
assert.equal(
fs.existsSync(staleMapPath),
false,
"stage script should remove stale root sourcemap",
);
assert.match(output, /cli\/_build\/default\/dist\/logseq-cli\.js/);
assert.match(output, /static\/logseq-cli\.js/);
}
{
const fixtureRoot = makeStageFixture();
const sourcePath = path.join(
fixtureRoot,
"cli",
"_build",
"default",
"dist",
"logseq-cli.js",
);
const stagedPath = path.join(fixtureRoot, "static", "logseq-cli.js");
fs.mkdirSync(path.dirname(sourcePath), { recursive: true });
fs.mkdirSync(path.dirname(stagedPath), { recursive: true });
fs.writeFileSync(sourcePath, "console.log('first');\n");
fs.writeFileSync(stagedPath, "console.log('old');\n");
fs.chmodSync(stagedPath, 0o444);
runStageCliRuntime(fixtureRoot);
assert.equal(
fs.readFileSync(stagedPath, "utf8"),
"console.log('first');\n",
"stage script should overwrite an existing read-only staged file",
);
}
assert.equal(
fs.existsSync(path.join(repoRoot, "deps/cli/package.json")),
false,
"old deps/cli package should be removed",
);
const depsEdn = readText("deps.edn");
assertNotContains(depsEdn, 'logseq/cli', "deps.edn");
assertNotContains(depsEdn, '"deps/cli"', "deps.edn");
const bbEdn = readText("bb.edn");
assertNotContains(bbEdn, "legacy cli", "bb.edn");
assertNotContains(bbEdn, "../cli/src", "bb.edn");
const lintTask = readText("scripts/src/logseq/tasks/dev/lint.clj");
assertNotContains(lintTask, '"deps/cli"', "lint task");
const lintDepsTask = readText("scripts/src/logseq/tasks/dev/lint_test_deps.clj");
assertNotContains(lintDepsTask, '"deps/cli"', "lint/test deps task");
for (const dependencyName of zvecOptionalRuntimeDependencies) {
assert.equal(
rootPackage.dependencies?.[dependencyName],
undefined,
`${dependencyName} should not be a hard root runtime dependency`,
);
assert.ok(
rootPackage.optionalDependencies?.[dependencyName],
`${dependencyName} should be an optional root runtime dependency`,
);
assert.equal(
desktopPackage.dependencies?.[dependencyName],
undefined,
`${dependencyName} should not be a hard desktop runtime dependency`,
);
assert.ok(
desktopPackage.optionalDependencies?.[dependencyName],
`${dependencyName} should be an optional desktop runtime dependency`,
);
}
assert.equal(
fs.existsSync(path.join(repoRoot, "src/main/logseq/cli/common/mcp/server.cljs")),
false,
"CLI sources should not include an MCP server",
);
assertFilesDoNotMatch(
[
...filesUnder("src/main/logseq/cli"),
...filesUnder("src/test/logseq/cli"),
"scripts/prepare-cli-package.mjs",
],
/logseq\.cli\.common\.mcp|modelcontextprotocol|zod\/v3|mcp-server/,
"CLI sources and package preparation",
);
const prepareCliPackageScript = readText("scripts/prepare-cli-package.mjs");
assert.match(
prepareCliPackageScript,
/static[\\/]logseq-cli\.js/,
"package preparation should package the staged CLI",
);
assert.match(
prepareCliPackageScript,
/cli[\\/]_build[\\/]default[\\/]dist[\\/]logseq-cli\.js/,
"package preparation should compare the staged CLI against the cli/ bundle",
);
for (const needle of ["SHADOW_IMPORT", ".shadow-cljs", "cljs-runtime"]) {
assert.match(
prepareCliPackageScript,
new RegExp(needle.replace(".", "\\.")),
`package preparation should reject ${needle}`,
);
}
const prepareDesktopRuntimeScript = readText(
"scripts/prepare-desktop-runtime-js.mjs",
);
assert.match(
prepareDesktopRuntimeScript,
/static[\\/]logseq-cli\.js/,
"desktop runtime preparation should read the staged CLI",
);
assert.match(
prepareDesktopRuntimeScript,
/static[\\/]js[\\/]logseq-cli\.js/,
"desktop runtime preparation should write static/js/logseq-cli.js",
);
assert.match(
prepareDesktopRuntimeScript,
/cli[\\/]_build[\\/]default[\\/]dist[\\/]logseq-cli\.js/,
"desktop runtime preparation should compare the staged CLI against the cli/ bundle",
);
assert.match(
prepareDesktopRuntimeScript,
/fs\.chmod\(to, stats\.mode \| 0o200\)/,
"desktop runtime preparation should overwrite read-only staged runtime files",
);
assertNotContains(
prepareDesktopRuntimeScript,
'fs.rm(path.join(staticDir, "logseq-cli.js")',
"desktop runtime preparation should keep root staged CLI available",
);
assertNotContains(
prepareDesktopRuntimeScript,
'fs.rm(path.join(staticDir, "db-worker-node.js")',
"desktop runtime preparation should keep root staged db-worker-node available",
);
execFileSync(process.execPath, ["scripts/prepare-cli-package.mjs"], {
cwd: repoRoot,
stdio: "pipe",
});
const packageRoot = path.join(repoRoot, "dist/cli-package");
const packageJson = JSON.parse(
fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"),
);
assert.equal(packageJson.name, "@logseq/cli");
assert.equal(packageJson.bin.logseq, "dist/logseq.js");
assert.equal(packageJson.private, undefined);
assert.equal(packageJson.dependencies?.["@modelcontextprotocol/sdk"], undefined);
assert.equal(packageJson.dependencies?.zod, undefined);
assert.ok(packageJson.dependencies?.["@js-joda/core"], "publish package should include @js-joda/core for release artifacts");
assert.ok(packageJson.dependencies?.keytar, "publish package should include keytar for db-worker-node");
assert.ok(packageJson.dependencies?.["string-width"], "publish package should include string-width for CLI rendering");
for (const dependencyName of zvecOptionalRuntimeDependencies) {
assert.equal(
packageJson.dependencies?.[dependencyName],
undefined,
`${dependencyName} should not be a hard publish package dependency`,
);
assert.ok(
packageJson.optionalDependencies?.[dependencyName],
`${dependencyName} should be an optional publish package dependency`,
);
}
assert.deepEqual(packageJson.pnpm?.onlyBuiltDependencies, [
"@zvec/zvec",
"better-sqlite3",
"keytar",
]);
assert.deepEqual(packageJson.files, [
"dist/logseq.js",
"static/logseq-cli.js",
"static/js/db-worker-node.js",
"static/js/db-worker-node-assets.json",
".agents/skills/logseq-cli/SKILL.md",
]);
for (const relativePath of packageJson.files) {
assert.equal(
fs.existsSync(path.join(packageRoot, relativePath)),
true,
`publish package should include ${relativePath}`,
);
}
assertNoShadowRuntime(readText("static/logseq-cli.js"), "root CLI release artifact");
assertNoShadowRuntime(
fs.readFileSync(path.join(packageRoot, "static/logseq-cli.js"), "utf8"),
"publish package CLI release artifact",
);
@@ -0,0 +1,68 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import test from 'node:test'
import {
findUnsupportedIOSFontAssets,
} from '../../lib/check-ios-web-fonts.mjs'
test('findUnsupportedIOSFontAssets rejects woff and woff2 files and CSS references', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'logseq-ios-fonts-'))
const assetRoot = path.join(tempDir, 'public')
const fontDir = path.join(assetRoot, 'css', 'fonts')
fs.mkdirSync(fontDir, { recursive: true })
fs.writeFileSync(path.join(fontDir, 'KaTeX_Main-Regular.ttf'), '')
fs.writeFileSync(path.join(fontDir, 'KaTeX_Main-Regular.woff'), '')
fs.writeFileSync(path.join(fontDir, 'KaTeX_Main-Regular.woff2'), '')
fs.writeFileSync(
path.join(assetRoot, 'css', 'style.css'),
[
'@font-face{src:url(fonts/KaTeX_Main-Regular.woff) format("woff")}',
'@font-face{src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2")}',
'@font-face{src:url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}',
].join('\n'))
try {
const result = findUnsupportedIOSFontAssets({
repoRoot: tempDir,
assetRoots: [assetRoot],
})
assert.deepEqual(result.fontFiles, [
'public/css/fonts/KaTeX_Main-Regular.woff',
'public/css/fonts/KaTeX_Main-Regular.woff2',
])
assert.deepEqual(result.cssFiles, [
'public/css/style.css',
])
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('findUnsupportedIOSFontAssets accepts ttf-only assets', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'logseq-ios-fonts-'))
const assetRoot = path.join(tempDir, 'public')
const fontDir = path.join(assetRoot, 'css', 'fonts')
fs.mkdirSync(fontDir, { recursive: true })
fs.writeFileSync(path.join(fontDir, 'KaTeX_Main-Regular.ttf'), '')
fs.writeFileSync(
path.join(assetRoot, 'css', 'style.css'),
'@font-face{src:url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}')
try {
const result = findUnsupportedIOSFontAssets({
repoRoot: tempDir,
assetRoots: [assetRoot],
})
assert.deepEqual(result.fontFiles, [])
assert.deepEqual(result.cssFiles, [])
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
@@ -0,0 +1,13 @@
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
import test from 'node:test'
const require = createRequire(import.meta.url)
test('gulpfile registers app watch tasks', () => {
const gulpfile = require('../../../gulpfile.js')
assert.equal(typeof gulpfile.watch, 'function')
assert.equal(typeof gulpfile.watchMobile, 'function')
assert.equal(typeof gulpfile.build, 'function')
})
@@ -0,0 +1,84 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const {
buildOperationPlan,
chooseRunnableOperation,
parseArgs,
} = require('../../lib/logseq-electron-op-sim.cjs');
test('buildOperationPlan generates requested length and all operation kinds', () => {
const plan = buildOperationPlan(500);
assert.equal(plan.length, 500);
assert.deepEqual(plan.slice(0, 9), [
'add',
'copyPaste',
'copyPasteTreeToEmptyTarget',
'move',
'indent',
'outdent',
'delete',
'undo',
'redo',
]);
const kinds = new Set(plan);
assert.deepEqual(
kinds,
new Set([
'add',
'copyPaste',
'copyPasteTreeToEmptyTarget',
'move',
'indent',
'outdent',
'delete',
'undo',
'redo',
]),
);
});
test('buildOperationPlan rejects invalid total operation count', () => {
assert.throws(() => buildOperationPlan(0), /positive integer/);
assert.throws(() => buildOperationPlan(-1), /positive integer/);
assert.throws(() => buildOperationPlan(12.5), /positive integer/);
assert.throws(() => buildOperationPlan('500'), /positive integer/);
});
test('chooseRunnableOperation falls back to add when operation preconditions are unmet', () => {
assert.equal(chooseRunnableOperation('copyPaste', 0), 'add');
assert.equal(chooseRunnableOperation('copyPasteTreeToEmptyTarget', 0), 'add');
assert.equal(chooseRunnableOperation('move', 1), 'add');
assert.equal(chooseRunnableOperation('indent', 1), 'add');
assert.equal(chooseRunnableOperation('delete', 1), 'add');
assert.equal(chooseRunnableOperation('move', 2), 'move');
assert.equal(chooseRunnableOperation('indent', 2), 'indent');
assert.equal(chooseRunnableOperation('outdent', 1), 'outdent');
assert.equal(chooseRunnableOperation('delete', 2), 'delete');
assert.equal(chooseRunnableOperation('undo', 0), 'undo');
assert.equal(chooseRunnableOperation('redo', 0), 'redo');
});
test('parseArgs defaults to 500 ops on default debug port', () => {
const args = parseArgs([]);
assert.equal(args.ops, 500);
assert.equal(args.port, 9333);
assert.equal(args.undoRedoDelayMs, 350);
});
test('parseArgs supports overrides', () => {
const args = parseArgs(['--ops', '750', '--port', '9444', '--undo-redo-delay-ms', '200']);
assert.equal(args.ops, 750);
assert.equal(args.port, 9444);
assert.equal(args.undoRedoDelayMs, 200);
});
test('parseArgs rejects invalid numbers', () => {
assert.throws(() => parseArgs(['--ops', '0']), /--ops must be a positive integer/);
assert.throws(() => parseArgs(['--ops', '499']), /--ops must be at least 500/);
assert.throws(() => parseArgs(['--port', '-1']), /--port must be a positive integer/);
assert.throws(() => parseArgs(['--undo-redo-delay-ms', '-1']), /--undo-redo-delay-ms must be a non-negative integer/);
});
@@ -0,0 +1,446 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {
parseArgs,
isRetryableAgentBrowserError,
buildCleanupTodayPageProgram,
classifySimulationFailure,
buildRejectedResultEntry,
extractChecksumMismatchDetailsFromError,
extractTxRejectedDetailsFromError,
buildRunArtifact,
createSeededRng,
shuffleOperationPlan,
extractReplayContext,
buildSimulationOperationPlan,
mergeOutlinerCoverageIntoRound,
ALL_OUTLINER_OP_COVERAGE_OPS,
} = require('../../sync-open-chrome-tab-simulate.cjs');
const OUTLINER_OP_SCHEMA_PATH = path.resolve(
__dirname,
'../../../deps/outliner/src/logseq/outliner/op.cljs'
);
const OUTLINER_OP_CONSTRUCT_PATH = path.resolve(
__dirname,
'../../../deps/outliner/src/logseq/outliner/op/construct.cljc'
);
function extractSection(sourceText, startToken, endToken) {
const start = sourceText.indexOf(startToken);
if (start < 0) {
throw new Error(`Missing start token: ${startToken}`);
}
const end = sourceText.indexOf(endToken, start);
if (end < 0) {
throw new Error(`Missing end token: ${endToken}`);
}
return sourceText.slice(start, end);
}
function parseOpSchemaOps(sourceText) {
const section = extractSection(
sourceText,
'(def ^:private ^:large-vars/data-var op-schema',
'(def ^:private ops-schema'
);
const ops = new Set();
for (const match of section.matchAll(/\[\:([a-z0-9-]+)\s*\n\s+\[:catn/g)) {
ops.add(match[1]);
}
return [...ops];
}
function parseSemanticOps(sourceText) {
const section = extractSection(
sourceText,
'(def ^:api semantic-outliner-ops',
'(def ^:private transient-block-keys'
);
const setStart = section.indexOf('#{');
const setEnd = section.indexOf('}', setStart);
if (setStart < 0 || setEnd < 0 || setEnd <= setStart) {
throw new Error('Failed to parse semantic-outliner-ops set');
}
const setText = section.slice(setStart + 2, setEnd);
const ops = new Set();
for (const match of setText.matchAll(/:([a-z0-9-]+)/g)) {
ops.add(match[1]);
}
return [...ops];
}
test('isRetryableAgentBrowserError treats transient CDP navigation closures as retryable', () => {
const navigationClosed = new Error(
'CDP error (Runtime.evaluate): Inspected target navigated or closed'
);
const contextDestroyed = new Error(
'CDP error (Runtime.evaluate): Execution context was destroyed.'
);
const responseChannelClosed = new Error('CDP response channel closed');
const pageStillLoading = new Error(
'Operation timed out. The page may still be loading or the element may not exist.'
);
assert.equal(isRetryableAgentBrowserError(navigationClosed), true);
assert.equal(isRetryableAgentBrowserError(contextDestroyed), true);
assert.equal(isRetryableAgentBrowserError(responseChannelClosed), true);
assert.equal(isRetryableAgentBrowserError(pageStillLoading), true);
assert.equal(
isRetryableAgentBrowserError(new Error('Evaluation error: Failed to create client root block')),
false
);
});
test('parseArgs defaults keep today-journal cleanup enabled', () => {
const args = parseArgs([]);
assert.equal(args.simulationPage, undefined);
assert.equal(args.opProfile, 'fast');
assert.equal(args.scenario, 'online');
assert.equal(args.opTimeoutMs, 1000);
assert.equal(args.cleanupTodayPage, true);
});
test('parseArgs accepts offline simulation scenario', () => {
const args = parseArgs(['--scenario', 'offline']);
assert.equal(args.scenario, 'offline');
});
test('parseArgs rejects unsupported simulation scenario', () => {
assert.throws(
() => parseArgs(['--scenario', 'invalid-mode']),
/--scenario must be one of: online, offline/
);
});
test('cleanup program targets today journal APIs', () => {
const program = buildCleanupTodayPageProgram();
assert.match(program, /get_today_page/);
assert.doesNotMatch(program, /testing journal/i);
});
test('classifySimulationFailure detects checksum mismatch failures', () => {
const mismatchError = new Error(
'Evaluation error: Error: checksum mismatch rtc-log detected: {"type":":rtc.log/checksum-mismatch"}'
);
const timeoutError = new Error('Operation timed out. The page may still be loading');
assert.equal(classifySimulationFailure(mismatchError), 'checksum_mismatch');
assert.equal(classifySimulationFailure(timeoutError), 'other');
});
test('classifySimulationFailure detects tx-rejected failures', () => {
const txRejectedError = new Error(
'Evaluation error: Error: tx rejected rtc-log detected: {"type":":rtc.log/tx-rejected","reason":"db transact failed"}'
);
assert.equal(classifySimulationFailure(txRejectedError), 'tx_rejected');
});
test('classifySimulationFailure treats opfs access-handle lock errors as other', () => {
const opfsLockError = new Error(
"NoModificationAllowedError: Failed to execute 'createSyncAccessHandle' on 'FileSystemFileHandle'"
);
assert.equal(classifySimulationFailure(opfsLockError), 'other');
});
test('buildRejectedResultEntry marks peer as cancelled after checksum mismatch fail-fast', () => {
const failFastState = {
sourceIndex: 0,
reasonType: 'checksum_mismatch',
};
const peer = buildRejectedResultEntry(
'logseq-op-sim-2',
1,
new Error('Command timed out'),
failFastState
);
assert.equal(peer.cancelled, true);
assert.equal(peer.cancelledReason, 'cancelled_due_to_peer_checksum_mismatch');
assert.equal(peer.peerInstanceIndex, 1);
const source = buildRejectedResultEntry(
'logseq-op-sim-1',
0,
new Error('checksum mismatch rtc-log detected'),
failFastState
);
assert.equal(source.cancelled, undefined);
assert.equal(source.failureType, 'checksum_mismatch');
});
test('buildRejectedResultEntry marks peer as cancelled after tx-rejected fail-fast', () => {
const failFastState = {
sourceIndex: 1,
reasonType: 'tx_rejected',
};
const peer = buildRejectedResultEntry(
'logseq-op-sim-1',
0,
new Error('Command timed out'),
failFastState
);
assert.equal(peer.cancelled, true);
assert.equal(peer.cancelledReason, 'cancelled_due_to_peer_tx_rejected');
assert.equal(peer.peerInstanceIndex, 2);
const source = buildRejectedResultEntry(
'logseq-op-sim-2',
1,
new Error('tx rejected rtc-log detected'),
failFastState
);
assert.equal(source.cancelled, undefined);
assert.equal(source.failureType, 'tx_rejected');
});
test('buildRejectedResultEntry does not cancel peer on opfs lock fail-fast reason', () => {
const failFastState = {
sourceIndex: 0,
reasonType: 'opfs_access_handle_lock',
};
const peer = buildRejectedResultEntry(
'logseq-op-sim-2',
1,
new Error('Command timed out'),
failFastState
);
assert.equal(peer.cancelled, undefined);
assert.equal(peer.failureType, 'other');
});
test('extractChecksumMismatchDetailsFromError parses rtc-log payload JSON', () => {
const errorText =
'Evaluation error: Error: checksum mismatch rtc-log detected: {"type":":rtc.log/checksum-mismatch","messageType":"tx/batch/ok","localTx":10,"remoteTx":10,"localChecksum":"aa","remoteChecksum":"bb"}';
const parsed = extractChecksumMismatchDetailsFromError(errorText);
assert.deepEqual(parsed, {
type: ':rtc.log/checksum-mismatch',
messageType: 'tx/batch/ok',
localTx: 10,
remoteTx: 10,
localChecksum: 'aa',
remoteChecksum: 'bb',
});
});
test('extractTxRejectedDetailsFromError parses rtc-log payload JSON', () => {
const errorText =
'Evaluation error: Error: tx rejected rtc-log detected: {"type":":rtc.log/tx-rejected","messageType":"tx/reject","reason":"db transact failed","remoteTx":3}';
const parsed = extractTxRejectedDetailsFromError(errorText);
assert.deepEqual(parsed, {
type: ':rtc.log/tx-rejected',
messageType: 'tx/reject',
reason: 'db transact failed',
remoteTx: 3,
});
});
test('buildRunArtifact includes mismatch diagnostics and per-client summaries', () => {
const output = {
ok: false,
instances: 2,
successCount: 0,
failureCount: 2,
results: [
{
session: 'logseq-op-sim-1',
instanceIndex: 1,
ok: false,
error:
'Evaluation error: Error: checksum mismatch rtc-log detected: {"type":":rtc.log/checksum-mismatch","localChecksum":"aa","remoteChecksum":"bb"}',
},
{
session: 'logseq-op-sim-2',
instanceIndex: 2,
ok: false,
cancelled: true,
cancelledReason: 'cancelled_due_to_peer_tx_rejected',
error:
'Evaluation error: Error: tx rejected rtc-log detected: {"type":":rtc.log/tx-rejected","reason":"db transact failed","remoteTx":12}',
},
],
};
const artifact = buildRunArtifact({
output,
args: { ops: 100, instances: 2 },
runContext: { runId: 'run-1', runPrefix: 'op-sim-run-1-' },
failFastState: { sourceIndex: 0, reasonType: 'checksum_mismatch' },
});
assert.equal(artifact.runId, 'run-1');
assert.equal(artifact.failFast.reasonType, 'checksum_mismatch');
assert.equal(artifact.mismatchCount, 1);
assert.equal(artifact.txRejectedCount, 1);
assert.equal(artifact.clients.length, 2);
assert.equal(artifact.clients[0].mismatch?.remoteChecksum, 'bb');
assert.equal(artifact.clients[1].txRejected?.reason, 'db transact failed');
});
test('parseArgs accepts seed for deterministic simulation', () => {
const args = parseArgs(['--seed', 'abc123']);
assert.equal(args.seed, 'abc123');
});
test('createSeededRng produces deterministic sequence for same seed', () => {
const a = createSeededRng('same-seed');
const b = createSeededRng('same-seed');
const seqA = [a(), a(), a(), a(), a()];
const seqB = [b(), b(), b(), b(), b()];
assert.deepEqual(seqA, seqB);
});
test('shuffleOperationPlan is deterministic with seeded rng', () => {
const plan = ['a', 'b', 'c', 'd', 'e', 'f'];
const shuffledA = shuffleOperationPlan(plan, createSeededRng('seed-1'));
const shuffledB = shuffleOperationPlan(plan, createSeededRng('seed-1'));
const shuffledC = shuffleOperationPlan(plan, createSeededRng('seed-2'));
assert.deepEqual(shuffledA, shuffledB);
assert.notDeepEqual(shuffledA, shuffledC);
});
test('parseArgs accepts replay artifact path', () => {
const args = parseArgs(['--replay', 'tmp/db-sync-repro/run-1/artifact.json']);
assert.equal(args.replay, 'tmp/db-sync-repro/run-1/artifact.json');
});
test('extractReplayContext returns args override and fixed client plans', () => {
const artifact = {
args: { ops: 100, instances: 2, seed: 'abc' },
clients: [
{ instanceIndex: 1, requestedPlan: ['add', 'move'] },
{ instanceIndex: 2, requestedPlan: ['add', 'delete'] },
],
};
const replay = extractReplayContext(artifact);
assert.equal(replay.argsOverride.seed, 'abc');
assert.deepEqual(replay.fixedPlansByInstance.get(1), ['add', 'move']);
assert.deepEqual(replay.fixedPlansByInstance.get(2), ['add', 'delete']);
});
test('buildSimulationOperationPlan full profile includes save, refs, templates, and multi-property ops', () => {
const plan = buildSimulationOperationPlan(20, 'full');
assert.deepEqual(plan, [
'add',
'save',
'inlineTag',
'emptyInlineTag',
'pageReference',
'blockReference',
'propertySet',
'batchSetProperty',
'propertyValueDelete',
'copyPaste',
'copyPasteTreeToEmptyTarget',
'templateApply',
'move',
'moveUpDown',
'indent',
'outdent',
'delete',
'propertyRemove',
'undo',
'redo',
]);
});
test('buildSimulationOperationPlan fast profile cycles through refs, templates, and property variants', () => {
const plan = buildSimulationOperationPlan(17, 'fast');
assert.deepEqual(plan, [
'add',
'save',
'inlineTag',
'emptyInlineTag',
'pageReference',
'blockReference',
'propertySet',
'batchSetProperty',
'move',
'delete',
'indent',
'outdent',
'moveUpDown',
'templateApply',
'propertyValueDelete',
'add',
'move',
]);
});
test('ALL_OUTLINER_OP_COVERAGE_OPS tracks canonical outliner-op definitions', () => {
const opSchemaSource = fs.readFileSync(OUTLINER_OP_SCHEMA_PATH, 'utf8');
const opConstructSource = fs.readFileSync(OUTLINER_OP_CONSTRUCT_PATH, 'utf8');
const expectedOps = [
...new Set([
...parseOpSchemaOps(opSchemaSource),
...parseSemanticOps(opConstructSource),
]),
].sort();
const actualOps = [...new Set(ALL_OUTLINER_OP_COVERAGE_OPS)].sort();
assert.equal(actualOps.length, ALL_OUTLINER_OP_COVERAGE_OPS.length);
assert.deepEqual(actualOps, expectedOps);
});
test('mergeOutlinerCoverageIntoRound prepends all outliner coverage ops to requested plan and op log', () => {
const round = {
requestedOps: 2,
executedOps: 2,
counts: { add: 1, move: 1 },
requestedPlan: ['add', 'move'],
opLog: [
{ index: 0, requested: 'add', executedAs: 'add', detail: { kind: 'add' } },
{ index: 1, requested: 'move', executedAs: 'move', detail: { kind: 'move' } },
],
outlinerOpCoverage: {
expectedOps: ['save-block', 'set-block-property'],
failedOps: [],
sample: [
{ op: 'save-block', ok: true, durationMs: 123 },
{ op: 'set-block-property', ok: true, durationMs: 88 },
],
},
};
const merged = mergeOutlinerCoverageIntoRound(round);
assert.equal(merged.requestedOps, 4);
assert.equal(merged.executedOps, 4);
assert.deepEqual(merged.requestedPlan, [
'outliner:save-block',
'outliner:set-block-property',
'add',
'move',
]);
assert.equal(merged.opLog.length, 4);
assert.equal(merged.opLog[0].requested, 'outliner:save-block');
assert.equal(merged.opLog[1].requested, 'outliner:set-block-property');
assert.equal(merged.opLog[2].index, 2);
assert.equal(merged.opLog[3].index, 3);
assert.equal(merged.counts.outlinerCoverage, 2);
assert.equal(merged.counts.outlinerCoverageFailed, 0);
});
test('mergeOutlinerCoverageIntoRound is idempotent once outliner ops are already merged', () => {
const round = {
requestedOps: 2,
executedOps: 2,
counts: {},
requestedPlan: ['outliner:save-block', 'add'],
opLog: [],
outlinerOpCoverage: {
expectedOps: ['save-block'],
failedOps: [],
},
};
const merged = mergeOutlinerCoverageIntoRound(round);
assert.deepEqual(merged, round);
});
@@ -0,0 +1,113 @@
(ns logseq.tasks.db-graph.create-graph-with-clojure-irc-history-test
(:require ["fs" :as fs]
["os" :as node-os]
["path" :as node-path]
[cljs.test :refer [deftest is testing]]
[logseq.tasks.db-graph.create-graph-with-clojure-irc-history :as sut]))
(deftest extract-day-paths-returns-sorted-unique-day-pages
(let [index-html (str "<a href=\"2008/2008-02-03.html\">3</a>"
"<a href=\"2008/2008-02-01.html\">1</a>"
"<a href=\"index.html\">home</a>"
"<a href=\"2008/2008-02-01.html\">1</a>")]
(is (= ["2008/2008-02-01.html" "2008/2008-02-03.html"]
(sut/extract-day-paths index-html)))))
(deftest extract-chat-rows-parses-time-nick-and-message
(let [day-html (str "<tr id=\"t1245A\"><td><a href=\"#t1245A\">12:45</a></td>"
"<td class=\"n2\">otwieracz</td>"
"<td>Hello &quot;there&quot; &amp; <a href=\"https://example.com\">https://example.com</a></td></tr>"
"<tr id=\"t1249A\" class=\"h\"><td><a href=\"#t1249A\">12:49</a></td>"
"<td class=\"n6\">lxsameer</td>"
"<td>otwieracz: selmer</td></tr>")]
(is (= [{:time "12:45"
:nick "otwieracz"
:message "Hello \"there\" & https://example.com"}
{:time "12:49"
:nick "lxsameer"
:message "otwieracz: selmer"}]
(sut/extract-chat-rows day-html)))))
(deftest select-day-paths-downloads-all-by-default
(let [paths ["2008/2008-02-01.html"
"2008/2008-02-02.html"
"2008/2008-02-03.html"
"2008/2008-02-04.html"]]
(is (= paths
(sut/select-day-paths paths {})))
(is (= ["2008/2008-02-01.html" "2008/2008-02-02.html"]
(sut/select-day-paths paths {:limit-days 2})))))
(deftest build-page-and-blocks-uses-journal-page-and-chat-timestamps
(testing "Each chat block stores created-by-ref and timestamp derived from date/time"
(let [chouser-uuid #uuid "11111111-1111-1111-1111-111111111111"
rhickey-uuid #uuid "22222222-2222-2222-2222-222222222222"
page (sut/build-page-and-blocks {:date "2008-02-01"
:day-path "2008/2008-02-01.html"
:base-url "https://chouser.us/clojure-log/"
:user->uuid {"Chouser" chouser-uuid
"rhickey" rhickey-uuid}
:chat-rows [{:time "20:46"
:nick "Chouser"
:message "Hi"}
{:time "20:47"
:nick "rhickey"
:message "hello"}]})]
(is (= 20080201
(get-in page [:page :build/journal])))
(is (= "20:46 Chouser: Hi"
(get-in page [:blocks 0 :block/title])))
(is (= "20:47 rhickey: hello"
(get-in page [:blocks 1 :block/title])))
(is (= [:block/uuid chouser-uuid]
(get-in page [:blocks 0 :build/properties :logseq.property/created-by-ref])))
(is (= [:block/uuid rhickey-uuid]
(get-in page [:blocks 1 :build/properties :logseq.property/created-by-ref])))
(is (= (sut/date-time->timestamp-ms "2008-02-01" "20:46")
(get-in page [:blocks 0 :block/created-at])))
(is (= (sut/date-time->timestamp-ms "2008-02-01" "20:47")
(get-in page [:blocks 1 :block/created-at])))
(is (= (sut/date-time->timestamp-ms "2008-02-01" "20:46")
(get-in page [:blocks 0 :block/updated-at])))
(is (= (sut/date-time->timestamp-ms "2008-02-01" "20:47")
(get-in page [:blocks 1 :block/updated-at]))))))
(deftest build-user-pages-creates-user-page-entities
(let [chouser-uuid #uuid "11111111-1111-1111-1111-111111111111"
rhickey-uuid #uuid "22222222-2222-2222-2222-222222222222"
pages (sut/build-user-pages {"Chouser" chouser-uuid
"rhickey" rhickey-uuid})
pages-by-title (into {} (map (fn [{:keys [page]}] [(:block/title page) page])) pages)]
(is (= #{"Chouser" "rhickey"} (set (keys pages-by-title))))
(is (= chouser-uuid (get-in pages-by-title ["Chouser" :block/uuid])))
(is (= "Chouser" (get-in pages-by-title ["Chouser" :build/properties :logseq.property.user/name])))
(is (= rhickey-uuid (get-in pages-by-title ["rhickey" :block/uuid])))
(is (= "rhickey" (get-in pages-by-title ["rhickey" :build/properties :logseq.property.user/name])))))
(deftest build-page-and-blocks-handles-empty-chat-day
(let [page (sut/build-page-and-blocks {:date "2008-02-01"
:day-path "2008/2008-02-01.html"
:base-url "https://chouser.us/clojure-log/"
:user->uuid {}
:chat-rows []})]
(is (= 20080201
(get-in page [:page :build/journal])))
(is (= []
(:blocks page)))))
(deftest resolve-source-dir-supports-root-and-direct-clojure-log-path
(let [tmp-root (str (fs/mkdtempSync (node-path/join (node-os/tmpdir) "clj-log-test-")))
repo-root (node-path/join tmp-root "chouser.github.io-master")
clojure-log-dir (node-path/join repo-root "clojure-log")
index-html "<html></html>"]
(try
(fs/mkdirSync clojure-log-dir #js {:recursive true})
(fs/writeFileSync (node-path/join clojure-log-dir "index.html") index-html)
(is (= clojure-log-dir
(sut/resolve-source-dir clojure-log-dir)))
(is (= clojure-log-dir
(sut/resolve-source-dir repo-root)))
(is (= clojure-log-dir
(sut/resolve-source-dir tmp-root)))
(finally
(fs/rmSync tmp-root #js {:recursive true :force true})))))
@@ -0,0 +1,69 @@
(ns logseq.tasks.db-graph.create-graph-with-large-sizes-test
(:require [cljs.test :refer [deftest is testing]]
[logseq.tasks.db-graph.create-graph-with-large-sizes :as sut]))
(deftest build-page-and-blocks-batch-builds-the-requested-graph-slice
(let [id-seq (map #(str "id-" %) (range))
next-id (let [ids (atom id-seq)]
(fn []
(let [id (first @ids)]
(swap! ids rest)
id)))
batch (#'sut/build-page-and-blocks-batch 10 2 3 next-id)]
(is (= 2 (count batch)))
(is (= ["Page-10" "Page-11"]
(map (comp :block/title :page) batch)))
(is (= ["id-0" "id-4"]
(map (comp :block/uuid :page) batch)))
(is (= [[(#'sut/build-block-title 10 0) (#'sut/build-block-title 10 1) (#'sut/build-block-title 10 2)]
[(#'sut/build-block-title 11 0) (#'sut/build-block-title 11 1) (#'sut/build-block-title 11 2)]]
(map (fn [{:keys [blocks]}]
(mapv :block/title blocks))
batch)))
(is (= [["id-1" "id-2" "id-3"]
["id-5" "id-6" "id-7"]]
(map (fn [{:keys [blocks]}]
(mapv :block/uuid blocks))
batch)))))
(deftest page-and-block-batches-only-realize-requested-batches
(let [calls (atom 0)
next-id (fn []
(swap! calls inc)
(str "id-" @calls))
batches (#'sut/page-and-block-batches {:pages 50000
:blocks 50
:batch-pages 100}
next-id)
first-batch (first batches)]
(is (= 100 (count first-batch)))
(is (= (* 100 51) @calls)
"Only the first batch should be realized")
(is (= "Page-0" (get-in first-batch [0 :page :block/title])))
(is (= "Page-99" (get-in first-batch [99 :page :block/title])))))
(deftest default-batching-keeps-large-graphs-bounded
(testing "50k pages with 50 blocks are split into many batches instead of one giant tx"
(let [batch-pages (#'sut/default-batch-pages 50)]
(is (< batch-pages 50000))
(is (pos? batch-pages))
(is (= batch-pages
(count (first (#'sut/page-and-block-batches {:pages 50000
:blocks 50}
(constantly "id")))))))))
(deftest page-and-block-batches-handle-empty-input
(is (= []
(into [] (#'sut/page-and-block-batches {:pages 0
:blocks 50}
(constantly "id"))))))
(deftest parse-args-keeps-the-graph-name-separate-from-cli-options
(let [{:keys [graph-dir options]} (sut/parse-args ["large-graph"
"-p" "3"
"-b" "2"
"-t" "1"])]
(is (= "large-graph" graph-dir))
(is (= 3 (:pages options)))
(is (= 2 (:blocks options)))
(is (= 1 (:batch-pages options)))))
@@ -0,0 +1,12 @@
(ns logseq.tasks.dev-mobile-test
(:require [clojure.test :refer [deftest is run-tests]]
[logseq.tasks.dev.mobile :as mobile]))
(deftest dev-server-url-keeps-mobile-assets-relative-to-mobile-path
(is (= "https://192.0.2.1:3002/mobile/"
(mobile/dev-server-url "192.0.2.1"))))
(defn -main
[& _]
(let [{:keys [fail error]} (run-tests 'logseq.tasks.dev-mobile-test)]
(System/exit (+ fail error))))
+197
View File
@@ -0,0 +1,197 @@
(ns logseq.tasks.dev-test
(:require [clojure.string :as string]
[clojure.test :refer [deftest is run-tests]]
[logseq.tasks.dev :as dev]
[logseq.tasks.dev.lint :as dev-lint]))
(deftest lint-and-test-starts-tests-while-lint-is-running
(let [lint-started (promise)
test-started (promise)
release-tasks (promise)
parallel-test-args (atom nil)]
(with-redefs [dev-lint/dev (fn []
(deliver lint-started true)
@test-started
@release-tasks)
dev/parallel-test (fn [& args]
(reset! parallel-test-args args)
(deliver test-started true)
@lint-started
@release-tasks)]
(let [runner (future (dev/lint-and-test))]
(is (deref lint-started 1000 false))
(is (deref test-started 100 false))
(deliver test-started true)
(deliver release-tasks true)
@runner
(is (= ["-e" "long" "-e" "fix-me"] @parallel-test-args))))))
(def test-namespaces
["frontend.alpha-test"
"frontend.beta-test"
"frontend.gamma-test"
"frontend.delta-test"
"frontend.epsilon-test"])
(deftest run-test-namespaces-batches-namespaces-across-workers
(let [started-node-runs (atom [])]
(with-redefs [dev/test-jobs 2
dev/test-batches-per-job 1
dev/run-shell (fn [& args]
(let [cmd-args (mapv str args)]
(if (some #{"--list-namespaces"} cmd-args)
{:out (string/join "\n" test-namespaces)}
(swap! started-node-runs conj cmd-args))))]
(dev/run-test-namespaces)
(is (= 2 (count @started-node-runs)))
(is (= (set test-namespaces)
(->> @started-node-runs
(mapcat identity)
(filter (set test-namespaces))
set))))))
(deftest run-test-namespaces-isolates-stateful-namespaces
(let [namespaces ["frontend.alpha-test"
"frontend.components.block.drop-boundary-test"
"frontend.handler.editor-test"
"frontend.worker.db-core-test"]
started-node-runs (atom [])]
(with-redefs [dev/test-jobs 2
dev/test-batches-per-job 1
dev/run-shell (fn [& args]
(let [cmd-args (mapv str args)]
(if (some #{"--list-namespaces"} cmd-args)
{:out (string/join "\n" namespaces)}
(swap! started-node-runs conj cmd-args))))]
(dev/run-test-namespaces)
(is (= 4 (count @started-node-runs)))
(doseq [isolated-ns ["frontend.components.block.drop-boundary-test"
"frontend.handler.editor-test"
"frontend.worker.db-core-test"]]
(is (= 1 (count (filter #(some #{isolated-ns} %) @started-node-runs))))
(is (= 1 (->> @started-node-runs
(some #(when (some #{isolated-ns} %) %))
(filter (set namespaces))
count)))))))
(deftest run-test-namespaces-runs-performance-tests-after-parallel-tests
(let [namespaces ["frontend.alpha-test"
"frontend.db.query-dsl-test"
"frontend.worker.search-test"]
completed-runs (atom [])
parallel-finished? (atom false)]
(with-redefs [dev/test-jobs 2
dev/test-batches-per-job 1
dev/run-shell (fn [& args]
(let [cmd-args (mapv str args)]
(if (some #{"--list-namespaces"} cmd-args)
{:out (string/join "\n" namespaces)}
(let [selected (filter (set namespaces) cmd-args)]
(when (some #{"frontend.alpha-test"} selected)
(reset! parallel-finished? true))
(when (some dev/serial-test-namespaces selected)
(is @parallel-finished?))
(swap! completed-runs into selected)))))]
(dev/run-test-namespaces)
(is (= namespaces @completed-runs)))))
(deftest run-test-namespaces-handles-an-empty-selection
(let [node-runs (atom 0)]
(with-redefs [dev/test-jobs 2
dev/test-batches-per-job 1
dev/run-shell (fn [& args]
(if (some #{"--list-namespaces"} (map str args))
{:out ""}
(swap! node-runs inc)))]
(dev/run-test-namespaces)
(is (zero? @node-runs)))))
(deftest parallel-test-runs-test-namespaces-concurrently
(let [compile-ran? (atom false)
listed-namespaces? (atom false)
started-node-runs (atom [])
release-node-runs (promise)
wait-for-started-runs (fn [n]
(loop [remaining-attempts 20]
(when (and (< (count @started-node-runs) n)
(pos? remaining-attempts))
(Thread/sleep 50)
(recur (dec remaining-attempts)))))]
(with-redefs [dev/test-jobs 2
dev/test-batches-per-job 1
dev/run-shell (fn [& args]
(let [cmd-text (string/join " " (map str args))]
(cond
(string/includes? cmd-text "pnpm cljs:test")
(reset! compile-ran? true)
(string/includes? cmd-text "--list-namespaces")
(do
(is (string/includes? cmd-text "^(?!logseq.db-sync.).*"))
(reset! listed-namespaces? true)
{:out (string/join "\n" test-namespaces)})
(string/includes? cmd-text "static/tests.js")
(do
(swap! started-node-runs conj args)
@release-node-runs))))]
(let [runner (future (dev/parallel-test "-e" "long" "-e" "fix-me"))]
(wait-for-started-runs dev/test-jobs)
(is @compile-ran?)
(is @listed-namespaces?)
(is (= dev/test-jobs (count @started-node-runs)))
(is (every? #(some #{"-n"} (map str %)) @started-node-runs))
(is (every? #(= ["-e" "long" "-e" "fix-me"]
(take-last 4 (mapv str %)))
@started-node-runs))
(deliver release-node-runs true)
@runner
(is (= dev/test-jobs (count @started-node-runs)))
(is (= (set test-namespaces)
(->> @started-node-runs
(mapcat #(map str %))
(filter (set test-namespaces))
set)))))))
(deftest parallel-test-reraises-namespace-failure-after-running-namespaces
(let [started-node-runs (atom [])
release-node-runs (promise)
wait-for-started-runs (fn [n]
(loop [remaining-attempts 20]
(when (and (< (count @started-node-runs) n)
(pos? remaining-attempts))
(Thread/sleep 50)
(recur (dec remaining-attempts)))))]
(with-redefs [dev/test-jobs 2
dev/test-batches-per-job 1
dev/run-shell (fn [& args]
(let [cmd-text (string/join " " (map str args))]
(cond
(string/includes? cmd-text "--list-namespaces")
(do
(is (string/includes? cmd-text "^(?!logseq.db-sync.).*"))
{:out (string/join "\n" test-namespaces)})
(string/includes? cmd-text "static/tests.js")
(let [run-number (count (swap! started-node-runs conj args))]
@release-node-runs
(when (= 2 run-number)
(throw (ex-info "namespace failed" {})))))))]
(let [runner (future
(try
(dev/parallel-test "-e" "long" "-e" "fix-me")
:passed
(catch Throwable e
e)))]
(wait-for-started-runs dev/test-jobs)
(is (= dev/test-jobs (count @started-node-runs)))
(deliver release-node-runs true)
(let [result @runner]
(is (= dev/test-jobs (count @started-node-runs)))
(is (instance? clojure.lang.ExceptionInfo result))
(is (= "namespace failed" (ex-message result))))))))
(defn -main
[& _]
(let [{:keys [fail error]} (run-tests 'logseq.tasks.dev-test)]
(System/exit (+ fail error))))
+127
View File
@@ -0,0 +1,127 @@
(ns logseq.tasks.lang-test
(:require [cljs.test :refer [deftest is testing]]
[logseq.tasks.lang-lint :as lang-lint]))
(deftest translation-placeholders-detect-placeholder-sets
(is (= #{"1" "2"}
(lang-lint/translation-placeholders "Open {1} from {2}")))
(is (= #{}
(lang-lint/translation-placeholders "Search with Google"))))
(deftest placeholder-mismatch-findings-detect-non-default-locale-errors
(testing "a localized value must match English placeholders exactly once it is defined"
(let [findings (lang-lint/placeholder-mismatch-findings
{:en {:electron/link-open-confirm "Are you sure?\n\n{1}"
:electron/write-file-failed-with-backup "Write failed {1} {2} {3}."}
:zh-Hant {:electron/link-open-confirm "確定要開啟此外部連結嗎?"
:electron/write-file-failed-with-backup "寫入失敗。備份檔案:{1}"}
:zh-CN {:electron/link-open-confirm "确定要打开此链接吗?\n\n{1}"
:electron/write-file-failed-with-backup "写入文件 {1} 失败,{2}。备份文件已保存到 {3}。"}})]
(is (= [{:lang :zh-Hant
:translation-key :electron/link-open-confirm
:expected-placeholders ["1"]
:actual-placeholders []
:default-value "Are you sure?\n\n{1}"
:localized-value "確定要開啟此外部連結嗎?"}
{:lang :zh-Hant
:translation-key :electron/write-file-failed-with-backup
:expected-placeholders ["1" "2" "3"]
:actual-placeholders ["1"]
:default-value "Write failed {1} {2} {3}."
:localized-value "寫入失敗。備份檔案:{1}"}]
findings)))))
(deftest translation-rich-validation-findings-report-rich-contract-mismatches
(testing "a localized rich translation must remain a zero-arg function once defined"
(is (= [{:lang :zh-Hant
:translation-key :e2ee/cloud-password-rich
:expected-value-kind :fn
:actual-value-kind :string}
{:lang :zh-Hant
:translation-key :on-boarding/main-title
:expected-value-kind :fn
:actual-value-kind :string}]
(lang-lint/rich-translation-mismatch-findings
{:en {:on-boarding/main-title (fn [] ["Welcome to " [:strong "Logseq!"]])
:e2ee/cloud-password-rich (fn [] ["Cloud sentence " [:span "Local sentence"]])
:e2ee/remember-password-rich (fn [] [[:span "Remember "] "your password."])}
:zh-Hant {:on-boarding/main-title "歡迎使用 Logseq"
:e2ee/cloud-password-rich "雲端密碼"
:e2ee/remember-password-rich (fn [] [[:span "請記住"] "你的密碼。"])}})))))
(deftest identical-translation-findings-report-defined-values-equal-to-english
(is (= [{:lang :ko
:translation-key :ui/cancel
:default-value "Cancel"}
{:lang :ko
:translation-key :ui/save
:default-value "Save"}]
(lang-lint/identical-translation-findings
{:en {:ui/cancel "Cancel"
:ui/save "Save"
:ui/close "Close"}
:ko {:ui/cancel "Cancel"
:ui/save "Save"
:ui/close "닫기"}
:fr {:ui/cancel "Annuler"}}
:ko))))
(deftest identical-translation-stats-count-defined-values-equal-to-english
(is (= [{:lang :en
:translation-count 2
:same-as-en-count 2}
{:lang :ko
:translation-count 2
:same-as-en-count 1}
{:lang :fr
:translation-count 1
:same-as-en-count 0}]
(lang-lint/identical-translation-stats
{:en {:ui/cancel "Cancel"
:ui/save "Save"}
:ko {:ui/cancel "Cancel"
:ui/save "저장"}
:fr {:ui/cancel "Annuler"}}))))
(deftest translation-summary-stats-report-untranslated-and-same-as-en-count
(is (= [{:lang :en
:translation-count 4
:untranslated-count nil
:same-as-en-count nil}
{:lang :fr
:translation-count 2
:untranslated-count 2
:same-as-en-count 1}
{:lang :ko
:translation-count 3
:untranslated-count 1
:same-as-en-count 2}]
(->> (lang-lint/translation-summary-stats
{:en {:ui/cancel "Cancel"
:ui/save "Save"
:ui/close "Close"
:ui/delete "Delete"}
:ko {:ui/cancel "Cancel"
:ui/save "저장"
:ui/close "Close"}
:fr {:ui/cancel "Annuler"
:ui/save "Save"}})
(sort-by :lang)
vec))))
(deftest sort-translation-summary-stats-keeps-en-first-then-sorts-by-untranslated-and-same-as-en-count
(is (= [:en :ko :fr :zh-Hant]
(->> [{:lang :fr
:untranslated-count 3
:same-as-en-count 1}
{:lang :en
:untranslated-count nil
:same-as-en-count nil}
{:lang :zh-Hant
:untranslated-count 1
:same-as-en-count 3}
{:lang :ko
:untranslated-count 3
:same-as-en-count 2}]
lang-lint/sort-translation-summary-stats
(mapv :lang)))))
@@ -0,0 +1,15 @@
(ns logseq.tasks.test-runner
(:require [cljs.test :as test]
[logseq.tasks.db-graph.create-graph-with-clojure-irc-history-test]
[logseq.tasks.db-graph.create-graph-with-large-sizes-test]
[logseq.tasks.lang-test]
[logseq.tasks.util-test]))
(defn -main [& _]
(let [{:keys [fail error]}
(test/run-tests 'logseq.tasks.db-graph.create-graph-with-large-sizes-test
'logseq.tasks.db-graph.create-graph-with-clojure-irc-history-test
'logseq.tasks.lang-test
'logseq.tasks.util-test)]
(when (pos? (+ fail error))
(js/process.exit 1))))
+19
View File
@@ -0,0 +1,19 @@
(ns logseq.tasks.util-test
(:require [cljs.test :refer [deftest is]]
[logseq.tasks.util :as util]))
(deftest display-width-handles-wide-and-combining-characters
(is (= 5 (util/display-width "hello")))
(is (= 4 (util/display-width "中文")))
(is (= 4 (util/display-width "한국")))
(is (= 1 (util/display-width "e\u0301"))))
(deftest render-table-right-aligns-columns-using-display-width
(is (= (str "| :locale | :language |\n"
"|---------+-----------|\n"
"| :en | English |\n"
"| :ja | 日本語 |\n"
"| :ko | 한국 |\n")
(util/render-table [{:locale :en :language "English"}
{:locale :ja :language "日本語"}
{:locale :ko :language "한국"}]))))