@engenty/wizards-runtime 0.14.2 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/runtime/dist/agents/studio-assistant.js +180 -4
- package/apps/runtime/dist/agents/website.js +10 -5
- package/apps/runtime/dist/app.js +27 -2
- package/apps/runtime/dist/auth/index.js +5 -0
- package/apps/runtime/dist/broker/account.js +5 -0
- package/apps/runtime/dist/broker/call.js +2 -0
- package/apps/runtime/dist/broker/host.js +1 -0
- package/apps/runtime/dist/broker/index.js +5 -0
- package/apps/runtime/dist/broker/rwx.js +293 -11
- package/apps/runtime/dist/cli/main.js +7 -0
- package/apps/runtime/dist/cli/move-files.js +68 -0
- package/apps/runtime/dist/cli/move-folder-sources.js +120 -0
- package/apps/runtime/dist/connectors/plugin-connections.js +74 -4
- package/apps/runtime/dist/db/migrations/tenant/0040_rwx_elements.sql +21 -0
- package/apps/runtime/dist/db/migrations/tenant/0041_broker_log_client.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/0042_client_spaces.sql +16 -0
- package/apps/runtime/dist/db/migrations/tenant/0043_space_member_invite.sql +19 -0
- package/apps/runtime/dist/db/migrations/tenant/0044_client_portal.sql +8 -0
- package/apps/runtime/dist/db/migrations/tenant/0045_client_portal_no_slug.sql +2 -0
- package/apps/runtime/dist/db/migrations/tenant/0046_space_file_hash.sql +2 -0
- package/apps/runtime/dist/db/migrations/tenant/0047_knowledge_folders.sql +3 -0
- package/apps/runtime/dist/db/migrations/tenant/0048_space_chunk_kind.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/0049_knowledge_sources.sql +57 -0
- package/apps/runtime/dist/db/migrations/tenant/0050_dateien.sql +71 -0
- package/apps/runtime/dist/db/migrations/tenant/0051_dateien_drafts.sql +23 -0
- package/apps/runtime/dist/db/migrations/tenant/0052_dateien_plugin_kinds.sql +5 -0
- package/apps/runtime/dist/db/migrations/tenant/0053_dateien_file_title.sql +3 -0
- package/apps/runtime/dist/db/migrations/tenant/0054_dateien_ocr.sql +14 -0
- package/apps/runtime/dist/db/migrations/tenant/0055_dateien_doc_reread.sql +3 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0040_snapshot.json +5153 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0041_snapshot.json +5160 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0042_snapshot.json +5286 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0043_snapshot.json +5293 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0044_snapshot.json +5344 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0045_snapshot.json +5329 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0046_snapshot.json +5343 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0047_snapshot.json +5391 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0048_snapshot.json +5398 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0049_snapshot.json +5793 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0050_snapshot.json +6288 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0051_snapshot.json +6461 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0052_snapshot.json +6497 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0053_snapshot.json +6504 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0054_snapshot.json +6504 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0055_snapshot.json +6504 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +112 -0
- package/apps/runtime/dist/db/schema.js +296 -5
- package/apps/runtime/dist/docs/dev/api.md +49 -2
- package/apps/runtime/dist/docs/dev/architecture.md +13 -2
- package/apps/runtime/dist/docs/dev/plugins/connections.md +30 -2
- package/apps/runtime/dist/docs/dev/plugins/index.md +1 -1
- package/apps/runtime/dist/docs/dev/plugins/reference.md +7 -4
- package/apps/runtime/dist/docs/dev/plugins/server.md +11 -5
- package/apps/runtime/dist/docs/dev/plugins/space.md +130 -4
- package/apps/runtime/dist/docs/dev/plugins/studio.md +13 -3
- package/apps/runtime/dist/docs/user-guide/command-line.md +2 -0
- package/apps/runtime/dist/docs/user-guide/plugins.md +1 -1
- package/apps/runtime/dist/docs/user-guide/space.md +6 -6
- package/apps/runtime/dist/docs/user-guide/steps.md +1 -1
- package/apps/runtime/dist/documents/ocr.js +72 -0
- package/apps/runtime/dist/documents/parse.js +81 -12
- package/apps/runtime/dist/elements/caller.js +47 -0
- package/apps/runtime/dist/elements/catalogue.js +14 -0
- package/apps/runtime/dist/elements/connections.js +60 -0
- package/apps/runtime/dist/elements/gate.js +81 -0
- package/apps/runtime/dist/elements/knowledge.js +308 -0
- package/apps/runtime/dist/elements/outside.js +103 -0
- package/apps/runtime/dist/elements/specs.js +102 -0
- package/apps/runtime/dist/elements/wizards.js +72 -0
- package/apps/runtime/dist/engenty/connections-google/connectors/drive.js +3 -0
- package/apps/runtime/dist/engenty/connections-microsoft/onedrive.js +3 -0
- package/apps/runtime/dist/engenty/connections-s3/s3.js +6 -0
- package/apps/runtime/dist/engine/runner.js +19 -2
- package/apps/runtime/dist/engine/steps.js +1 -1
- package/apps/runtime/dist/env.js +11 -2
- package/apps/runtime/dist/files/blobs.js +57 -1
- package/apps/runtime/dist/files/objects.js +1 -0
- package/apps/runtime/dist/files/pictures.js +41 -0
- package/apps/runtime/dist/files/storage.js +14 -26
- package/apps/runtime/dist/files/thumbs.js +77 -0
- package/apps/runtime/dist/files/upload-check.js +2 -2
- package/apps/runtime/dist/index.js +22 -0
- package/apps/runtime/dist/live/views.js +2 -1
- package/apps/runtime/dist/manage.js +4 -1
- package/apps/runtime/dist/mcp/elements.js +88 -0
- package/apps/runtime/dist/mcp/handler.js +2 -0
- package/apps/runtime/dist/mcp/scopes.js +5 -0
- package/apps/runtime/dist/mcp/tools.js +5 -0
- package/apps/runtime/dist/models.js +82 -13
- package/apps/runtime/dist/mounts/cache.js +71 -0
- package/apps/runtime/dist/mounts/drafts.js +367 -0
- package/apps/runtime/dist/mounts/folder.js +148 -0
- package/apps/runtime/dist/mounts/mounts.js +1315 -0
- package/apps/runtime/dist/mounts/source.js +179 -0
- package/apps/runtime/dist/mounts/units.js +97 -0
- package/apps/runtime/dist/move-files.js +4 -0
- package/apps/runtime/dist/plugins/loader.js +73 -1
- package/apps/runtime/dist/plugins/registry.js +2 -0
- package/apps/runtime/dist/prompts/authoring.md +2 -2
- package/apps/runtime/dist/prompts/goose.md +13 -1
- package/apps/runtime/dist/prompts/tools.md +8 -2
- package/apps/runtime/dist/render/convert.js +188 -1
- package/apps/runtime/dist/routes/api.js +7 -2
- package/apps/runtime/dist/routes/client-contract.js +164 -0
- package/apps/runtime/dist/routes/client-spaces.js +58 -0
- package/apps/runtime/dist/routes/dateien.js +173 -0
- package/apps/runtime/dist/routes/elements.js +76 -0
- package/apps/runtime/dist/routes/plugins.js +2 -1
- package/apps/runtime/dist/routes/runs.js +24 -10
- package/apps/runtime/dist/routes/studio.js +168 -8
- package/apps/runtime/dist/secrets/signing.js +16 -0
- package/apps/runtime/dist/services/client-portal.js +439 -0
- package/apps/runtime/dist/services/client-spaces.js +228 -0
- package/apps/runtime/dist/services/cloud.js +2 -0
- package/apps/runtime/dist/services/knowledge-model.js +24 -8
- package/apps/runtime/dist/services/knowledge.js +72 -42
- package/apps/runtime/dist/services/links.js +17 -0
- package/apps/runtime/dist/services/members-studio.js +5 -1
- package/apps/runtime/dist/services/page-pictures.js +162 -0
- package/apps/runtime/dist/services/runs.js +22 -6
- package/apps/runtime/dist/services/space-categories.js +41 -5
- package/apps/runtime/dist/services/space-data.js +165 -8
- package/apps/runtime/dist/services/space-files.js +102 -19
- package/apps/runtime/dist/services/space-index.js +384 -41
- package/apps/runtime/dist/services/space-origin.js +25 -1
- package/apps/runtime/dist/services/space-sources.js +937 -0
- package/apps/runtime/dist/services/spaces.js +60 -12
- package/apps/runtime/dist/services/synced-spaces.js +10 -1
- package/apps/runtime/dist/services/work-ai.js +53 -24
- package/apps/runtime/dist/services/work-chats.js +3 -2
- package/apps/runtime/dist/services/work-connections.js +2 -2
- package/apps/runtime/dist/sharing/index.js +2 -0
- package/apps/runtime/dist/store/index.js +29 -8
- package/apps/runtime/dist/store/shared-lists.js +30 -17
- package/apps/runtime/dist/sync/records.js +22 -27
- package/apps/runtime/dist/texts.js +4 -0
- package/apps/runtime/dist/tools/index.js +5 -4
- package/apps/runtime/dist/tools/pages.js +1 -1
- package/apps/runtime/dist/tools/skills.js +80 -54
- package/apps/runtime/dist/tools/space.js +8 -152
- package/apps/runtime/dist/widgets/step.js +2 -1
- package/apps/web/dist/assets/AboutDialog-0q4P80yv.js +1 -0
- package/apps/web/dist/assets/BlockEditor-CUYFH_CU.js +173 -0
- package/apps/web/dist/assets/BlockEditor-CtW6lw0y.css +1 -0
- package/apps/web/dist/assets/CapabilitiesPage-BlZP8DYb.js +2 -0
- package/apps/web/dist/assets/{ChangelogDialog-D_dQOMIq.js → ChangelogDialog-CDN7kMs1.js} +1 -1
- package/apps/web/dist/assets/{CodeEditor-nxoOt8ge.js → CodeEditor-D-Y16fdk.js} +1 -1
- package/apps/web/dist/assets/EditorPage-CrMVsgUt.js +3 -0
- package/apps/web/dist/assets/{FlowPreview-aMfwcPul.js → FlowPreview-DXnk7m9P.js} +1 -1
- package/apps/web/dist/assets/{LangSwitch-DpD0inR4.js → LangSwitch-Dkd0FBIH.js} +1 -1
- package/apps/web/dist/assets/Marketplace-Cty40VwG.js +2 -0
- package/apps/web/dist/assets/NewWizardChannels-Czool7s1.js +1 -0
- package/apps/web/dist/assets/NewWizardPage-CfVe_4a2.js +7 -0
- package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +1 -0
- package/apps/web/dist/assets/PreviewPane-CQDKQO6z.js +7 -0
- package/apps/web/dist/assets/PublicRunner-BDZNnlQw.js +1 -0
- package/apps/web/dist/assets/ReadOnly-B7MUySpC.js +1 -0
- package/apps/web/dist/assets/SettingsPage-Bgurv3l2.js +2 -0
- package/apps/web/dist/assets/SetupPage-C3km8vqv.js +1 -0
- package/apps/web/dist/assets/{SharePage-N80EhoD7.js → SharePage-UwEJBIzq.js} +1 -1
- package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +1 -0
- package/apps/web/dist/assets/Skills-Bv6XbKxc.js +9 -0
- package/apps/web/dist/assets/SpacePage-D9PXLSU_.js +2 -0
- package/apps/web/dist/assets/UpdateCheck-C7I43zFZ.js +2 -0
- package/apps/web/dist/assets/changelog-DwgWiSZb.js +1 -0
- package/apps/web/dist/assets/circle-check-DDLzlcXP.js +1 -0
- package/apps/web/dist/assets/code-DsnwzN1x.js +1 -0
- package/apps/web/dist/assets/code-editor-Ca5EAxmd.js +2 -0
- package/apps/web/dist/assets/code-xml-S4IFi5Jc.js +1 -0
- package/apps/web/dist/assets/connection-sign-in-hI3HXhq4.js +1 -0
- package/apps/web/dist/assets/{dist-H1UN89OA.js → dist-B3Ray2U5.js} +1 -1
- package/apps/web/dist/assets/dist-CQpLJoQZ.js +10 -0
- package/apps/web/dist/assets/{dist-GlRRx9Xl.js → dist-D1uGQ_tB.js} +1 -1
- package/apps/web/dist/assets/{dist-BdDd1FxP.js → dist-DFI-tsfx.js} +1 -1
- package/apps/web/dist/assets/eye-TJSuiHHO.js +1 -0
- package/apps/web/dist/assets/floating-ui.dom-pwdNGv4b.js +1 -0
- package/apps/web/dist/assets/host-D5hNHbhF.js +125 -0
- package/apps/web/dist/assets/i18n-BBzMbGoo.js +55 -0
- package/apps/web/dist/assets/index-CyBrvupM.js +10 -0
- package/apps/web/dist/assets/index-w-3J3ZJ9.css +1 -0
- package/apps/web/dist/assets/{json-CEsfHdlZ.js → json-Ce3iHrtf.js} +1 -1
- package/apps/web/dist/assets/link-CPL8pB1P.js +1 -0
- package/apps/web/dist/assets/list-checks-DaxmUPqK.js +1 -0
- package/apps/web/dist/assets/{markdown-5-I9_izp.js → markdown-hqKQy2pp.js} +1 -1
- package/apps/web/dist/assets/marked.esm-DQ7XA7AC.js +67 -0
- package/apps/web/dist/assets/oss-credits-BrwV0a4F.js +1 -0
- package/apps/web/dist/assets/pdf-Dg-raaUo.js +54 -0
- package/apps/web/dist/assets/pdf.worker.min-68CMzziE.js +1 -0
- package/apps/web/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
- package/apps/web/dist/assets/phone-B4uKDBFq.js +1 -0
- package/apps/web/dist/assets/read-aloud-Bfp9_bUY.js +1 -0
- package/apps/web/dist/assets/{runners-CyIvJIHr.js → runners-CUpBpSji.js} +1 -1
- package/apps/web/dist/assets/scroll-text-BEnPzQEi.js +1 -0
- package/apps/web/dist/assets/session-CMQo8P-G.js +2 -0
- package/apps/web/dist/assets/table-5B9G3oA6.js +1 -0
- package/apps/web/dist/assets/theme-CdX0marK.js +11 -0
- package/apps/web/dist/assets/ui-BCfu5sia.js +16 -0
- package/apps/web/dist/assets/upload-CAlHC232.js +1 -0
- package/apps/web/dist/assets/{useMutation-DEkZhp5c.js → useMutation-1fV4Nnxq.js} +1 -1
- package/apps/web/dist/assets/viewers-ChriFcRy.js +2 -0
- package/apps/web/dist/assets/volume-2-BqlBtCIJ.js +1 -0
- package/apps/web/dist/assets/w3c-keyname-BOAvb0qz.js +1 -0
- package/apps/web/dist/assets/xlsx-CuSbHU4R.js +141 -0
- package/apps/web/dist/index.html +19 -14
- package/apps/web/dist/mcp/flow.html +2 -2
- package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +223 -4
- package/node_modules/@engenty/wizards/dist/plugin/mount.d.ts +123 -0
- package/node_modules/@engenty/wizards/dist/plugin/mount.js +7 -0
- package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +110 -1
- package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +1 -1
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +24 -0
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +24 -0
- package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +33 -4
- package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
- package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
- package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +21 -4
- package/node_modules/@engenty/wizards-shared/dist/rwx.js +30 -3
- package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +11 -1
- package/node_modules/@engenty/wizards-shared/dist/spaces.js +9 -2
- package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +6 -0
- package/node_modules/@engenty/wizards-shared/dist/text-merge.js +25 -0
- package/package.json +3 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/README.md +3 -0
- package/plugin/plugin.json +1 -1
- package/plugin/skills/work-in-space/SKILL.md +16 -0
- package/apps/web/dist/assets/AboutDialog-Cag3RJuT.js +0 -1
- package/apps/web/dist/assets/CapabilitiesPage-BQYiN0gT.js +0 -2
- package/apps/web/dist/assets/EditorPage-C4_8LsQN.js +0 -3
- package/apps/web/dist/assets/Marketplace-CpzD9pNQ.js +0 -2
- package/apps/web/dist/assets/NewWizardChannels-CcE3UMVb.js +0 -1
- package/apps/web/dist/assets/NewWizardPage-BzN7zrQx.js +0 -7
- package/apps/web/dist/assets/OnboardingPage-ztHT01ah.js +0 -1
- package/apps/web/dist/assets/PreviewPane-BabMbBZI.js +0 -9
- package/apps/web/dist/assets/PublicRunner-D-JmtqCi.js +0 -1
- package/apps/web/dist/assets/ReadOnly-GAORKKqV.js +0 -1
- package/apps/web/dist/assets/SettingsPage-BKAiYmXl.js +0 -2
- package/apps/web/dist/assets/SetupPage-C1EZZHIp.js +0 -1
- package/apps/web/dist/assets/SkillEditor-CqQMg2MC.js +0 -1
- package/apps/web/dist/assets/Skills-CnhpgoOA.js +0 -9
- package/apps/web/dist/assets/SpacePage-CRR8JvV1.js +0 -2
- package/apps/web/dist/assets/UpdateCheck-CfXZBQNv.js +0 -2
- package/apps/web/dist/assets/changelog-6MqC8Vy8.js +0 -1
- package/apps/web/dist/assets/circle-alert-C8Ma-bPY.js +0 -1
- package/apps/web/dist/assets/circle-check-Bu9Z3mlJ.js +0 -1
- package/apps/web/dist/assets/code-editor-CfTGqOpp.js +0 -2
- package/apps/web/dist/assets/code-xml-B4kLFZSj.js +0 -1
- package/apps/web/dist/assets/connection-sign-in-B2D0O8W-.js +0 -1
- package/apps/web/dist/assets/dist-EBVTpvRr.js +0 -10
- package/apps/web/dist/assets/eye-BpoKpIdt.js +0 -1
- package/apps/web/dist/assets/host-BlKXX7YK.js +0 -118
- package/apps/web/dist/assets/i18n-BJ7Ld6O6.js +0 -55
- package/apps/web/dist/assets/index-66tE1oti.js +0 -10
- package/apps/web/dist/assets/index-D18DvnxX.css +0 -1
- package/apps/web/dist/assets/oss-credits-IdX5bc71.js +0 -1
- package/apps/web/dist/assets/phone-Ctvf-Am-.js +0 -1
- package/apps/web/dist/assets/read-aloud-Da_RSm2S.js +0 -1
- package/apps/web/dist/assets/scroll-text-ChrjRu9Y.js +0 -1
- package/apps/web/dist/assets/session-SXPtTWRK.js +0 -2
- package/apps/web/dist/assets/theme-Br1S0j5h.js +0 -11
- package/apps/web/dist/assets/ui-Uqnx1UpK.js +0 -82
- package/apps/web/dist/assets/upload-BchUnQGV.js +0 -1
- package/apps/web/dist/assets/volume-2-CU_oy81Z.js +0 -1
|
@@ -0,0 +1,1315 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readdir, stat } from "node:fs/promises";
|
|
4
|
+
import { homedir, platform } from "node:os";
|
|
5
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
6
|
+
import { featureOn } from "@engenty/wizards-shared/features";
|
|
7
|
+
import { AUDIENCES, } from "@engenty/wizards-shared/rwx";
|
|
8
|
+
import { embedMany } from "ai";
|
|
9
|
+
import { and, asc, eq, inArray, isNotNull, isNull, ne, notInArray, or, sql } from "drizzle-orm";
|
|
10
|
+
import { nanoid } from "nanoid";
|
|
11
|
+
import { readableMounts, seedRwx } from "../broker/rwx.js";
|
|
12
|
+
import { db, knownTenants, schema, withTenant } from "../db/client.js";
|
|
13
|
+
import { documentMime, ownText } from "../documents/parse.js";
|
|
14
|
+
import { currentFeatures } from "../features.js";
|
|
15
|
+
import { objects } from "../files/objects.js";
|
|
16
|
+
import { jpegOf, MAX_PAGE_PICTURES, pdfPages } from "../files/pictures.js";
|
|
17
|
+
import { hasThumb, makeThumb } from "../files/thumbs.js";
|
|
18
|
+
import { managed } from "../manage.js";
|
|
19
|
+
import { embeddingModel } from "../models.js";
|
|
20
|
+
import { onPluginChange, pluginsOf } from "../plugins/registry.js";
|
|
21
|
+
import { currentRole, isAdminRole, MEMBERS_EDIT_ONLY } from "../services/access.js";
|
|
22
|
+
import { notFound, ServiceError } from "../services/errors.js";
|
|
23
|
+
import { itemCategoriesOf, putCategory, setItemCategories } from "../services/space-categories.js";
|
|
24
|
+
import { currentTenant } from "../tenants/tenant.js";
|
|
25
|
+
import { cachedText, keptText } from "./cache.js";
|
|
26
|
+
import { FolderReader, leftOut } from "./folder.js";
|
|
27
|
+
import { pathWords, textUnits, unitText } from "./units.js";
|
|
28
|
+
/** Larger files are listed and found by their name, not read. */
|
|
29
|
+
const MAX_READ_BYTES = 100 * 1024 * 1024;
|
|
30
|
+
/** Larger documents are not read for their text. */
|
|
31
|
+
const MAX_TEXT_BYTES = 50 * 1024 * 1024;
|
|
32
|
+
/** What has text of its own to read: documents, tables, mails, plain text. */
|
|
33
|
+
const TEXT = /^(application\/pdf|application\/msword|application\/json|message\/rfc822|text\/|application\/vnd\.openxmlformats-officedocument\.(wordprocessingml|spreadsheetml))/;
|
|
34
|
+
/** The pictures the embedding model is shown: what @napi-rs/canvas reads. */
|
|
35
|
+
const PICTURE = /^image\/(png|jpeg|webp|gif)$/;
|
|
36
|
+
/** A mount's tree is listed again this often, for what a watcher missed. */
|
|
37
|
+
const RESCAN_MS = 3600_000;
|
|
38
|
+
/** A plugin's mount is listed whole again this often; between, its `changes` say. */
|
|
39
|
+
const RELIST_MS = 7 * 24 * 3600_000;
|
|
40
|
+
/** Changes a watcher tells of wait this long, so a copy of many files is one round. */
|
|
41
|
+
const SETTLE_MS = 2000;
|
|
42
|
+
export async function dateienOn() {
|
|
43
|
+
return featureOn(await currentFeatures(), "dateien");
|
|
44
|
+
}
|
|
45
|
+
/** Mounts exist only behind the switch. */
|
|
46
|
+
async function requireDateien() {
|
|
47
|
+
if (!(await dateienOn())) {
|
|
48
|
+
throw notFound();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** A folder of this computer is mounted only on a local install. */
|
|
52
|
+
async function requireFolders() {
|
|
53
|
+
if (managed) {
|
|
54
|
+
throw notFound();
|
|
55
|
+
}
|
|
56
|
+
await requireDateien();
|
|
57
|
+
}
|
|
58
|
+
function requireAdmin() {
|
|
59
|
+
if (!isAdminRole(currentRole())) {
|
|
60
|
+
throw new ServiceError("forbidden", MEMBERS_EDIT_ONLY);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** The open mounts of this process, by id: their reader, its cursor, its watcher. */
|
|
64
|
+
const opened = new Map();
|
|
65
|
+
const isFolder = (mount) => mount.kind === "folder";
|
|
66
|
+
const folderPath = (mount) => mount.source.path;
|
|
67
|
+
/** A mount as a plugin's kind is handed it. */
|
|
68
|
+
const pluginMount = (mount) => ({
|
|
69
|
+
id: mount.id,
|
|
70
|
+
space: mount.spaceId,
|
|
71
|
+
name: mount.name,
|
|
72
|
+
source: mount.source,
|
|
73
|
+
});
|
|
74
|
+
/** The kind of a plugin's mount, where the tenant has its plugin now; null where not. */
|
|
75
|
+
async function kindOf(mount) {
|
|
76
|
+
const plugin = (await pluginsOf(currentTenant())).find((p) => p.source.id === mount.plugin);
|
|
77
|
+
return plugin?.mountKinds.get(mount.kind) ?? null;
|
|
78
|
+
}
|
|
79
|
+
/** The mount kinds of the tenant's plugins, with the plugin that brings each. */
|
|
80
|
+
export async function mountKinds() {
|
|
81
|
+
return (await pluginsOf(currentTenant())).flatMap((p) => [...p.mountKinds.values()].map((kind) => ({ plugin: p.source.id, kind })));
|
|
82
|
+
}
|
|
83
|
+
async function openOf(mount) {
|
|
84
|
+
let open = opened.get(mount.id);
|
|
85
|
+
if (!open) {
|
|
86
|
+
let reader;
|
|
87
|
+
if (isFolder(mount)) {
|
|
88
|
+
reader = new FolderReader(folderPath(mount));
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
const kind = await kindOf(mount);
|
|
92
|
+
if (!kind) {
|
|
93
|
+
throw new ServiceError("not_found", `The plugin that reads "${mount.name}" is not there.`);
|
|
94
|
+
}
|
|
95
|
+
reader = kind.open(pluginMount(mount));
|
|
96
|
+
}
|
|
97
|
+
open = opened.get(mount.id) ?? { reader, plugin: mount.plugin, cursor: mount.cursor };
|
|
98
|
+
opened.set(mount.id, open);
|
|
99
|
+
}
|
|
100
|
+
return open;
|
|
101
|
+
}
|
|
102
|
+
export async function readerOf(mount) {
|
|
103
|
+
return (await openOf(mount)).reader;
|
|
104
|
+
}
|
|
105
|
+
// A plugin loaded again or went: its readers are opened again with its new code.
|
|
106
|
+
onPluginChange(({ id }) => {
|
|
107
|
+
for (const [mountId, open] of opened) {
|
|
108
|
+
if (open.plugin && (id === null || open.plugin === id)) {
|
|
109
|
+
closeMount(mountId);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
const changeListeners = [];
|
|
114
|
+
/** Tells `listener` of every change a listing of a mount found, in the mount's tenant. */
|
|
115
|
+
export function onMountChanged(listener) {
|
|
116
|
+
changeListeners.push(listener);
|
|
117
|
+
}
|
|
118
|
+
/** Starts listening to a mount's source: a change asks for its changes a moment later. */
|
|
119
|
+
async function watchMount(mount) {
|
|
120
|
+
const open = await openOf(mount);
|
|
121
|
+
if (open.stop || !open.reader.watch) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const tenant = currentTenant();
|
|
125
|
+
open.stop = open.reader.watch(() => {
|
|
126
|
+
clearTimeout(open.timer);
|
|
127
|
+
open.timer = setTimeout(() => queue(tenant, mount.id, "changes"), SETTLE_MS);
|
|
128
|
+
open.timer.unref?.();
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function closeMount(id) {
|
|
132
|
+
const open = opened.get(id);
|
|
133
|
+
clearTimeout(open?.timer);
|
|
134
|
+
open?.stop?.();
|
|
135
|
+
open?.reader.close?.();
|
|
136
|
+
opened.delete(id);
|
|
137
|
+
}
|
|
138
|
+
const thumbKey = (mountId, fileId) => `derived/m/${mountId}/${fileId}.jpg`;
|
|
139
|
+
/** The source's id of a file, for its reader: where the row knows it. */
|
|
140
|
+
const idOf = (file) => (file.sourceId ? { id: file.sourceId } : {});
|
|
141
|
+
const jobs = new Map();
|
|
142
|
+
const active = new Set();
|
|
143
|
+
let working = null;
|
|
144
|
+
/** Files that failed to embed in this process: not tried again until it restarts. */
|
|
145
|
+
const failed = new Set();
|
|
146
|
+
/** Calls to the embedding model that failed one after the other: at 3 the vectors wait. */
|
|
147
|
+
let inRow = 0;
|
|
148
|
+
const MAX_IN_ROW = 3;
|
|
149
|
+
function queue(tenant, mountId, kind) {
|
|
150
|
+
const key = `${tenant}|${mountId}`;
|
|
151
|
+
// A scan says everything a list of changes would.
|
|
152
|
+
if (jobs.get(key)?.kind !== "scan") {
|
|
153
|
+
jobs.set(key, { tenant, mountId, kind });
|
|
154
|
+
}
|
|
155
|
+
kick(tenant);
|
|
156
|
+
}
|
|
157
|
+
function kick(tenant) {
|
|
158
|
+
active.add(tenant);
|
|
159
|
+
inRow = 0;
|
|
160
|
+
working ??= work()
|
|
161
|
+
.catch((err) => console.error("[dateien]", err))
|
|
162
|
+
.finally(() => {
|
|
163
|
+
working = null;
|
|
164
|
+
if (jobs.size) {
|
|
165
|
+
kick([...jobs.values()][0].tenant);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
async function work() {
|
|
170
|
+
for (;;) {
|
|
171
|
+
const [key, job] = [...jobs].find(([, j]) => j.kind === "changes") ?? [...jobs][0] ?? [];
|
|
172
|
+
if (key && job) {
|
|
173
|
+
jobs.delete(key);
|
|
174
|
+
await withTenant(job.tenant, () => job.kind === "scan" ? scanMount(job.mountId) : followChanges(job.mountId)).catch((err) => console.error(`[dateien] ${job.kind} ${job.mountId}`, err));
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
let progressed = false;
|
|
178
|
+
for (const tenant of [...active]) {
|
|
179
|
+
const did = await withTenant(tenant, async () => (await indexNext()) || (await embedTexts()) || (await embedPictures())).catch((err) => {
|
|
180
|
+
console.error(`[dateien] ${tenant}`, err);
|
|
181
|
+
return false;
|
|
182
|
+
});
|
|
183
|
+
if (did) {
|
|
184
|
+
progressed = true;
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
active.delete(tenant);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (!progressed) {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Resolves once nothing waits: every mount listed, every file indexed, every vector made. */
|
|
196
|
+
export async function flushMounts() {
|
|
197
|
+
while (working) {
|
|
198
|
+
await working;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* At start, and hourly: every tenant's mounts watched and listed again. A folder is listed whole
|
|
203
|
+
* each time; a plugin's mount asks its `changes` from the cursor it kept, as often as its kind
|
|
204
|
+
* says, and is listed whole once a week or when its `changes` can't say.
|
|
205
|
+
*/
|
|
206
|
+
export async function startMounts() {
|
|
207
|
+
const started = new Set();
|
|
208
|
+
const scanAll = async () => {
|
|
209
|
+
for (const tenant of await knownTenants()) {
|
|
210
|
+
await withTenant(tenant, async () => {
|
|
211
|
+
if (!(await dateienOn())) {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
for (const mount of await db.query.spaceMount.findMany()) {
|
|
215
|
+
if (isFolder(mount)) {
|
|
216
|
+
if (managed) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
await watchMount(mount).catch(() => undefined);
|
|
220
|
+
queue(tenant, mount.id, "scan");
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const kind = await kindOf(mount);
|
|
224
|
+
if (!kind) {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const open = await openOf(mount).catch(() => null);
|
|
228
|
+
if (!open) {
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
await watchMount(mount).catch(() => undefined);
|
|
232
|
+
const stale = !(mount.cursor && mount.scannedAt) ||
|
|
233
|
+
Date.now() - mount.scannedAt.getTime() > RELIST_MS;
|
|
234
|
+
const due = !started.has(mount.id) ||
|
|
235
|
+
(!open.reader.watch &&
|
|
236
|
+
Date.now() - (open.askedAt ?? 0) >= (kind.everyHours ?? 1) * 3600_000 - 60_000);
|
|
237
|
+
started.add(mount.id);
|
|
238
|
+
if (stale) {
|
|
239
|
+
queue(tenant, mount.id, "scan");
|
|
240
|
+
}
|
|
241
|
+
else if (due) {
|
|
242
|
+
queue(tenant, mount.id, "changes");
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}).catch((err) => console.error(`[dateien] start ${tenant}`, err));
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
await scanAll();
|
|
249
|
+
setInterval(() => void scanAll(), RESCAN_MS).unref();
|
|
250
|
+
}
|
|
251
|
+
// --- listing -------------------------------------------------------------------------------
|
|
252
|
+
async function sourceThere(mount) {
|
|
253
|
+
if (!isFolder(mount)) {
|
|
254
|
+
return Boolean(await kindOf(mount));
|
|
255
|
+
}
|
|
256
|
+
return Boolean((await stat(folderPath(mount)).catch(() => null))?.isDirectory());
|
|
257
|
+
}
|
|
258
|
+
/** Keeps where the source's changes go on from, in this process and for the next start. */
|
|
259
|
+
async function keepCursor(mountId, open, cursor) {
|
|
260
|
+
open.cursor = cursor;
|
|
261
|
+
open.askedAt = Date.now();
|
|
262
|
+
await db.update(schema.spaceMount).set({ cursor }).where(eq(schema.spaceMount.id, mountId));
|
|
263
|
+
}
|
|
264
|
+
/** What a plugin's reader threw while listing: the account went, the bucket can't be reached. */
|
|
265
|
+
async function away(mountId, err) {
|
|
266
|
+
await setStatus(mountId, "away", String(err?.message ?? err).slice(0, 300));
|
|
267
|
+
}
|
|
268
|
+
async function setStatus(mountId, status, error) {
|
|
269
|
+
await db
|
|
270
|
+
.update(schema.spaceMount)
|
|
271
|
+
.set({ status, error, updatedAt: new Date() })
|
|
272
|
+
.where(eq(schema.spaceMount.id, mountId));
|
|
273
|
+
}
|
|
274
|
+
/** Lists the whole tree against the rows. */
|
|
275
|
+
export async function scanMount(mountId) {
|
|
276
|
+
const mount = await db.query.spaceMount.findFirst({ where: eq(schema.spaceMount.id, mountId) });
|
|
277
|
+
if (!mount) {
|
|
278
|
+
closeMount(mountId);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
// A drive not plugged in, a folder moved: what was found stays found, nothing opens.
|
|
282
|
+
if (!(await sourceThere(mount))) {
|
|
283
|
+
await setStatus(mount.id, "away", null);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
await setStatus(mount.id, "scanning", null);
|
|
287
|
+
const listed = [];
|
|
288
|
+
try {
|
|
289
|
+
const open = await openOf(mount);
|
|
290
|
+
await keepCursor(mount.id, open, (await open.reader.changes(null)).cursor);
|
|
291
|
+
for await (const entry of open.reader.list()) {
|
|
292
|
+
listed.push(entry);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
catch (err) {
|
|
296
|
+
if (isFolder(mount)) {
|
|
297
|
+
throw err;
|
|
298
|
+
}
|
|
299
|
+
await away(mount.id, err);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
await reconcile(mount, listed, null);
|
|
303
|
+
await db
|
|
304
|
+
.update(schema.spaceMount)
|
|
305
|
+
.set({ status: "ready", scannedAt: new Date(), updatedAt: new Date() })
|
|
306
|
+
.where(eq(schema.spaceMount.id, mount.id));
|
|
307
|
+
}
|
|
308
|
+
/** What the watcher told of: the changes since the last round, or the whole tree again. */
|
|
309
|
+
async function followChanges(mountId) {
|
|
310
|
+
const mount = await db.query.spaceMount.findFirst({ where: eq(schema.spaceMount.id, mountId) });
|
|
311
|
+
if (!mount) {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
let changes;
|
|
315
|
+
try {
|
|
316
|
+
const open = await openOf(mount);
|
|
317
|
+
changes = await open.reader.changes(open.cursor);
|
|
318
|
+
await keepCursor(mount.id, open, changes.cursor);
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
if (isFolder(mount)) {
|
|
322
|
+
throw err;
|
|
323
|
+
}
|
|
324
|
+
await away(mount.id, err);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (changes.relist) {
|
|
328
|
+
return scanMount(mountId);
|
|
329
|
+
}
|
|
330
|
+
if (mount.status === "away") {
|
|
331
|
+
await setStatus(mount.id, "ready", null);
|
|
332
|
+
}
|
|
333
|
+
await reconcile(mount, changes.changed, [...changes.gone, ...changes.changed.map((c) => c.path)], changes.goneIds ?? []);
|
|
334
|
+
}
|
|
335
|
+
async function hashOf(reader, entry) {
|
|
336
|
+
if (entry.size > MAX_READ_BYTES) {
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const data = await reader.read(entry.path, entry.id ? { id: entry.id } : {}).catch(() => null);
|
|
340
|
+
return data ? createHash("sha256").update(data).digest("hex") : null;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Brings the rows in line with what the source listed. `under`: the paths the listing covers
|
|
344
|
+
* (a change's), null for the whole tree; `goneIds`: files gone by the source's id. A file listed
|
|
345
|
+
* at a new path keeps its row: found by the source's id where it has one, else as a file a row
|
|
346
|
+
* no longer listed has (same size and time, else same bytes).
|
|
347
|
+
*/
|
|
348
|
+
async function reconcile(mount, listed, under, goneIds = []) {
|
|
349
|
+
const t = schema.spaceMountFile;
|
|
350
|
+
const removeRows = async (ids) => {
|
|
351
|
+
for (let i = 0; i < ids.length; i += 500) {
|
|
352
|
+
await db.delete(t).where(inArray(t.id, ids.slice(i, i + 500)));
|
|
353
|
+
}
|
|
354
|
+
for (const id of ids) {
|
|
355
|
+
await objects.remove(thumbKey(mount.id, id)).catch(() => undefined);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const changed = [];
|
|
359
|
+
if (goneIds.length) {
|
|
360
|
+
const rows = await db.query.spaceMountFile.findMany({
|
|
361
|
+
where: and(eq(t.mountId, mount.id), inArray(t.sourceId, goneIds)),
|
|
362
|
+
columns: { id: true, path: true },
|
|
363
|
+
});
|
|
364
|
+
await removeRows(rows.map((r) => r.id));
|
|
365
|
+
changed.push(...rows.map((r) => r.path));
|
|
366
|
+
}
|
|
367
|
+
const rows = await db.query.spaceMountFile.findMany({
|
|
368
|
+
where: eq(t.mountId, mount.id),
|
|
369
|
+
columns: { id: true, path: true, size: true, modified: true, hash: true, sourceId: true },
|
|
370
|
+
});
|
|
371
|
+
const byPath = new Map(rows.map((r) => [r.path, r]));
|
|
372
|
+
const byId = new Map(rows.filter((r) => r.sourceId).map((r) => [r.sourceId, r]));
|
|
373
|
+
const seen = new Set(listed.map((e) => e.path));
|
|
374
|
+
const covered = (path) => under === null || under.some((p) => path === p || path.startsWith(`${p}/`));
|
|
375
|
+
const gone = rows.filter((r) => covered(r.path) && !seen.has(r.path));
|
|
376
|
+
const taken = new Set();
|
|
377
|
+
const fresh = [];
|
|
378
|
+
const reader = await readerOf(mount);
|
|
379
|
+
const now = new Date();
|
|
380
|
+
for (const entry of listed) {
|
|
381
|
+
const mime = documentMime(entry.path, entry.mime ?? "");
|
|
382
|
+
const sourceId = entry.id ?? null;
|
|
383
|
+
const known = sourceId ? byId.get(sourceId) : undefined;
|
|
384
|
+
if (known && known.path !== entry.path) {
|
|
385
|
+
// Moved or renamed at the source: the row follows its id. A file at the new path is replaced.
|
|
386
|
+
const there = byPath.get(entry.path);
|
|
387
|
+
if (there && there.id !== known.id) {
|
|
388
|
+
await removeRows([there.id]);
|
|
389
|
+
byPath.delete(entry.path);
|
|
390
|
+
}
|
|
391
|
+
taken.add(known.id);
|
|
392
|
+
changed.push(known.path, entry.path);
|
|
393
|
+
byPath.delete(known.path);
|
|
394
|
+
byPath.set(entry.path, { ...known, path: entry.path });
|
|
395
|
+
await db
|
|
396
|
+
.update(t)
|
|
397
|
+
.set({
|
|
398
|
+
path: entry.path,
|
|
399
|
+
name: basename(entry.path),
|
|
400
|
+
mime,
|
|
401
|
+
size: entry.size,
|
|
402
|
+
modified: entry.modified,
|
|
403
|
+
status: "pending",
|
|
404
|
+
updatedAt: now,
|
|
405
|
+
})
|
|
406
|
+
.where(eq(t.id, known.id));
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
const row = byPath.get(entry.path);
|
|
410
|
+
if (row) {
|
|
411
|
+
const differs = row.size !== entry.size || row.modified !== entry.modified;
|
|
412
|
+
if (differs) {
|
|
413
|
+
changed.push(entry.path);
|
|
414
|
+
}
|
|
415
|
+
if (differs || (sourceId && row.sourceId !== sourceId)) {
|
|
416
|
+
await db
|
|
417
|
+
.update(t)
|
|
418
|
+
.set({
|
|
419
|
+
size: entry.size,
|
|
420
|
+
modified: entry.modified,
|
|
421
|
+
sourceId: sourceId ?? row.sourceId,
|
|
422
|
+
...(differs ? { status: "pending" } : {}),
|
|
423
|
+
updatedAt: now,
|
|
424
|
+
})
|
|
425
|
+
.where(eq(t.id, row.id));
|
|
426
|
+
}
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
const alike = sourceId
|
|
430
|
+
? []
|
|
431
|
+
: gone.filter((g) => g.size === entry.size && !taken.has(g.id) && !g.sourceId);
|
|
432
|
+
let moved = alike.find((g) => g.modified === entry.modified);
|
|
433
|
+
if (!moved && alike.some((g) => g.hash)) {
|
|
434
|
+
const hash = await hashOf(reader, entry);
|
|
435
|
+
moved = alike.find((g) => g.hash && g.hash === hash);
|
|
436
|
+
}
|
|
437
|
+
if (moved) {
|
|
438
|
+
taken.add(moved.id);
|
|
439
|
+
changed.push(moved.path, entry.path);
|
|
440
|
+
// Its words name its path: indexed again, from the cache, keeping its vectors.
|
|
441
|
+
await db
|
|
442
|
+
.update(t)
|
|
443
|
+
.set({
|
|
444
|
+
path: entry.path,
|
|
445
|
+
name: basename(entry.path),
|
|
446
|
+
mime,
|
|
447
|
+
modified: entry.modified,
|
|
448
|
+
status: "pending",
|
|
449
|
+
updatedAt: now,
|
|
450
|
+
})
|
|
451
|
+
.where(eq(t.id, moved.id));
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
fresh.push({
|
|
455
|
+
id: nanoid(12),
|
|
456
|
+
mountId: mount.id,
|
|
457
|
+
spaceId: mount.spaceId,
|
|
458
|
+
path: entry.path,
|
|
459
|
+
sourceId,
|
|
460
|
+
name: basename(entry.path),
|
|
461
|
+
mime,
|
|
462
|
+
size: entry.size,
|
|
463
|
+
modified: entry.modified,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
const removed = gone.filter((g) => !taken.has(g.id));
|
|
467
|
+
await removeRows(removed.map((g) => g.id));
|
|
468
|
+
for (let i = 0; i < fresh.length; i += 200) {
|
|
469
|
+
await db
|
|
470
|
+
.insert(t)
|
|
471
|
+
.values(fresh.slice(i, i + 200))
|
|
472
|
+
.onConflictDoNothing();
|
|
473
|
+
}
|
|
474
|
+
if (fresh.length || taken.size || listed.length) {
|
|
475
|
+
kick(currentTenant());
|
|
476
|
+
}
|
|
477
|
+
changed.push(...fresh.map((f) => f.path), ...removed.map((r) => r.path));
|
|
478
|
+
if (changed.length) {
|
|
479
|
+
for (const listener of changeListeners) {
|
|
480
|
+
listener(mount, changed);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
// --- indexing a file: words, thumbnail, units ------------------------------------------------
|
|
485
|
+
/** The folder of the first level a file lies in, or null for a file at the top. */
|
|
486
|
+
const firstFolder = (path) => (path.includes("/") ? path.split("/")[0] : null);
|
|
487
|
+
/** Files read at once: reading, hashing and drawing a thumbnail wait on the disk and a child. */
|
|
488
|
+
const INDEX_LANES = 3;
|
|
489
|
+
async function indexNext() {
|
|
490
|
+
const files = await db.query.spaceMountFile.findMany({
|
|
491
|
+
where: eq(schema.spaceMountFile.status, "pending"),
|
|
492
|
+
orderBy: [asc(schema.spaceMountFile.path)],
|
|
493
|
+
limit: INDEX_LANES,
|
|
494
|
+
});
|
|
495
|
+
if (!files.length) {
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
const mounts = await db.query.spaceMount.findMany({
|
|
499
|
+
where: inArray(schema.spaceMount.id, [...new Set(files.map((f) => f.mountId))]),
|
|
500
|
+
});
|
|
501
|
+
await Promise.all(files.map(async (file) => {
|
|
502
|
+
const mount = mounts.find((m) => m.id === file.mountId);
|
|
503
|
+
if (!mount) {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
try {
|
|
507
|
+
await indexFile(mount, file);
|
|
508
|
+
}
|
|
509
|
+
catch (err) {
|
|
510
|
+
await db
|
|
511
|
+
.update(schema.spaceMountFile)
|
|
512
|
+
.set({ status: "failed", error: String(err.message ?? err).slice(0, 300) })
|
|
513
|
+
.where(eq(schema.spaceMountFile.id, file.id));
|
|
514
|
+
}
|
|
515
|
+
}));
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* The text of a file's bytes, read without a model; through the cache. `again`: a kept read
|
|
520
|
+
* without text is read once more (OCR may not have been there).
|
|
521
|
+
*/
|
|
522
|
+
function textOf(file, hash, data, again = false) {
|
|
523
|
+
return cachedText(hash, async () => data ? ownText({ data, name: file.name, mime: file.mime }).catch(() => null) : null, again);
|
|
524
|
+
}
|
|
525
|
+
/** What a text calls itself: its front matter's `title:`, else its first `#` heading. */
|
|
526
|
+
export function titleOf(text) {
|
|
527
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
|
|
528
|
+
const named = front ? /^title:\s*["']?(.+?)["']?\s*$/m.exec(front)?.[1] : undefined;
|
|
529
|
+
const heading = /^#\s+(.+?)\s*#*\s*$/m.exec(text)?.[1];
|
|
530
|
+
const title = (named ?? heading)?.trim();
|
|
531
|
+
return title ? title.slice(0, 200) : null;
|
|
532
|
+
}
|
|
533
|
+
const hasText = (file) => TEXT.test(file.mime) && file.size <= MAX_TEXT_BYTES;
|
|
534
|
+
/** Reads a file once: its fingerprint, its words, its thumbnail, its units (vectors later). */
|
|
535
|
+
async function indexFile(mount, file) {
|
|
536
|
+
const t = schema.spaceMountFile;
|
|
537
|
+
const u = schema.spaceMountUnit;
|
|
538
|
+
const reader = await readerOf(mount);
|
|
539
|
+
const big = file.size > MAX_READ_BYTES;
|
|
540
|
+
const data = big ? null : await reader.read(file.path, idOf(file));
|
|
541
|
+
const hash = data ? createHash("sha256").update(data).digest("hex") : null;
|
|
542
|
+
const same = hash !== null && hash === file.hash;
|
|
543
|
+
const parsed = hash && hasText(file) ? await textOf(file, hash, data ?? undefined, true) : null;
|
|
544
|
+
const text = parsed?.markdown ?? "";
|
|
545
|
+
const pages = parsed?.pages ?? null;
|
|
546
|
+
const base = { spaceId: mount.spaceId, mountId: mount.id, fileId: file.id };
|
|
547
|
+
const units = [{ ...base, idx: 0 }];
|
|
548
|
+
for (const unit of text ? textUnits(text) : []) {
|
|
549
|
+
units.push({ ...base, idx: units.length, ...unit });
|
|
550
|
+
}
|
|
551
|
+
if (hash && PICTURE.test(file.mime)) {
|
|
552
|
+
units.push({ ...base, idx: units.length, kind: "image" });
|
|
553
|
+
}
|
|
554
|
+
else if (hash && file.mime === "application/pdf") {
|
|
555
|
+
for (let page = 1; page <= Math.min(pages ?? MAX_PAGE_PICTURES, MAX_PAGE_PICTURES); page++) {
|
|
556
|
+
units.push({ ...base, idx: units.length, kind: "page", sheet: page });
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
// The same bytes at another path: every vector but the name's stays.
|
|
560
|
+
const before = same
|
|
561
|
+
? await db
|
|
562
|
+
.select({
|
|
563
|
+
kind: u.kind,
|
|
564
|
+
sheet: u.sheet,
|
|
565
|
+
start: u.start,
|
|
566
|
+
end: u.end,
|
|
567
|
+
embedding: u.embedding,
|
|
568
|
+
model: u.model,
|
|
569
|
+
})
|
|
570
|
+
.from(u)
|
|
571
|
+
.where(eq(u.fileId, file.id))
|
|
572
|
+
: [];
|
|
573
|
+
const key = (x) => `${x.kind ?? ""}|${x.sheet ?? ""}|${x.start ?? ""}|${x.end ?? ""}`;
|
|
574
|
+
const kept = new Map(before.filter((b) => b.start !== null || b.kind).map((b) => [key(b), b]));
|
|
575
|
+
await db.delete(u).where(eq(u.fileId, file.id));
|
|
576
|
+
const words = [];
|
|
577
|
+
for (let i = 0; i < units.length; i += 100) {
|
|
578
|
+
const batch = units.slice(i, i + 100).map((unit) => {
|
|
579
|
+
const old = kept.get(key(unit));
|
|
580
|
+
return old ? { ...unit, embedding: old.embedding, model: old.model } : unit;
|
|
581
|
+
});
|
|
582
|
+
const ids = await db.insert(u).values(batch).returning({ id: u.id });
|
|
583
|
+
ids.forEach(({ id }, j) => {
|
|
584
|
+
const unit = batch[j];
|
|
585
|
+
if (unit.idx === 0) {
|
|
586
|
+
words.push([id, pathWords(file.path)]);
|
|
587
|
+
}
|
|
588
|
+
else if (!unit.kind) {
|
|
589
|
+
words.push([
|
|
590
|
+
id,
|
|
591
|
+
unitText(text, unit),
|
|
592
|
+
]);
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
for (let i = 0; i < words.length; i += 50) {
|
|
597
|
+
const part = words.slice(i, i + 50);
|
|
598
|
+
for (const table of ["space_mount_unit_fts", "space_mount_unit_tri"]) {
|
|
599
|
+
await db.run(sql `INSERT INTO ${sql.raw(table)}(rowid, text) VALUES ${sql.join(part.map(([id, w]) => sql `(${id}, ${w})`), sql `, `)}`);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
let thumb = same && file.thumb;
|
|
603
|
+
if (data && !thumb && hasThumb(file.mime)) {
|
|
604
|
+
const made = await makeThumb(data, file.mime);
|
|
605
|
+
if (made) {
|
|
606
|
+
await objects.put(thumbKey(mount.id, file.id), made);
|
|
607
|
+
}
|
|
608
|
+
thumb = Boolean(made);
|
|
609
|
+
}
|
|
610
|
+
await db
|
|
611
|
+
.update(t)
|
|
612
|
+
.set({
|
|
613
|
+
hash,
|
|
614
|
+
pages,
|
|
615
|
+
title: titleOf(text),
|
|
616
|
+
thumb,
|
|
617
|
+
status: big || (!text && !hasThumb(file.mime)) ? "skipped" : "ready",
|
|
618
|
+
error: null,
|
|
619
|
+
updatedAt: new Date(),
|
|
620
|
+
})
|
|
621
|
+
.where(eq(t.id, file.id));
|
|
622
|
+
const folder = firstFolder(file.path);
|
|
623
|
+
if (mount.folderCategoryId && folder) {
|
|
624
|
+
const category = await db.query.spaceCategory.findFirst({
|
|
625
|
+
where: eq(schema.spaceCategory.id, mount.folderCategoryId),
|
|
626
|
+
});
|
|
627
|
+
if (category) {
|
|
628
|
+
await setItemCategories(mount.spaceId, { mountFileId: file.id }, { [category.name]: folder }, "origin");
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
// --- vectors -------------------------------------------------------------------------------
|
|
633
|
+
const vectorBytes = (v) => Buffer.from(new Float32Array(v).buffer);
|
|
634
|
+
/** Units in one call to the embedding model. */
|
|
635
|
+
const EMBED_BATCH = 32;
|
|
636
|
+
const lacking = (model) => or(isNull(schema.spaceMountUnit.model), ne(schema.spaceMountUnit.model, model));
|
|
637
|
+
/** The text of a file for its vectors: the cache, else its original read again. */
|
|
638
|
+
async function textForVectors(mount, file) {
|
|
639
|
+
if (!(file.hash && hasText(file))) {
|
|
640
|
+
return "";
|
|
641
|
+
}
|
|
642
|
+
const kept = await keptText(file.hash);
|
|
643
|
+
if (kept !== undefined) {
|
|
644
|
+
return kept?.markdown ?? "";
|
|
645
|
+
}
|
|
646
|
+
const data = await (await readerOf(mount)).read(file.path, idOf(file));
|
|
647
|
+
if (createHash("sha256").update(data).digest("hex") !== file.hash) {
|
|
648
|
+
// Changed since: the next listing indexes it again.
|
|
649
|
+
return "";
|
|
650
|
+
}
|
|
651
|
+
return (await textOf(file, file.hash, data))?.markdown ?? "";
|
|
652
|
+
}
|
|
653
|
+
/** The vectors of up to EMBED_BATCH passages and names, of the files that lack them. */
|
|
654
|
+
async function embedTexts() {
|
|
655
|
+
const resolved = await embeddingModel().catch(() => null);
|
|
656
|
+
// The model is not there or not working: the next start, or the next change, tries again.
|
|
657
|
+
if (!resolved || inRow >= MAX_IN_ROW) {
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
660
|
+
const u = schema.spaceMountUnit;
|
|
661
|
+
const todo = await db
|
|
662
|
+
.select()
|
|
663
|
+
.from(u)
|
|
664
|
+
.where(and(isNull(u.kind), lacking(resolved.ref), failed.size ? notInArray(u.fileId, [...failed]) : undefined))
|
|
665
|
+
.orderBy(asc(u.fileId), asc(u.idx))
|
|
666
|
+
.limit(EMBED_BATCH);
|
|
667
|
+
if (!todo.length) {
|
|
668
|
+
return false;
|
|
669
|
+
}
|
|
670
|
+
const fileIds = [...new Set(todo.map((x) => x.fileId))];
|
|
671
|
+
const files = await db.query.spaceMountFile.findMany({
|
|
672
|
+
where: inArray(schema.spaceMountFile.id, fileIds),
|
|
673
|
+
});
|
|
674
|
+
const mounts = await db.query.spaceMount.findMany({
|
|
675
|
+
where: inArray(schema.spaceMount.id, [...new Set(files.map((f) => f.mountId))]),
|
|
676
|
+
});
|
|
677
|
+
const texts = new Map();
|
|
678
|
+
for (const file of files) {
|
|
679
|
+
const mount = mounts.find((m) => m.id === file.mountId);
|
|
680
|
+
texts.set(file.id, await textForVectors(mount, file).catch(() => ""));
|
|
681
|
+
}
|
|
682
|
+
const values = todo.map((unit) => {
|
|
683
|
+
const file = files.find((f) => f.id === unit.fileId);
|
|
684
|
+
if (!file) {
|
|
685
|
+
return "";
|
|
686
|
+
}
|
|
687
|
+
if (unit.start === null || unit.end === null) {
|
|
688
|
+
return pathWords(file.path);
|
|
689
|
+
}
|
|
690
|
+
return unitText(texts.get(file.id) ?? "", unit);
|
|
691
|
+
});
|
|
692
|
+
try {
|
|
693
|
+
const result = await embedMany({
|
|
694
|
+
model: resolved.model,
|
|
695
|
+
values: values.map((v) => v || " "),
|
|
696
|
+
maxParallelCalls: 2,
|
|
697
|
+
});
|
|
698
|
+
for (const [i, unit] of todo.entries()) {
|
|
699
|
+
await db
|
|
700
|
+
.update(u)
|
|
701
|
+
.set({ embedding: vectorBytes(Array.from(result.embeddings[i])), model: resolved.ref })
|
|
702
|
+
.where(eq(u.id, unit.id));
|
|
703
|
+
}
|
|
704
|
+
inRow = 0;
|
|
705
|
+
}
|
|
706
|
+
catch (err) {
|
|
707
|
+
console.error("[dateien] embedding failed", err.message);
|
|
708
|
+
inRow++;
|
|
709
|
+
for (const id of fileIds) {
|
|
710
|
+
failed.add(id);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return true;
|
|
714
|
+
}
|
|
715
|
+
/** The pictures of the next file whose picture units lack a vector of the model at hand. */
|
|
716
|
+
async function embedPictures() {
|
|
717
|
+
const resolved = await embeddingModel().catch(() => null);
|
|
718
|
+
const embedImage = resolved?.embedImage;
|
|
719
|
+
if (!(resolved && embedImage) || inRow >= MAX_IN_ROW) {
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
const u = schema.spaceMountUnit;
|
|
723
|
+
const first = await db
|
|
724
|
+
.select({ fileId: u.fileId })
|
|
725
|
+
.from(u)
|
|
726
|
+
.where(and(isNotNull(u.kind), lacking(resolved.ref), failed.size ? notInArray(u.fileId, [...failed]) : undefined))
|
|
727
|
+
.limit(1);
|
|
728
|
+
const fileId = first[0]?.fileId;
|
|
729
|
+
if (!fileId) {
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
const file = await db.query.spaceMountFile.findFirst({
|
|
733
|
+
where: eq(schema.spaceMountFile.id, fileId),
|
|
734
|
+
});
|
|
735
|
+
const mount = file
|
|
736
|
+
? await db.query.spaceMount.findFirst({ where: eq(schema.spaceMount.id, file.mountId) })
|
|
737
|
+
: undefined;
|
|
738
|
+
if (!(file && mount)) {
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
const units = await db
|
|
742
|
+
.select({ id: u.id, kind: u.kind, sheet: u.sheet })
|
|
743
|
+
.from(u)
|
|
744
|
+
.where(and(eq(u.fileId, fileId), isNotNull(u.kind), lacking(resolved.ref)));
|
|
745
|
+
try {
|
|
746
|
+
const data = await (await readerOf(mount)).read(file.path, idOf(file));
|
|
747
|
+
const pictures = file.mime === "application/pdf"
|
|
748
|
+
? new Map((await pdfPages(data)).map((p) => [p.page, p.jpeg]))
|
|
749
|
+
: new Map([[0, await jpegOf(data)]]);
|
|
750
|
+
for (const unit of units) {
|
|
751
|
+
const jpeg = pictures.get(unit.kind === "page" ? (unit.sheet ?? 0) : 0);
|
|
752
|
+
if (!jpeg) {
|
|
753
|
+
// A page the PDF does not have.
|
|
754
|
+
await db.delete(u).where(eq(u.id, unit.id));
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
await db
|
|
758
|
+
.update(u)
|
|
759
|
+
.set({ embedding: vectorBytes(await embedImage(jpeg)), model: resolved.ref })
|
|
760
|
+
.where(eq(u.id, unit.id));
|
|
761
|
+
}
|
|
762
|
+
inRow = 0;
|
|
763
|
+
}
|
|
764
|
+
catch (err) {
|
|
765
|
+
console.error("[dateien] picture", file.path, err.message);
|
|
766
|
+
inRow++;
|
|
767
|
+
failed.add(fileId);
|
|
768
|
+
}
|
|
769
|
+
return true;
|
|
770
|
+
}
|
|
771
|
+
function slugOf(name) {
|
|
772
|
+
return (name
|
|
773
|
+
.normalize("NFKD")
|
|
774
|
+
.replace(/[̀-ͯ]/g, "")
|
|
775
|
+
.toLowerCase()
|
|
776
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
777
|
+
.replace(/^-|-$/g, "")
|
|
778
|
+
.slice(0, 60) || "ordner");
|
|
779
|
+
}
|
|
780
|
+
async function viewOf(mounts) {
|
|
781
|
+
if (!mounts.length) {
|
|
782
|
+
return [];
|
|
783
|
+
}
|
|
784
|
+
const ids = mounts.map((m) => m.id);
|
|
785
|
+
const counts = await db.all(sql `
|
|
786
|
+
SELECT mount_id, count(*) AS n, coalesce(sum(size), 0) AS bytes,
|
|
787
|
+
sum(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending
|
|
788
|
+
FROM space_mount_file WHERE mount_id IN (${sql.join(ids.map((id) => sql `${id}`), sql `, `)}) GROUP BY mount_id`);
|
|
789
|
+
const resolved = await embeddingModel().catch(() => null);
|
|
790
|
+
const vectors = resolved
|
|
791
|
+
? await db.all(sql `
|
|
792
|
+
SELECT mount_id, count(*) AS n FROM space_mount_unit
|
|
793
|
+
WHERE mount_id IN (${sql.join(ids.map((id) => sql `${id}`), sql `, `)}) AND (model IS NULL OR model != ${resolved.ref})
|
|
794
|
+
${resolved.embedImage ? sql `` : sql `AND kind IS NULL`}
|
|
795
|
+
GROUP BY mount_id`)
|
|
796
|
+
: [];
|
|
797
|
+
return mounts.map((m) => {
|
|
798
|
+
const c = counts.find((x) => x.mount_id === m.id);
|
|
799
|
+
return {
|
|
800
|
+
id: m.id,
|
|
801
|
+
name: m.name,
|
|
802
|
+
slug: m.slug,
|
|
803
|
+
kind: m.kind,
|
|
804
|
+
plugin: m.plugin,
|
|
805
|
+
where: m.location ?? folderPath(m),
|
|
806
|
+
status: m.status,
|
|
807
|
+
error: m.error,
|
|
808
|
+
files: c?.n ?? 0,
|
|
809
|
+
bytes: c?.bytes ?? 0,
|
|
810
|
+
pending: c?.pending ?? 0,
|
|
811
|
+
vectorsPending: vectors.find((v) => v.mount_id === m.id)?.n ?? 0,
|
|
812
|
+
scannedAt: m.scannedAt?.toISOString() ?? null,
|
|
813
|
+
folderCategoryId: m.folderCategoryId,
|
|
814
|
+
writable: m.writable,
|
|
815
|
+
};
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
/** The mounts of a space `who` may see. */
|
|
819
|
+
export async function listMounts(spaceId, who) {
|
|
820
|
+
await requireDateien();
|
|
821
|
+
const mounts = await db.query.spaceMount.findMany({
|
|
822
|
+
where: eq(schema.spaceMount.spaceId, spaceId),
|
|
823
|
+
orderBy: [asc(schema.spaceMount.createdAt)],
|
|
824
|
+
});
|
|
825
|
+
const ok = await readableMounts(spaceId, who, mounts.map((m) => m.id));
|
|
826
|
+
return viewOf(mounts.filter((m) => ok.has(m.id)));
|
|
827
|
+
}
|
|
828
|
+
/** A mount `who` may see, or not found. */
|
|
829
|
+
export async function mountRow(spaceId, mountId, who) {
|
|
830
|
+
await requireDateien();
|
|
831
|
+
const mount = await db.query.spaceMount.findFirst({
|
|
832
|
+
where: and(eq(schema.spaceMount.id, mountId), eq(schema.spaceMount.spaceId, spaceId)),
|
|
833
|
+
});
|
|
834
|
+
if (!(mount && (await readableMounts(spaceId, who, [mount.id])).has(mount.id))) {
|
|
835
|
+
throw notFound();
|
|
836
|
+
}
|
|
837
|
+
return mount;
|
|
838
|
+
}
|
|
839
|
+
export async function mountView(spaceId, mountId, who) {
|
|
840
|
+
return (await viewOf([await mountRow(spaceId, mountId, who)]))[0];
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* The rules a mount is written with: who sees it, which wizards may use it, what an AI working
|
|
844
|
+
* for a person may do. Where its files may be changed, the admins and the team write them, and an
|
|
845
|
+
* AI writes drafts where it may; a wizard never does (it doesn't publish).
|
|
846
|
+
*/
|
|
847
|
+
function mountRules(mountId, { see, wizards, agents, writable }) {
|
|
848
|
+
const rule = (subjectKind, subjectId, w) => ({
|
|
849
|
+
subjectKind,
|
|
850
|
+
subjectId,
|
|
851
|
+
resourceKind: "mount",
|
|
852
|
+
resourceId: mountId,
|
|
853
|
+
r: "allow",
|
|
854
|
+
w,
|
|
855
|
+
x: null,
|
|
856
|
+
});
|
|
857
|
+
// Who sees it may change it where it is writable, but clients and guests: they only read.
|
|
858
|
+
const team = see.includes("team") ? ["member"] : [];
|
|
859
|
+
const ids = wizards === "all" ? ["*"] : wizards === "none" ? [] : wizards;
|
|
860
|
+
return [
|
|
861
|
+
...["owner", "admin", ...team].map((r) => rule("role", r, writable ? "allow" : null)),
|
|
862
|
+
...(see.includes("clients") ? [rule("role", "client", null)] : []),
|
|
863
|
+
...(see.includes("guests") ? [rule("guest", null, null)] : []),
|
|
864
|
+
...ids.map((id) => rule("wizard", id, null)),
|
|
865
|
+
...(agents === "none"
|
|
866
|
+
? []
|
|
867
|
+
: [rule("agent", null, writable && agents === "drafts" ? "allow" : null)]),
|
|
868
|
+
];
|
|
869
|
+
}
|
|
870
|
+
async function writeRules(spaceId, mountId, rules, by) {
|
|
871
|
+
const r = schema.rwxRule;
|
|
872
|
+
// A space is seeded where it has no rules yet: a mount's rules first would leave it unseeded.
|
|
873
|
+
if (!(await db.query.rwxRule.findFirst({ where: eq(r.spaceId, spaceId), columns: { id: true } }))) {
|
|
874
|
+
await seedRwx(spaceId);
|
|
875
|
+
}
|
|
876
|
+
await db
|
|
877
|
+
.delete(r)
|
|
878
|
+
.where(and(eq(r.spaceId, spaceId), eq(r.resourceKind, "mount"), eq(r.resourceId, mountId)));
|
|
879
|
+
if (rules.length) {
|
|
880
|
+
await db.insert(r).values(rules.map((x) => ({
|
|
881
|
+
id: nanoid(12),
|
|
882
|
+
tenantId: currentTenant(),
|
|
883
|
+
spaceId,
|
|
884
|
+
...x,
|
|
885
|
+
createdBy: by,
|
|
886
|
+
})));
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
/** Where a mount comes from: a folder of this computer, or what a plugin's kind prepared. */
|
|
890
|
+
async function sourceOf(spaceId, input) {
|
|
891
|
+
if (!input.kind || input.kind === "folder") {
|
|
892
|
+
await requireFolders();
|
|
893
|
+
const typed = input.path ?? "";
|
|
894
|
+
const path = resolve(typed.replace(/^~(?=$|\/)/, homedir()));
|
|
895
|
+
if (!(typed && (await stat(path).catch(() => null))?.isDirectory())) {
|
|
896
|
+
throw new ServiceError("invalid", `There is no folder "${typed}".`);
|
|
897
|
+
}
|
|
898
|
+
return {
|
|
899
|
+
kind: "folder",
|
|
900
|
+
plugin: null,
|
|
901
|
+
source: { path },
|
|
902
|
+
name: basename(path) || path,
|
|
903
|
+
location: path,
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
const found = (await mountKinds()).find((k) => k.kind.kind === input.kind);
|
|
907
|
+
if (!found) {
|
|
908
|
+
throw new ServiceError("invalid", `No plugin brings mounts of the kind "${input.kind}".`);
|
|
909
|
+
}
|
|
910
|
+
let prepared;
|
|
911
|
+
try {
|
|
912
|
+
prepared = await found.kind.prepare({ space: spaceId, source: input.source ?? {} });
|
|
913
|
+
}
|
|
914
|
+
catch (err) {
|
|
915
|
+
throw new ServiceError("invalid", String(err?.message ?? err).slice(0, 300));
|
|
916
|
+
}
|
|
917
|
+
return {
|
|
918
|
+
kind: found.kind.kind,
|
|
919
|
+
plugin: found.plugin,
|
|
920
|
+
source: prepared.source,
|
|
921
|
+
name: prepared.name,
|
|
922
|
+
location: prepared.where,
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
/** Mounts a folder or a plugin's source in a space; listing and indexing go on in the background. */
|
|
926
|
+
export async function createMount(userId, spaceId, input) {
|
|
927
|
+
await requireDateien();
|
|
928
|
+
requireAdmin();
|
|
929
|
+
return addMount(userId, spaceId, input);
|
|
930
|
+
}
|
|
931
|
+
/** Mounts without asking who: `createMount`, and a command's conversion of folders. */
|
|
932
|
+
export async function addMount(userId, spaceId, input) {
|
|
933
|
+
const from = await sourceOf(spaceId, input);
|
|
934
|
+
if (input.writable && !(await mayWrite({ ...from, spaceId, name: from.name }))) {
|
|
935
|
+
throw new ServiceError("refused", NO_WRITE_RIGHTS);
|
|
936
|
+
}
|
|
937
|
+
const mounts = await db.query.spaceMount.findMany({
|
|
938
|
+
where: eq(schema.spaceMount.spaceId, spaceId),
|
|
939
|
+
});
|
|
940
|
+
if (mounts.some((m) => (m.location ?? folderPath(m)) === from.location)) {
|
|
941
|
+
throw new ServiceError("refused", `"${from.location}" is mounted in this space already.`);
|
|
942
|
+
}
|
|
943
|
+
const name = input.name?.trim() || from.name;
|
|
944
|
+
let slug = slugOf(name);
|
|
945
|
+
for (let n = 2; mounts.some((m) => m.slug === slug); n++) {
|
|
946
|
+
slug = `${slugOf(name)}-${n}`;
|
|
947
|
+
}
|
|
948
|
+
const category = input.folderCategory?.trim()
|
|
949
|
+
? await putCategory(spaceId, { name: input.folderCategory.trim(), type: "choice" })
|
|
950
|
+
: null;
|
|
951
|
+
const id = nanoid(12);
|
|
952
|
+
await db.insert(schema.spaceMount).values({
|
|
953
|
+
id,
|
|
954
|
+
tenantId: currentTenant(),
|
|
955
|
+
spaceId,
|
|
956
|
+
name,
|
|
957
|
+
slug,
|
|
958
|
+
kind: from.kind,
|
|
959
|
+
plugin: from.plugin,
|
|
960
|
+
source: from.source,
|
|
961
|
+
location: from.location,
|
|
962
|
+
folderCategoryId: category?.id ?? null,
|
|
963
|
+
writable: Boolean(input.writable),
|
|
964
|
+
createdBy: userId,
|
|
965
|
+
});
|
|
966
|
+
await writeRules(spaceId, id, mountRules(id, {
|
|
967
|
+
see: input.see,
|
|
968
|
+
wizards: input.wizards,
|
|
969
|
+
agents: input.agents,
|
|
970
|
+
writable: Boolean(input.writable),
|
|
971
|
+
}), userId);
|
|
972
|
+
const mount = (await db.query.spaceMount.findFirst({
|
|
973
|
+
where: eq(schema.spaceMount.id, id),
|
|
974
|
+
}));
|
|
975
|
+
await watchMount(mount).catch(() => undefined);
|
|
976
|
+
queue(currentTenant(), id, "scan");
|
|
977
|
+
return (await viewOf([mount]))[0];
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Whether a mount's account may write where it lives: a folder of this computer may; a plugin's
|
|
981
|
+
* kind says (false: its studio half connects the account again with the rights to write).
|
|
982
|
+
*/
|
|
983
|
+
export function mountCanWrite(mount) {
|
|
984
|
+
return mayWrite(mount);
|
|
985
|
+
}
|
|
986
|
+
/** Writing turned on where the mount's account may not write: the studio connects it again first. */
|
|
987
|
+
const NO_WRITE_RIGHTS = "The account may not write there yet. Connect it again with the rights to write.";
|
|
988
|
+
async function mayWrite(mount) {
|
|
989
|
+
if (isFolder(mount)) {
|
|
990
|
+
return true;
|
|
991
|
+
}
|
|
992
|
+
const kind = await kindOf(mount);
|
|
993
|
+
if (!kind) {
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
const asked = kind.canWrite?.({
|
|
997
|
+
id: mount.id ?? "",
|
|
998
|
+
space: mount.spaceId,
|
|
999
|
+
name: mount.name,
|
|
1000
|
+
source: mount.source,
|
|
1001
|
+
});
|
|
1002
|
+
return asked ? asked.catch(() => false) : true;
|
|
1003
|
+
}
|
|
1004
|
+
// --- a plugin's mounts, for the plugin ------------------------------------------------------
|
|
1005
|
+
/** The mounts of a plugin's kinds in the current tenant, of one space or of all. */
|
|
1006
|
+
export async function pluginMounts(plugin, space) {
|
|
1007
|
+
const rows = await db.query.spaceMount.findMany({
|
|
1008
|
+
where: and(eq(schema.spaceMount.plugin, plugin), space ? eq(schema.spaceMount.spaceId, space) : undefined),
|
|
1009
|
+
});
|
|
1010
|
+
return rows.map((m) => ({ ...pluginMount(m), kind: m.kind }));
|
|
1011
|
+
}
|
|
1012
|
+
/** The source told a plugin of a change: its changes are asked for now. */
|
|
1013
|
+
export async function pluginMountChanged(plugin, id) {
|
|
1014
|
+
const mount = await db.query.spaceMount.findFirst({
|
|
1015
|
+
where: and(eq(schema.spaceMount.id, id), eq(schema.spaceMount.plugin, plugin)),
|
|
1016
|
+
});
|
|
1017
|
+
if (!mount) {
|
|
1018
|
+
throw notFound();
|
|
1019
|
+
}
|
|
1020
|
+
queue(currentTenant(), mount.id, "changes");
|
|
1021
|
+
}
|
|
1022
|
+
/** Who sees a mount, which wizards may use it and what an AI may do, as its rules say. */
|
|
1023
|
+
export async function mountAccess(spaceId, mountId) {
|
|
1024
|
+
const rules = await db.query.rwxRule.findMany({
|
|
1025
|
+
where: and(eq(schema.rwxRule.spaceId, spaceId), eq(schema.rwxRule.resourceKind, "mount"), eq(schema.rwxRule.resourceId, mountId)),
|
|
1026
|
+
});
|
|
1027
|
+
const allowed = rules.filter((r) => r.r === "allow");
|
|
1028
|
+
const wizards = allowed.filter((r) => r.subjectKind === "wizard").map((r) => r.subjectId ?? "");
|
|
1029
|
+
return {
|
|
1030
|
+
see: AUDIENCES.filter((a) => allowed.some((r) => a === "guests"
|
|
1031
|
+
? r.subjectKind === "guest"
|
|
1032
|
+
: r.subjectKind === "role" && r.subjectId === (a === "team" ? "member" : "client"))),
|
|
1033
|
+
wizards: wizards.includes("*") ? "all" : wizards.length ? wizards : "none",
|
|
1034
|
+
agents: (() => {
|
|
1035
|
+
const agent = allowed.find((r) => r.subjectKind === "agent");
|
|
1036
|
+
return !agent ? "none" : agent.w === "allow" ? "drafts" : "read";
|
|
1037
|
+
})(),
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
export async function updateMount(userId, spaceId, mountId, who, patch) {
|
|
1041
|
+
requireAdmin();
|
|
1042
|
+
const mount = await mountRow(spaceId, mountId, who);
|
|
1043
|
+
const writable = patch.writable ?? mount.writable;
|
|
1044
|
+
if (writable && !mount.writable && !(await mountCanWrite(mount))) {
|
|
1045
|
+
throw new ServiceError("refused", NO_WRITE_RIGHTS);
|
|
1046
|
+
}
|
|
1047
|
+
if (patch.name?.trim() || writable !== mount.writable) {
|
|
1048
|
+
await db
|
|
1049
|
+
.update(schema.spaceMount)
|
|
1050
|
+
.set({ name: patch.name?.trim() || mount.name, writable, updatedAt: new Date() })
|
|
1051
|
+
.where(eq(schema.spaceMount.id, mount.id));
|
|
1052
|
+
}
|
|
1053
|
+
if (patch.see || patch.wizards || patch.agents || writable !== mount.writable) {
|
|
1054
|
+
const now = await mountAccess(spaceId, mount.id);
|
|
1055
|
+
await writeRules(spaceId, mount.id, mountRules(mount.id, {
|
|
1056
|
+
see: patch.see ?? now.see,
|
|
1057
|
+
wizards: patch.wizards ?? now.wizards,
|
|
1058
|
+
agents: patch.agents ?? now.agents,
|
|
1059
|
+
writable,
|
|
1060
|
+
}), userId);
|
|
1061
|
+
}
|
|
1062
|
+
return (await viewOf([
|
|
1063
|
+
(await db.query.spaceMount.findFirst({
|
|
1064
|
+
where: eq(schema.spaceMount.id, mount.id),
|
|
1065
|
+
})),
|
|
1066
|
+
]))[0];
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* A file written to its source from here („Veröffentlichen“): its row takes the entry the source
|
|
1070
|
+
* gave back, and it is read again for the index. The watcher's turn after it finds nothing new.
|
|
1071
|
+
*/
|
|
1072
|
+
export async function writtenAtSource(fileId, entry) {
|
|
1073
|
+
await db
|
|
1074
|
+
.update(schema.spaceMountFile)
|
|
1075
|
+
.set({ size: entry.size, modified: entry.modified, status: "pending", updatedAt: new Date() })
|
|
1076
|
+
.where(eq(schema.spaceMountFile.id, fileId));
|
|
1077
|
+
kick(currentTenant());
|
|
1078
|
+
}
|
|
1079
|
+
/** Lists a mount's tree again now: "Neu einlesen". */
|
|
1080
|
+
export async function rescanMount(spaceId, mountId, who) {
|
|
1081
|
+
const mount = await mountRow(spaceId, mountId, who);
|
|
1082
|
+
await watchMount(mount).catch(() => undefined);
|
|
1083
|
+
queue(currentTenant(), mount.id, "scan");
|
|
1084
|
+
}
|
|
1085
|
+
/** Takes a mount out of the space: its rows, index, thumbnails and rules. The files stay. */
|
|
1086
|
+
export async function deleteMount(spaceId, mountId) {
|
|
1087
|
+
await requireDateien();
|
|
1088
|
+
requireAdmin();
|
|
1089
|
+
const mount = await db.query.spaceMount.findFirst({
|
|
1090
|
+
where: and(eq(schema.spaceMount.id, mountId), eq(schema.spaceMount.spaceId, spaceId)),
|
|
1091
|
+
});
|
|
1092
|
+
if (!mount) {
|
|
1093
|
+
throw notFound();
|
|
1094
|
+
}
|
|
1095
|
+
closeMount(mount.id);
|
|
1096
|
+
await writeRules(spaceId, mount.id, [], "");
|
|
1097
|
+
await db.delete(schema.spaceMount).where(eq(schema.spaceMount.id, mount.id));
|
|
1098
|
+
await objects.removePrefix(`derived/m/${mount.id}/`);
|
|
1099
|
+
}
|
|
1100
|
+
const fileView = (f, categories = []) => ({
|
|
1101
|
+
id: f.id,
|
|
1102
|
+
path: f.path,
|
|
1103
|
+
name: f.name,
|
|
1104
|
+
mime: f.mime,
|
|
1105
|
+
size: f.size,
|
|
1106
|
+
modified: f.modified,
|
|
1107
|
+
status: f.status,
|
|
1108
|
+
thumb: f.thumb,
|
|
1109
|
+
pages: f.pages,
|
|
1110
|
+
title: f.title,
|
|
1111
|
+
categories,
|
|
1112
|
+
});
|
|
1113
|
+
/** Every file of a mount, by path: the studio draws the tree from the paths. */
|
|
1114
|
+
export async function mountFiles(spaceId, mountId, who) {
|
|
1115
|
+
const mount = await mountRow(spaceId, mountId, who);
|
|
1116
|
+
const files = await db.query.spaceMountFile.findMany({
|
|
1117
|
+
where: eq(schema.spaceMountFile.mountId, mount.id),
|
|
1118
|
+
orderBy: [asc(schema.spaceMountFile.path)],
|
|
1119
|
+
});
|
|
1120
|
+
const categories = await itemCategoriesOf(files.map((f) => ({ mountFileId: f.id })));
|
|
1121
|
+
return files.map((f) => fileView(f, categories.get(`m:${f.id}`)));
|
|
1122
|
+
}
|
|
1123
|
+
/** A file of a mount `who` may see. */
|
|
1124
|
+
export async function mountFile(spaceId, fileId, who) {
|
|
1125
|
+
await requireDateien();
|
|
1126
|
+
const file = await db.query.spaceMountFile.findFirst({
|
|
1127
|
+
where: and(eq(schema.spaceMountFile.id, fileId), eq(schema.spaceMountFile.spaceId, spaceId)),
|
|
1128
|
+
});
|
|
1129
|
+
if (!file) {
|
|
1130
|
+
throw notFound();
|
|
1131
|
+
}
|
|
1132
|
+
const mount = await mountRow(spaceId, file.mountId, who);
|
|
1133
|
+
return { mount, file };
|
|
1134
|
+
}
|
|
1135
|
+
/** One file of a mount, with the mount it lives in: what a search hit (`m:<id>`) opens. */
|
|
1136
|
+
export async function mountFileView(spaceId, fileId, who) {
|
|
1137
|
+
const { mount, file } = await mountFile(spaceId, fileId, who);
|
|
1138
|
+
const categories = await itemCategoriesOf([{ mountFileId: file.id }]);
|
|
1139
|
+
return { ...fileView(file, categories.get(`m:${file.id}`)), mountId: mount.id };
|
|
1140
|
+
}
|
|
1141
|
+
/** The file's bytes, read from where it lives: nothing of them is kept. */
|
|
1142
|
+
export async function mountFileContent(spaceId, fileId, who) {
|
|
1143
|
+
const { mount, file } = await mountFile(spaceId, fileId, who);
|
|
1144
|
+
const reader = await readerOf(mount);
|
|
1145
|
+
const data = await reader.read(file.path, idOf(file)).catch(() => {
|
|
1146
|
+
throw new ServiceError("not_found", `"${file.path}" is not in the folder any more.`);
|
|
1147
|
+
});
|
|
1148
|
+
return { file, data };
|
|
1149
|
+
}
|
|
1150
|
+
export async function mountFileThumb(spaceId, fileId, who) {
|
|
1151
|
+
const { mount, file } = await mountFile(spaceId, fileId, who);
|
|
1152
|
+
return file.thumb ? objects.get(thumbKey(mount.id, file.id)) : null;
|
|
1153
|
+
}
|
|
1154
|
+
/** A mounted file's text, read from the original through the cache; empty for a picture. */
|
|
1155
|
+
export async function mountFileText(mount, file) {
|
|
1156
|
+
if (!hasText(file)) {
|
|
1157
|
+
return "";
|
|
1158
|
+
}
|
|
1159
|
+
const data = await (await readerOf(mount)).read(file.path, idOf(file));
|
|
1160
|
+
const hash = createHash("sha256").update(data).digest("hex");
|
|
1161
|
+
return (await textOf(file, hash, data))?.markdown ?? "";
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* The text of units found by a search, for snippets and the classifier: from the cache, else the
|
|
1165
|
+
* original read again. Empty where the source is away.
|
|
1166
|
+
*/
|
|
1167
|
+
export async function unitTexts(units) {
|
|
1168
|
+
const fileIds = [...new Set(units.map((x) => x.fileId))];
|
|
1169
|
+
const files = fileIds.length
|
|
1170
|
+
? await db.query.spaceMountFile.findMany({
|
|
1171
|
+
where: inArray(schema.spaceMountFile.id, fileIds),
|
|
1172
|
+
})
|
|
1173
|
+
: [];
|
|
1174
|
+
const mounts = files.length
|
|
1175
|
+
? await db.query.spaceMount.findMany({
|
|
1176
|
+
where: inArray(schema.spaceMount.id, [...new Set(files.map((f) => f.mountId))]),
|
|
1177
|
+
})
|
|
1178
|
+
: [];
|
|
1179
|
+
const texts = new Map();
|
|
1180
|
+
for (const file of files) {
|
|
1181
|
+
const mount = mounts.find((m) => m.id === file.mountId);
|
|
1182
|
+
texts.set(file.id, await textForVectors(mount, file).catch(() => ""));
|
|
1183
|
+
}
|
|
1184
|
+
return units.map((x) => {
|
|
1185
|
+
const file = files.find((f) => f.id === x.fileId);
|
|
1186
|
+
if (!file) {
|
|
1187
|
+
return "";
|
|
1188
|
+
}
|
|
1189
|
+
return x.start === null || x.end === null
|
|
1190
|
+
? pathWords(file.path)
|
|
1191
|
+
: unitText(texts.get(file.id) ?? "", x);
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
/** The mounts of a space a caller may use: ids with their name and slug. */
|
|
1195
|
+
export async function usableMounts(spaceId, who) {
|
|
1196
|
+
if (!(await dateienOn())) {
|
|
1197
|
+
return [];
|
|
1198
|
+
}
|
|
1199
|
+
const mounts = await db.query.spaceMount.findMany({
|
|
1200
|
+
where: eq(schema.spaceMount.spaceId, spaceId),
|
|
1201
|
+
columns: { id: true, name: true, slug: true },
|
|
1202
|
+
});
|
|
1203
|
+
const ok = await readableMounts(spaceId, who, mounts.map((m) => m.id));
|
|
1204
|
+
return mounts.filter((m) => ok.has(m.id));
|
|
1205
|
+
}
|
|
1206
|
+
/** A mounted file by its path for a wizard: `dateien/<mount>/<path>`, among the mounts it may use. */
|
|
1207
|
+
export async function fileByPath(spaceId, path, who) {
|
|
1208
|
+
const [, slug, ...rest] = path.replace(/^\/+/, "").split("/");
|
|
1209
|
+
const mount = (await usableMounts(spaceId, who)).find((m) => m.slug === slug);
|
|
1210
|
+
if (!mount) {
|
|
1211
|
+
return null;
|
|
1212
|
+
}
|
|
1213
|
+
const file = await db.query.spaceMountFile.findFirst({
|
|
1214
|
+
where: and(eq(schema.spaceMountFile.mountId, mount.id), eq(schema.spaceMountFile.path, rest.join("/"))),
|
|
1215
|
+
});
|
|
1216
|
+
const row = await db.query.spaceMount.findFirst({ where: eq(schema.spaceMount.id, mount.id) });
|
|
1217
|
+
return file && row ? { mount: row, file } : null;
|
|
1218
|
+
}
|
|
1219
|
+
// --- choosing a folder ----------------------------------------------------------------------
|
|
1220
|
+
/**
|
|
1221
|
+
* The system's folder dialog, where this computer has one: macOS `choose folder`, Windows'
|
|
1222
|
+
* FolderBrowserDialog, Linux `zenity`. Null when the person cancelled; `false` where there is no
|
|
1223
|
+
* dialog (the studio asks for a path instead).
|
|
1224
|
+
*/
|
|
1225
|
+
export async function pickFolder(prompt) {
|
|
1226
|
+
await requireFolders();
|
|
1227
|
+
const run = (cmd, args) => new Promise((done) => {
|
|
1228
|
+
execFile(cmd, args, { timeout: 10 * 60_000 }, (err, stdout) => {
|
|
1229
|
+
if (err) {
|
|
1230
|
+
// ENOENT: no such program. Else the person cancelled.
|
|
1231
|
+
done(err.code === "ENOENT" ? false : null);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
done(stdout.trim().replace(/\/$/, "") || null);
|
|
1235
|
+
});
|
|
1236
|
+
});
|
|
1237
|
+
switch (platform()) {
|
|
1238
|
+
case "darwin":
|
|
1239
|
+
return run("osascript", [
|
|
1240
|
+
"-e",
|
|
1241
|
+
`tell application (path to frontmost application as text) to POSIX path of (choose folder with prompt ${JSON.stringify(prompt)})`,
|
|
1242
|
+
]);
|
|
1243
|
+
case "win32":
|
|
1244
|
+
return run("powershell.exe", [
|
|
1245
|
+
"-NoProfile",
|
|
1246
|
+
"-STA",
|
|
1247
|
+
"-Command",
|
|
1248
|
+
`Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = ${JSON.stringify(prompt)}; if ($d.ShowDialog() -eq 'OK') { $d.SelectedPath }`,
|
|
1249
|
+
]);
|
|
1250
|
+
default:
|
|
1251
|
+
return process.env.DISPLAY || process.env.WAYLAND_DISPLAY
|
|
1252
|
+
? run("zenity", ["--file-selection", "--directory", `--title=${prompt}`])
|
|
1253
|
+
: false;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
/** Folders whose path starts with `typed`, for the path field. */
|
|
1257
|
+
export async function completeFolder(typed) {
|
|
1258
|
+
await requireFolders();
|
|
1259
|
+
const full = typed.replace(/^~(?=$|\/)/, homedir()) || homedir();
|
|
1260
|
+
const [dir, start] = full.endsWith("/") ? [full, ""] : [dirname(full), basename(full)];
|
|
1261
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
1262
|
+
return entries
|
|
1263
|
+
.filter((e) => e.isDirectory() && !leftOut(e.name) && e.name.toLowerCase().startsWith(start.toLowerCase()))
|
|
1264
|
+
.map((e) => join(dir, e.name))
|
|
1265
|
+
.slice(0, 20);
|
|
1266
|
+
}
|
|
1267
|
+
/** What a folder holds, before it is mounted: counts, its folders of the first level, what is left out. */
|
|
1268
|
+
export async function previewFolder(path) {
|
|
1269
|
+
await requireFolders();
|
|
1270
|
+
const root = resolve(path.replace(/^~(?=$|\/)/, homedir()));
|
|
1271
|
+
if (!(await stat(root).catch(() => null))?.isDirectory()) {
|
|
1272
|
+
throw new ServiceError("invalid", `There is no folder "${path}".`);
|
|
1273
|
+
}
|
|
1274
|
+
const reader = new FolderReader(root);
|
|
1275
|
+
let files = 0;
|
|
1276
|
+
let bytes = 0;
|
|
1277
|
+
const folders = new Set();
|
|
1278
|
+
const first = new Map();
|
|
1279
|
+
let top = 0;
|
|
1280
|
+
const signal = AbortSignal.timeout(20_000);
|
|
1281
|
+
try {
|
|
1282
|
+
for await (const entry of reader.list("", { signal })) {
|
|
1283
|
+
files++;
|
|
1284
|
+
bytes += entry.size;
|
|
1285
|
+
const parts = entry.path.split("/");
|
|
1286
|
+
for (let i = 1; i < parts.length; i++) {
|
|
1287
|
+
folders.add(parts.slice(0, i).join("/"));
|
|
1288
|
+
}
|
|
1289
|
+
if (parts.length > 1) {
|
|
1290
|
+
first.set(parts[0], (first.get(parts[0]) ?? 0) + 1);
|
|
1291
|
+
}
|
|
1292
|
+
else {
|
|
1293
|
+
top++;
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
catch {
|
|
1298
|
+
// A tree too large to count in time: what was counted, said as "at least".
|
|
1299
|
+
}
|
|
1300
|
+
// What the listing leaves out at the top, said in the review.
|
|
1301
|
+
const all = await readdir(root).catch(() => []);
|
|
1302
|
+
return {
|
|
1303
|
+
path: root,
|
|
1304
|
+
name: basename(root),
|
|
1305
|
+
files,
|
|
1306
|
+
folders: folders.size,
|
|
1307
|
+
bytes,
|
|
1308
|
+
complete: !signal.aborted,
|
|
1309
|
+
top,
|
|
1310
|
+
first: [...first]
|
|
1311
|
+
.map(([name, count]) => ({ name, files: count }))
|
|
1312
|
+
.sort((a, b) => a.name.localeCompare(b.name, "de")),
|
|
1313
|
+
leftOut: all.filter(leftOut).length,
|
|
1314
|
+
};
|
|
1315
|
+
}
|