topotopo 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +10 -10
- package/README.md +460 -117
- package/dist/cli.js +327 -147
- package/dist/config.d.ts +48 -0
- package/dist/config.js +170 -0
- package/dist/core/bake.d.ts +14 -3
- package/dist/core/bake.js +153 -4
- package/dist/core/bevel.d.ts +3 -1
- package/dist/core/bevel.js +76 -3
- package/dist/core/decimate.d.ts +65 -0
- package/dist/core/decimate.js +409 -3
- package/dist/core/erosion.d.ts +37 -0
- package/dist/core/erosion.js +41 -1
- package/dist/core/geometry.d.ts +5 -1
- package/dist/core/geometry.js +203 -3
- package/dist/core/heightfield.d.ts +27 -4
- package/dist/core/heightfield.js +54 -16
- package/dist/core/intrinsics.d.ts +7 -0
- package/dist/core/intrinsics.js +94 -0
- package/dist/core/manifold.d.ts +12 -1
- package/dist/core/manifold.js +78 -6
- package/dist/core/materials.d.ts +7 -0
- package/dist/core/materials.js +45 -0
- package/dist/core/noise.d.ts +9 -0
- package/dist/core/noise.js +10 -1
- package/dist/core/polymerge.d.ts +21 -0
- package/dist/core/polymerge.js +327 -0
- package/dist/core/repair.d.ts +2 -0
- package/dist/core/repair.js +2 -0
- package/dist/core/report.d.ts +70 -0
- package/dist/core/report.js +275 -0
- package/dist/core/scene.js +2 -1
- package/dist/core/sha256.d.ts +4 -0
- package/dist/core/sha256.js +69 -0
- package/dist/core/shapes.d.ts +3 -0
- package/dist/core/shapes.js +34 -0
- package/dist/core/snippet-lib.d.ts +14 -1
- package/dist/core/snippet-lib.js +39 -13
- package/dist/core/tangents.d.ts +2 -0
- package/dist/core/tangents.js +5 -1
- package/dist/core/texnoise.d.ts +6 -1
- package/dist/core/texnoise.js +6 -2
- package/dist/core/texsdf.d.ts +131 -0
- package/dist/core/texsdf.js +637 -0
- package/dist/core/texture.d.ts +163 -9
- package/dist/core/texture.js +844 -20
- package/dist/core/topology.d.ts +10 -0
- package/dist/core/topology.js +168 -0
- package/dist/core/unwrap.d.ts +72 -0
- package/dist/core/unwrap.js +800 -0
- package/dist/core/usercode.d.ts +27 -0
- package/dist/core/usercode.js +87 -0
- package/dist/core/uv.d.ts +4 -18
- package/dist/core/uv.js +35 -188
- package/dist/core/uvislands.d.ts +62 -0
- package/dist/core/uvislands.js +574 -0
- package/dist/core/uvoverlap.d.ts +58 -0
- package/dist/core/uvoverlap.js +220 -0
- package/dist/core/uvpack.d.ts +64 -0
- package/dist/core/uvpack.js +628 -0
- package/dist/core/uvreport.d.ts +61 -0
- package/dist/core/uvreport.js +207 -143
- package/dist/core/wrangle.d.ts +6 -1
- package/dist/core/wrangle.js +27 -16
- package/dist/core/xatlas.d.ts +16 -1
- package/dist/core/xatlas.js +66 -62
- package/dist/engines.d.ts +63 -0
- package/dist/engines.js +180 -0
- package/dist/explain.d.ts +4 -3
- package/dist/explain.js +129 -12
- package/dist/graph/engine.d.ts +92 -29
- package/dist/graph/engine.js +298 -148
- package/dist/graph/expr.d.ts +6 -3
- package/dist/graph/expr.js +18 -8
- package/dist/graph/outputs.d.ts +23 -0
- package/dist/graph/outputs.js +41 -0
- package/dist/graph/packages.d.ts +72 -0
- package/dist/graph/packages.js +261 -0
- package/dist/graph/parallel.d.ts +3 -1
- package/dist/graph/parallel.js +4 -1
- package/dist/graph/params.d.ts +6 -0
- package/dist/graph/params.js +34 -7
- package/dist/graph/scope.d.ts +55 -0
- package/dist/graph/scope.js +14 -0
- package/dist/graph/types.d.ts +75 -12
- package/dist/graph/types.js +4 -2
- package/dist/graph/vars.d.ts +16 -0
- package/dist/graph/vars.js +80 -0
- package/dist/host/artifacts.d.ts +10 -1
- package/dist/host/artifacts.js +37 -6
- package/dist/host/cook.d.ts +241 -0
- package/dist/host/cook.js +844 -0
- package/dist/host/export-targets.d.ts +42 -5
- package/dist/host/export-targets.js +72 -13
- package/dist/host/godot-commands.d.ts +4 -0
- package/dist/host/godot-commands.js +21 -0
- package/dist/host/godot.d.ts +183 -0
- package/dist/host/godot.js +916 -0
- package/dist/host/node.d.ts +12 -7
- package/dist/host/node.js +27 -9
- package/dist/host/pool.js +51 -2
- package/dist/host/sidecars.d.ts +8 -0
- package/dist/host/sidecars.js +50 -0
- package/dist/host/types.d.ts +19 -6
- package/dist/host/version.d.ts +1 -0
- package/dist/host/version.js +3 -0
- package/dist/host/worker.js +5 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/inspect.d.ts +80 -2
- package/dist/inspect.js +265 -30
- package/dist/io/common.d.ts +25 -5
- package/dist/io/export.js +2 -1
- package/dist/io/files.d.ts +23 -4
- package/dist/io/files.js +60 -8
- package/dist/io/gltf.js +134 -47
- package/dist/io/heightmap.d.ts +3 -0
- package/dist/io/heightmap.js +1 -0
- package/dist/io/import.js +10 -0
- package/dist/io/inspect-scene.d.ts +55 -0
- package/dist/io/inspect-scene.js +155 -0
- package/dist/io/kinds.d.ts +81 -0
- package/dist/io/kinds.js +163 -0
- package/dist/io/points.d.ts +2 -1
- package/dist/io/points.js +3 -1
- package/dist/io/sidecars.d.ts +24 -0
- package/dist/io/sidecars.js +57 -0
- package/dist/io/source.d.ts +65 -0
- package/dist/io/source.js +112 -0
- package/dist/io/targets.d.ts +47 -3
- package/dist/io/targets.js +148 -13
- package/dist/io/textures.js +21 -1
- package/dist/io/unreal.js +5 -1
- package/dist/mcp/docs.d.ts +10 -1
- package/dist/mcp/docs.js +786 -143
- package/dist/mcp/inputs.d.ts +12 -5
- package/dist/mcp/inputs.js +50 -13
- package/dist/mcp/server.js +56 -27
- package/dist/mcp/tools.d.ts +14 -7
- package/dist/mcp/tools.js +198 -103
- package/dist/mcp/verify.d.ts +2 -2
- package/dist/mcp/verify.js +1 -1
- package/dist/mcp/workspace.d.ts +15 -0
- package/dist/mcp/workspace.js +349 -0
- package/dist/nodes/attributes.js +198 -1
- package/dist/nodes/bake.js +151 -47
- package/dist/nodes/beam.d.ts +1 -0
- package/dist/nodes/beam.js +201 -0
- package/dist/nodes/bevel.js +51 -3
- package/dist/nodes/cloth.js +2 -0
- package/dist/nodes/code.js +21 -9
- package/dist/nodes/curves.js +433 -93
- package/dist/nodes/flow.js +53 -33
- package/dist/nodes/generate.js +12 -38
- package/dist/nodes/heightfield.js +248 -77
- package/dist/nodes/imageops.js +16 -19
- package/dist/nodes/index.d.ts +1 -0
- package/dist/nodes/index.js +1 -0
- package/dist/nodes/material.js +89 -24
- package/dist/nodes/measure.js +43 -17
- package/dist/nodes/particles.js +2 -0
- package/dist/nodes/pcg.js +6 -5
- package/dist/nodes/procedural.js +4 -3
- package/dist/nodes/remesh.js +71 -15
- package/dist/nodes/scene.js +4 -2
- package/dist/nodes/sdf.js +10 -5
- package/dist/nodes/solid.js +20 -5
- package/dist/nodes/splines.d.ts +15 -1
- package/dist/nodes/splines.js +112 -105
- package/dist/nodes/texture.d.ts +21 -6
- package/dist/nodes/texture.js +1318 -185
- package/dist/nodes/topology.d.ts +7 -0
- package/dist/nodes/topology.js +133 -6
- package/dist/nodes/transform.js +6 -2
- package/dist/nodes/uv.js +192 -174
- package/dist/nodes/wasmcall.js +5 -1
- package/dist/open.d.ts +19 -0
- package/dist/open.js +12 -0
- package/dist/package.d.ts +288 -0
- package/dist/package.js +772 -0
- package/dist/packages/check.d.ts +32 -0
- package/dist/packages/check.js +169 -0
- package/dist/packages/commands.d.ts +57 -0
- package/dist/packages/commands.js +537 -0
- package/dist/packages/registry.d.ts +796 -0
- package/dist/packages/registry.js +2998 -0
- package/dist/packages/update.d.ts +124 -0
- package/dist/packages/update.js +476 -0
- package/dist/render/options.d.ts +2 -0
- package/dist/render/options.js +57 -5
- package/dist/render/preview.d.ts +17 -4
- package/dist/render/preview.js +6 -4
- package/dist/render/raster.d.ts +74 -5
- package/dist/render/raster.js +527 -143
- package/dist/render/texview.d.ts +6 -0
- package/dist/render/texview.js +27 -0
- package/dist/scan.d.ts +61 -0
- package/dist/scan.js +228 -0
- package/dist/session.d.ts +311 -0
- package/dist/session.js +849 -0
- package/dist/viewer/app/api.js +48 -6
- package/dist/viewer/app/cooking.js +78 -0
- package/dist/viewer/app/embed.js +27 -7
- package/dist/viewer/app/export-popover.js +118 -16
- package/dist/viewer/app/grid.js +5 -1
- package/dist/viewer/app/guides.js +122 -0
- package/dist/viewer/app/keymap.js +6 -3
- package/dist/viewer/app/layers.js +4 -4
- package/dist/viewer/app/main.js +185 -52
- package/dist/viewer/app/markers.js +60 -0
- package/dist/viewer/app/outliner.js +72 -27
- package/dist/viewer/app/output-info.js +45 -0
- package/dist/viewer/app/outputs.css +147 -8
- package/dist/viewer/app/outputs.js +168 -54
- package/dist/viewer/app/packages.js +614 -0
- package/dist/viewer/app/props.js +176 -52
- package/dist/viewer/app/scene.js +30 -5
- package/dist/viewer/app/select.js +4 -3
- package/dist/viewer/app/status.js +12 -15
- package/dist/viewer/app/style.css +65 -7
- package/dist/viewer/app/vars.js +47 -0
- package/dist/viewer/app/welcome.js +72 -0
- package/dist/viewer/graph-file.d.ts +62 -0
- package/dist/viewer/graph-file.js +175 -0
- package/dist/viewer/index.html +23 -10
- package/dist/viewer/json-edit.d.ts +13 -0
- package/dist/viewer/json-edit.js +274 -0
- package/dist/viewer/outputs.d.ts +49 -5
- package/dist/viewer/outputs.js +264 -56
- package/dist/viewer/packages.d.ts +121 -0
- package/dist/viewer/packages.js +584 -0
- package/dist/viewer/server.d.ts +14 -9
- package/dist/viewer/server.js +266 -28
- package/dist/web/app/web.css +419 -0
- package/dist/web/app/web.js +188 -0
- package/dist/{gallery → web}/bake.d.ts +4 -4
- package/dist/{gallery → web}/bake.js +24 -15
- package/dist/web/folder-page.d.ts +101 -0
- package/dist/web/folder-page.js +146 -0
- package/dist/web/folders.d.ts +280 -0
- package/dist/web/folders.js +970 -0
- package/dist/web/library.d.ts +91 -0
- package/dist/web/library.js +228 -0
- package/dist/web/markdown.d.ts +45 -0
- package/dist/web/markdown.js +677 -0
- package/dist/web/pages.d.ts +258 -0
- package/dist/web/pages.js +301 -0
- package/dist/web/server.d.ts +24 -0
- package/dist/web/server.js +1068 -0
- package/dist/workspace.d.ts +88 -118
- package/dist/workspace.js +358 -460
- package/integrations/godot/addons/topotopo/LICENSE +202 -0
- package/integrations/godot/addons/topotopo/README.md +57 -0
- package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
- package/integrations/godot/addons/topotopo/dock.gd +266 -0
- package/integrations/godot/addons/topotopo/dock.tscn +72 -0
- package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
- package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
- package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
- package/integrations/godot/addons/topotopo/inspector.gd +38 -0
- package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
- package/integrations/godot/addons/topotopo/package.gd +23 -0
- package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
- package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
- package/integrations/godot/addons/topotopo/plugin.gd +970 -0
- package/integrations/godot/addons/topotopo/record.gd +435 -0
- package/integrations/godot/addons/topotopo/runner.gd +458 -0
- package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
- package/integrations/godot/addons/topotopo/watcher.gd +199 -0
- package/kernels/pkg/README.md +2 -1
- package/kernels/pkg-simd/README.md +2 -1
- package/library/architecture/versions/1.0/architecture.topo +12 -0
- package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
- package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
- package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
- package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
- package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
- package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
- package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
- package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
- package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
- package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
- package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
- package/library/architecture/versions/1.0/version.json +1119 -0
- package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
- package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
- package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
- package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
- package/library/nature/versions/1.0/graphs/lineup.json +24 -0
- package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
- package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
- package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
- package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
- package/library/nature/versions/1.0/nature.topo +12 -0
- package/library/nature/versions/1.0/version.json +534 -0
- package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
- package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
- package/library/props/versions/1.0/graphs/lineup.json +18 -0
- package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
- package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
- package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
- package/library/props/versions/1.0/props.topo +12 -0
- package/library/props/versions/1.0/version.json +336 -0
- package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
- package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
- package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
- package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
- package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
- package/library/street/versions/1.0/graphs/lineup.json +22 -0
- package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
- package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
- package/library/street/versions/1.0/street.topo +12 -0
- package/library/street/versions/1.0/version.json +421 -0
- package/package.json +13 -8
- package/dist/gallery/app/gallery.css +0 -100
- package/dist/gallery/app/gallery.js +0 -80
- package/dist/gallery/cli.d.ts +0 -4
- package/dist/gallery/cli.js +0 -157
- package/dist/gallery/library.d.ts +0 -124
- package/dist/gallery/library.js +0 -366
- package/dist/gallery/pages.d.ts +0 -94
- package/dist/gallery/pages.js +0 -148
- package/dist/gallery/server.d.ts +0 -21
- package/dist/gallery/server.js +0 -391
- package/dist/graph/migrate.d.ts +0 -23
- package/dist/graph/migrate.js +0 -58
- package/dist/mcp/library.d.ts +0 -12
- package/dist/mcp/library.js +0 -159
- package/shelf/index.json +0 -190
|
@@ -0,0 +1,2998 @@
|
|
|
1
|
+
// Packages on disk (the engine side is src/graph/packages.ts): the copies of the package versions a package uses and
|
|
2
|
+
// their lock, the places a package finds packages in, adding a package on first use, following a package's working
|
|
3
|
+
// folder for one session, publishing a version (with the kind, tags and description of each output, and a dry run),
|
|
4
|
+
// the newer versions of what a package uses and updating to one (the before/after is src/packages/update.ts), and
|
|
5
|
+
// searching the outputs of every place.
|
|
6
|
+
//
|
|
7
|
+
// <package>/<id>.topo "name": "studio/trees" (set by the author), "uses"
|
|
8
|
+
// <package>/versions/1.3/ a published version, never written over: <id>.topo, graphs/,
|
|
9
|
+
// assets/, inputs/, packages/ (the copies it uses and their lock) and
|
|
10
|
+
// version.json (note, hash, interface)
|
|
11
|
+
// <package>/packages/<owner>/<name>/<version>/ the package's copy of a version it uses, or of one those use: flat,
|
|
12
|
+
// each version once (in a workspace: topotopo-packages/ beside
|
|
13
|
+
// topotopo-workspace.json, one copy for every package in it)
|
|
14
|
+
// <package>/packages/lock.json every copied version: its hash, where it came from (a path from the
|
|
15
|
+
// folder of the copies, or a registered library's name) and its uses
|
|
16
|
+
//
|
|
17
|
+
// A copy holds the files of the version but the copies the version holds itself, which sit flat beside it; it keeps the
|
|
18
|
+
// version's lock. A version's hash covers every file of the version but version.json: the sorted posix paths, each with
|
|
19
|
+
// the SHA-256 of the file's content ("<sha256> <path>" lines, hashed again). A text file's content is read with LF line
|
|
20
|
+
// ends, so a checkout that turns them into CRLF (core.autocrlf on Windows) keeps every hash; binary files are hashed as
|
|
21
|
+
// they are (textContent); files an engine writes beside them (*.import, *.uid, *.uasset …) are no part of it. A copy is
|
|
22
|
+
// checked against it together with the copies it uses as the package holds them, so a copy edited by hand shows.
|
|
23
|
+
//
|
|
24
|
+
// Where a package finds packages (package.ts librariesFor): in a workspace, the workspace itself (scanned), then the
|
|
25
|
+
// shared libraries its file lists, in order; outside one, the library the package is in (from its own checkout), then
|
|
26
|
+
// every other registered library; then TopoTopo's built-in library, which alone holds the packages named
|
|
27
|
+
// "topotopo/…". A name is taken from the first place that has it, the same name in a later place is not used (said);
|
|
28
|
+
// two folders of one place publishing one name leave the name out (said, naming both); a folder reached through two
|
|
29
|
+
// places counts once, in the first. Cooking needs only the copies.
|
|
30
|
+
//
|
|
31
|
+
// A package's graphs name its own outputs by full name, with no entry in its uses: in a version they resolve to that
|
|
32
|
+
// version, in a followed working folder to that folder, and in the package that publishes versions to its own graphs as
|
|
33
|
+
// they are now (its working folder, as following it would). Outputs that name each other in a loop do not resolve, and
|
|
34
|
+
// publishing refuses them.
|
|
35
|
+
//
|
|
36
|
+
// Update goes to the newest version with the same big number, or to a version named (a big one is named). Its
|
|
37
|
+
// before/after reads the new version where its place holds it, apart from the copies (a scope and results of its
|
|
38
|
+
// own), and copies nothing; applying copies it in, sets "uses" and the lock, and deletes the copies nothing uses any
|
|
39
|
+
// more: those the uses needed before and need no more.
|
|
40
|
+
import fs from 'node:fs';
|
|
41
|
+
import path from 'node:path';
|
|
42
|
+
import { createHash } from 'node:crypto';
|
|
43
|
+
import { graphInterface } from '../graph/engine.js';
|
|
44
|
+
import { KINDS, isKind, outputFieldIssues } from '../graph/outputs.js';
|
|
45
|
+
import { ownOutputsNamed, packageAt, packageOutputDef, packagesNamedIn, varsRead } from '../graph/packages.js';
|
|
46
|
+
import { didYouMean, resolveParamName } from '../graph/params.js';
|
|
47
|
+
import { getNodeDef } from '../graph/registry.js';
|
|
48
|
+
import { ID_RE, parsePackageName } from '../graph/scope.js';
|
|
49
|
+
import { TOPOTOPO_VERSION } from '../host/version.js';
|
|
50
|
+
import { kindMismatch, outputKind, publishedKind } from '../io/kinds.js';
|
|
51
|
+
import { readMaterials } from '../core/materials.js';
|
|
52
|
+
import { imageRef, referenceableImages } from '../core/image.js';
|
|
53
|
+
import { graphFiles, registerAssets } from '../session.js';
|
|
54
|
+
import { BUILTIN_LIBRARY, loadConfig } from '../config.js';
|
|
55
|
+
import { BUILTIN_TEXT, VERSION_RE, WORKSPACE_FILE, WORKSPACE_PACKAGES, copiesFor, isPackageName, locate, parseUses, librariesFor, libraryEntry, manifestAt, manifestFile, oldManifestAbove, placeText, program, packageDirOf, packageId, readManifest, readUses, renameInto, withStoreLock, within, workspaceFlag, writeAtomic, writeManifest, writeUses } from '../package.js';
|
|
56
|
+
import { folderKey, forgetScans, scanTree } from '../scan.js';
|
|
57
|
+
import { readWorkspace, scanWorkspace } from '../workspace.js';
|
|
58
|
+
import { godotIgnore, isEngineFile } from '../engines.js';
|
|
59
|
+
/** Publishing warns about a version above this size: every package that uses it keeps a copy. */
|
|
60
|
+
export const MAX_VERSION_BYTES = 50 * 2 ** 20;
|
|
61
|
+
/** The owner of TopoTopo's own packages: nobody else publishes under it. */
|
|
62
|
+
export const RESERVED_OWNER = 'topotopo';
|
|
63
|
+
/** How a folder becomes a package, said where only a package will do. */
|
|
64
|
+
const makePackage = () => `${program()} init <folder> (MCP: workspace {action:"init"} for the server's folder, when the person says so) makes the folder a package (<id>.topo)`;
|
|
65
|
+
/** A library as messages name it: library "game", and TopoTopo's built-in library by its name and what it is. */
|
|
66
|
+
export const libraryText = (name) => `library "${name}"${name === BUILTIN_LIBRARY.name ? ' (TopoTopo\'s built-in library)' : ''}`;
|
|
67
|
+
/** Is `o` the version's default output (the graph the manifest shows, at its output node)? */
|
|
68
|
+
export const isDefaultOutput = (v, o) => o.graph === v.default.graph && o.node === v.default.node;
|
|
69
|
+
/** The named output that is the default one too, or null when the default output is one of its own. */
|
|
70
|
+
export const defaultOutputName = (v) => Object.entries(v.outputs).find(([, o]) => isDefaultOutput(v, o))?.[0] ?? null;
|
|
71
|
+
// ------------------------------------------------------------------------------------------------------- versions
|
|
72
|
+
const versionParts = (v) => v.split('.').map(Number);
|
|
73
|
+
export const compareVersions = (a, b) => { const [x, y] = versionParts(a), [u, w] = versionParts(b); return x - u || y - w; };
|
|
74
|
+
/** A version that starts a big version: 2.0, 3.0, 10.0 (1.0 is the first one, 1.10 a small one). */
|
|
75
|
+
export const startsBigVersion = (v) => { const [big, small] = versionParts(v); return small === 0 && big > 1; };
|
|
76
|
+
const newestOf = (vs) => [...vs].sort(compareVersions).at(-1);
|
|
77
|
+
/** A package name "owner/name" (no output). */
|
|
78
|
+
function readVersionInfo(dir) {
|
|
79
|
+
const file = path.join(dir, 'version.json');
|
|
80
|
+
let raw;
|
|
81
|
+
try {
|
|
82
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
throw new Error(`${file}: ${e.message}`);
|
|
86
|
+
}
|
|
87
|
+
if (!raw || typeof raw !== 'object' || typeof raw.package !== 'string' || typeof raw.version !== 'string' || typeof raw.hash !== 'string' || !raw.outputs || typeof raw.outputs !== 'object' || !raw.default)
|
|
88
|
+
throw new Error(`${file} is not a version record: it needs package, version, hash, outputs and default`);
|
|
89
|
+
// every output records what it is: its kind and its tags
|
|
90
|
+
for (const [k, o] of [...Object.entries(raw.outputs), ['(the default output)', raw.default]])
|
|
91
|
+
if (!o || typeof o !== 'object' || !isKind(o.kind) || !Array.isArray(o.tags) || !o.sliders || !Array.isArray(o.inputs))
|
|
92
|
+
throw new Error(`${file} is not a version record: output ${k} needs its kind (${KINDS.join(', ')}), tags, sliders and inputs`);
|
|
93
|
+
return raw;
|
|
94
|
+
}
|
|
95
|
+
// ---------------------------------------------------------------------------------------------------------- files
|
|
96
|
+
const sha = (d) => createHash('sha256').update(d).digest('hex');
|
|
97
|
+
const byRel = (a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
|
|
98
|
+
const sortKeys = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
99
|
+
/** a copy's folder in a packages/ folder */
|
|
100
|
+
const copyAt = (packages, pkg, v) => path.join(packages, ...pkg.split('/'), v);
|
|
101
|
+
/** a version's own copies (not its lock), which a copy of it leaves out */
|
|
102
|
+
const nestedCopy = (rel) => rel.startsWith('packages/') && rel !== 'packages/lock.json';
|
|
103
|
+
/**
|
|
104
|
+
* What is said about a copy that is missing, and about one edited by hand (a loaded copy warns, publishing blocks).
|
|
105
|
+
* `direct`: the package in use that needs it (itself, or the one that uses it), whose `use` copies it again.
|
|
106
|
+
*/
|
|
107
|
+
const missingCopy = (pkg, v, at, direct) => `the copy of ${pkg} ${v} is missing: ${at}${direct ? `; restore it, or run ${program()} use ${direct}, which copies what is missing` : ''}`;
|
|
108
|
+
const editedCopy = (pkg, v, at, direct) => `the copy of ${pkg} ${v} (${at}) was edited by hand: its files no longer match the hash packages/lock.json records; restore it, or delete it and run ${program()} use ${direct ?? pkg}, which copies what is missing`;
|
|
109
|
+
/**
|
|
110
|
+
* Every file below `dir`, dot-files and dot-folders skipped, and the files an engine writes beside ours (*.import,
|
|
111
|
+
* *.uid, *.translation, *.uasset: isEngineFile): posix paths relative to it, sorted.
|
|
112
|
+
*/
|
|
113
|
+
function filesBelow(dir) {
|
|
114
|
+
const out = [];
|
|
115
|
+
const walk = (d, rel, depth) => {
|
|
116
|
+
let entries;
|
|
117
|
+
try {
|
|
118
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
for (const e of entries) {
|
|
124
|
+
if (e.name.startsWith('.') || (!e.isDirectory() && isEngineFile(e.name)))
|
|
125
|
+
continue;
|
|
126
|
+
const abs = path.join(d, e.name), r = rel ? `${rel}/${e.name}` : e.name;
|
|
127
|
+
let st;
|
|
128
|
+
try {
|
|
129
|
+
st = fs.statSync(abs);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (st.isDirectory()) {
|
|
135
|
+
if (depth < 32)
|
|
136
|
+
walk(abs, r, depth + 1);
|
|
137
|
+
} // the depth cap stops link cycles
|
|
138
|
+
else if (st.isFile())
|
|
139
|
+
out.push({ rel: r, abs });
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
walk(dir, '', 0);
|
|
143
|
+
return out.sort(byRel);
|
|
144
|
+
}
|
|
145
|
+
/** Files that are never text, whatever their bytes: images, meshes, fonts, archives. */
|
|
146
|
+
const BINARY = /\.(png|jpe?g|webp|gif|avif|bmp|tga|tiff?|exr|hdr|dds|ktx2?|glb|bin|bgeo|sc|usdc|usdz|fbx|abc|vdb|r16|r32|raw|wasm|ttf|otf|woff2?|zip|gz|7z|pdf|mp4|webm|wav|ogg|mp3)$/i;
|
|
147
|
+
/**
|
|
148
|
+
* A file's content as a version's hash reads it: a text file with its CRLF line ends read as LF, so that a checkout that
|
|
149
|
+
* turns LF into CRLF (core.autocrlf) keeps the hash; anything else as it is. Text is what version control takes for
|
|
150
|
+
* text: no NUL byte in the first 8000 bytes, and no binary format by its name.
|
|
151
|
+
*/
|
|
152
|
+
export function textContent(name, bytes) {
|
|
153
|
+
if (BINARY.test(name))
|
|
154
|
+
return bytes;
|
|
155
|
+
const head = Math.min(bytes.length, 8000);
|
|
156
|
+
for (let i = 0; i < head; i++)
|
|
157
|
+
if (bytes[i] === 0)
|
|
158
|
+
return bytes;
|
|
159
|
+
let crlf = 0;
|
|
160
|
+
for (let i = 0; i + 1 < bytes.length; i++)
|
|
161
|
+
if (bytes[i] === 13 && bytes[i + 1] === 10)
|
|
162
|
+
crlf++;
|
|
163
|
+
if (!crlf)
|
|
164
|
+
return bytes;
|
|
165
|
+
const out = new Uint8Array(bytes.length - crlf);
|
|
166
|
+
let j = 0;
|
|
167
|
+
for (let i = 0; i < bytes.length; i++)
|
|
168
|
+
if (!(bytes[i] === 13 && bytes[i + 1] === 10))
|
|
169
|
+
out[j++] = bytes[i];
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
/** The SHA-256 a version's hash takes of a file: of its text with LF line ends, or of its bytes (textContent). */
|
|
173
|
+
export const contentSha = (name, bytes) => sha(textContent(name, bytes));
|
|
174
|
+
/**
|
|
175
|
+
* SHA-256 of files kept while their size and time stay the same: copies and followed folders are read again often. A
|
|
176
|
+
* package keeps those of its own files between runs in packages/.cache.json (never committed: init lists it in its
|
|
177
|
+
* .gitignore), so a new process does not read every byte of its copies again.
|
|
178
|
+
*/
|
|
179
|
+
const shaCache = new Map();
|
|
180
|
+
let shaFresh = false;
|
|
181
|
+
function fileSha(abs, cached) {
|
|
182
|
+
if (!cached)
|
|
183
|
+
return contentSha(abs, fs.readFileSync(abs));
|
|
184
|
+
const st = fs.statSync(abs), stamp = `${st.size}:${st.mtimeMs}`;
|
|
185
|
+
const c = shaCache.get(abs);
|
|
186
|
+
if (c?.stamp === stamp)
|
|
187
|
+
return c.sha;
|
|
188
|
+
const h = contentSha(abs, fs.readFileSync(abs));
|
|
189
|
+
shaCache.set(abs, { stamp, sha: h });
|
|
190
|
+
shaFresh = true;
|
|
191
|
+
return h;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The file that keeps the hashes of a store's files between runs (.cache.json beside its copies; its paths are from
|
|
195
|
+
* the store's folder, the package's or the workspace's), and the shape it is written in.
|
|
196
|
+
*/
|
|
197
|
+
const shaCacheFile = (store) => path.join(store.packages, '.cache.json');
|
|
198
|
+
const SHA_CACHE_FORMAT = 1;
|
|
199
|
+
const shaCacheRead = new Set();
|
|
200
|
+
/** Take in the hashes a store kept (.cache.json), once per process. */
|
|
201
|
+
function readShaCache(store) {
|
|
202
|
+
const dir = store.root;
|
|
203
|
+
if (shaCacheRead.has(dir))
|
|
204
|
+
return;
|
|
205
|
+
shaCacheRead.add(dir);
|
|
206
|
+
let raw;
|
|
207
|
+
try {
|
|
208
|
+
raw = JSON.parse(fs.readFileSync(shaCacheFile(store), 'utf8'));
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (raw?.format !== SHA_CACHE_FORMAT || !raw.files || typeof raw.files !== 'object')
|
|
214
|
+
return;
|
|
215
|
+
for (const [rel, s] of Object.entries(raw.files)) {
|
|
216
|
+
const [stamp, h] = String(s).split(' ');
|
|
217
|
+
const abs = path.join(dir, ...rel.split('/'));
|
|
218
|
+
if (stamp && h && !shaCache.has(abs))
|
|
219
|
+
shaCache.set(abs, { stamp, sha: h });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** Keep the hashes of the store's files that are still there (.cache.json), when new ones were taken. */
|
|
223
|
+
function writeShaCache(store) {
|
|
224
|
+
const dir = store.root;
|
|
225
|
+
if (!shaFresh || !fs.existsSync(store.packages))
|
|
226
|
+
return;
|
|
227
|
+
shaFresh = false;
|
|
228
|
+
const files = {};
|
|
229
|
+
for (const [abs, c] of shaCache) {
|
|
230
|
+
const rel = path.relative(dir, abs);
|
|
231
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel) || !fs.existsSync(abs))
|
|
232
|
+
continue;
|
|
233
|
+
files[rel.split(path.sep).join('/')] = `${c.stamp} ${c.sha}`;
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
writeAtomic(shaCacheFile(store), JSON.stringify({ format: SHA_CACHE_FORMAT, files: sortKeys(files) }) + '\n');
|
|
237
|
+
}
|
|
238
|
+
catch { /* a cache: kept next time */ }
|
|
239
|
+
}
|
|
240
|
+
/** The hash of a set of files: their sorted posix paths, each with the SHA-256 of its content (contentSha). */
|
|
241
|
+
export function filesHash(files) {
|
|
242
|
+
return sha([...files].sort(byRel).map((f) => `${f.sha} ${f.rel}\n`).join(''));
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* The hash a version published from the package folder `dir` now would have, which tells whether a working folder
|
|
246
|
+
* differs from its versions (its files are re-read only when they change).
|
|
247
|
+
*/
|
|
248
|
+
export function workingHash(dir) {
|
|
249
|
+
const m = readManifest(dir), lock = readLock(dir);
|
|
250
|
+
return filesHash(versionFiles(dir, m, lock).map((f) => ({ rel: f.rel, sha: f.bytes ? contentSha(f.rel, f.bytes) : fileSha(f.abs, true) })));
|
|
251
|
+
}
|
|
252
|
+
/** The hash of a version folder as published: every file but its version.json. */
|
|
253
|
+
export function versionHash(dir, cached = false) {
|
|
254
|
+
return filesHash(filesBelow(dir).filter((f) => f.rel !== 'version.json').map((f) => ({ rel: f.rel, sha: fileSha(f.abs, cached) })));
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The hash of the version a copy holds: its own files (but version.json) with, under packages/, the copies its lock
|
|
258
|
+
* lists as the packages/ folder `packages` holds them.
|
|
259
|
+
*/
|
|
260
|
+
function copyHash(copy, packages) {
|
|
261
|
+
const files = filesBelow(copy).filter((f) => f.rel !== 'version.json').map((f) => ({ rel: f.rel, sha: fileSha(f.abs, true) }));
|
|
262
|
+
for (const [pkg, vs] of Object.entries(readLock(copy).packages))
|
|
263
|
+
for (const v of Object.keys(vs))
|
|
264
|
+
for (const f of filesBelow(copyAt(packages, pkg, v)))
|
|
265
|
+
files.push({ rel: `packages/${pkg}/${v}/${f.rel}`, sha: fileSha(f.abs, true) });
|
|
266
|
+
return filesHash(files);
|
|
267
|
+
}
|
|
268
|
+
/** Copy the files of `from` that `keep` keeps into a new folder `to`, through a .part folder renamed into place. */
|
|
269
|
+
function copyTree(from, to, keep = () => true) {
|
|
270
|
+
if (fs.existsSync(to))
|
|
271
|
+
throw new Error(`${to} is there already`);
|
|
272
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
273
|
+
const part = path.join(path.dirname(to), `.${path.basename(to)}.${process.pid}-${Date.now().toString(36)}.part`);
|
|
274
|
+
try {
|
|
275
|
+
for (const f of filesBelow(from)) {
|
|
276
|
+
if (!keep(f.rel))
|
|
277
|
+
continue;
|
|
278
|
+
const dest = path.join(part, ...f.rel.split('/'));
|
|
279
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
280
|
+
fs.copyFileSync(f.abs, dest);
|
|
281
|
+
}
|
|
282
|
+
fs.mkdirSync(part, { recursive: true });
|
|
283
|
+
renameInto(part, to);
|
|
284
|
+
}
|
|
285
|
+
catch (e) {
|
|
286
|
+
fs.rmSync(part, { recursive: true, force: true });
|
|
287
|
+
throw e;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// ----------------------------------------------------------------------------------------------------------- lock
|
|
291
|
+
export const lockFile = (dir) => path.join(dir, 'packages', 'lock.json');
|
|
292
|
+
/** A folder's packages/lock.json (empty when there is none); throws naming the file when it is not valid. */
|
|
293
|
+
export function readLock(dir) {
|
|
294
|
+
return readLockAt(path.join(dir, 'packages'));
|
|
295
|
+
}
|
|
296
|
+
/** The lock.json of a folder of copies (packages/, a workspace's topotopo-packages/). */
|
|
297
|
+
export function readLockAt(packages) {
|
|
298
|
+
const file = path.join(packages, 'lock.json');
|
|
299
|
+
if (!fs.existsSync(file))
|
|
300
|
+
return { packages: {} };
|
|
301
|
+
let raw;
|
|
302
|
+
try {
|
|
303
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
304
|
+
}
|
|
305
|
+
catch (e) {
|
|
306
|
+
throw new Error(`${file}: ${e.message}`);
|
|
307
|
+
}
|
|
308
|
+
const shape = `${file} must be {"packages": {"owner/name": {"1.3": {"hash", "library", "uses"}}}}`;
|
|
309
|
+
if (!raw || typeof raw !== 'object' || !raw.packages || typeof raw.packages !== 'object' || Array.isArray(raw.packages))
|
|
310
|
+
throw new Error(shape);
|
|
311
|
+
const out = { packages: {} };
|
|
312
|
+
for (const [pkg, vs] of Object.entries(raw.packages)) {
|
|
313
|
+
if (!isPackageName(pkg) || !vs || typeof vs !== 'object' || Array.isArray(vs))
|
|
314
|
+
throw new Error(shape);
|
|
315
|
+
for (const [v, e] of Object.entries(vs)) {
|
|
316
|
+
if (!VERSION_RE.test(v) || !e || typeof e.hash !== 'string' || typeof e.library !== 'string')
|
|
317
|
+
throw new Error(shape);
|
|
318
|
+
(out.packages[pkg] ??= {})[v] = { hash: e.hash, library: e.library, uses: parseUses(e.uses, `${file} ${pkg} ${v}`) };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
/** The lock as written: packages by name, versions by number. */
|
|
324
|
+
function lockText(lock) {
|
|
325
|
+
const packages = Object.fromEntries(Object.entries(sortKeys(lock.packages)).map(([pkg, vs]) => [pkg, Object.fromEntries(Object.keys(vs).sort(compareVersions).map((v) => [v, { hash: vs[v].hash, library: vs[v].library, uses: sortKeys(vs[v].uses) }]))]));
|
|
326
|
+
return JSON.stringify({ packages }, null, 2) + '\n';
|
|
327
|
+
}
|
|
328
|
+
function writeLockAt(packages, lock) {
|
|
329
|
+
fs.mkdirSync(packages, { recursive: true });
|
|
330
|
+
writeAtomic(path.join(packages, 'lock.json'), lockText(lock));
|
|
331
|
+
}
|
|
332
|
+
/** Every version `uses` needs through the lock (its uses, theirs …), sorted; throws for one the lock does not list. */
|
|
333
|
+
function usesClosure(uses, lock) {
|
|
334
|
+
const out = new Map();
|
|
335
|
+
// `top`: the package of `uses` that needs it, whose `use` copies and records what is missing
|
|
336
|
+
const visit = (pkg, v, by, top) => {
|
|
337
|
+
const key = `${pkg}@${v}`;
|
|
338
|
+
if (out.has(key))
|
|
339
|
+
return;
|
|
340
|
+
const e = lock.packages[pkg]?.[v];
|
|
341
|
+
if (!e)
|
|
342
|
+
throw new Error(`packages/lock.json does not list ${pkg} ${v} (${by} uses it): ${program()} use ${top} copies it and records it`);
|
|
343
|
+
out.set(key, [pkg, v]);
|
|
344
|
+
for (const [p, w] of Object.entries(e.uses))
|
|
345
|
+
visit(p, w, `${pkg} ${v}`, top);
|
|
346
|
+
};
|
|
347
|
+
for (const [pkg, v] of Object.entries(uses))
|
|
348
|
+
visit(pkg, v, 'the manifest', pkg);
|
|
349
|
+
return [...out.values()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : compareVersions(a[1], b[1])));
|
|
350
|
+
}
|
|
351
|
+
// -------------------------------------------------------------------------------------------- what a package holds
|
|
352
|
+
/** A package's graphs by name (graphs/ and the graph files beside its manifest); unreadable ones are problems. */
|
|
353
|
+
function readGraphs(dir, problems) {
|
|
354
|
+
const out = new Map();
|
|
355
|
+
for (const [name, file] of graphFiles(dir)) {
|
|
356
|
+
try {
|
|
357
|
+
out.set(name, JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
358
|
+
}
|
|
359
|
+
catch (e) {
|
|
360
|
+
problems.push(`${path.relative(dir, file).split(path.sep).join('/')}: ${e.message}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return out;
|
|
364
|
+
}
|
|
365
|
+
/** A graph's description, trimmed ('' without one). */
|
|
366
|
+
const describedAs = (g) => (typeof g.description === 'string' ? g.description.trim() : '');
|
|
367
|
+
/**
|
|
368
|
+
* What a package folder publishes: every named output of every graph in graphs/ but those marked "publish": false, and
|
|
369
|
+
* the default output, the output node of the graph the manifest shows (with the tags and description of the named
|
|
370
|
+
* output it is, if any). Names that are not ids, clashes, a malformed kind, tag or description and a missing default
|
|
371
|
+
* are problems (publishing blocks on them); a clashing name is left out. `invalid`: those of them that have a usable
|
|
372
|
+
* name (a clash, an output naming no node, a malformed field), which an engine cook fails by that name.
|
|
373
|
+
*/
|
|
374
|
+
function folderOutputs(m, graphs) {
|
|
375
|
+
const problems = [];
|
|
376
|
+
// outputs with a usable name that cannot be published as they are (an engine cook fails them by name)
|
|
377
|
+
const invalid = [];
|
|
378
|
+
const byName = new Map();
|
|
379
|
+
for (const [graph, spec] of graphs) {
|
|
380
|
+
for (const [id, out] of Object.entries(spec.outputs ?? {})) {
|
|
381
|
+
if (!out || typeof out !== 'object' || out.publish === false)
|
|
382
|
+
continue;
|
|
383
|
+
if (!ID_RE.test(id)) {
|
|
384
|
+
problems.push(`output "${id}" (graph "${graph}") is not a package output name: lower-case letters, digits, - and _, starting with a letter or digit`);
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (typeof out.node !== 'string' || !Object.hasOwn(spec.nodes, out.node)) {
|
|
388
|
+
problems.push(`output "${id}" (graph "${graph}") names no node of its graph`);
|
|
389
|
+
invalid.push({ id, graphs: [graph], message: `output "${id}" (graph "${graph}") names no node of its graph` });
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
const issues = outputFieldIssues(out);
|
|
393
|
+
if (issues.length) {
|
|
394
|
+
for (const i of issues)
|
|
395
|
+
problems.push(`output "${id}" (graph "${graph}"): ${i.message} (${i.hint})`);
|
|
396
|
+
invalid.push({ id, graphs: [graph], message: issues.map((i) => `output "${id}" (graph "${graph}"): ${i.message} (${i.hint})`).join('; ') });
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
const description = (typeof out.description === 'string' ? out.description.trim() : '') || describedAs(spec);
|
|
400
|
+
const list = byName.get(id) ?? [];
|
|
401
|
+
list.push({
|
|
402
|
+
name: id, graph, spec, node: out.node, ...(typeof out.label === 'string' ? { label: out.label } : {}),
|
|
403
|
+
...(out.kind ? { kind: out.kind } : {}), tags: out.tags ?? [], ...(description ? { description } : {}),
|
|
404
|
+
});
|
|
405
|
+
byName.set(id, list);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
const named = [];
|
|
409
|
+
for (const [id, list] of byName) {
|
|
410
|
+
if (list.length > 1) {
|
|
411
|
+
const said = `output "${id}" is published by graphs ${list.map((o) => `"${o.graph}"`).join(' and ')}: output names are unique in a package (mark all but one "publish": false, or rename)`;
|
|
412
|
+
problems.push(said);
|
|
413
|
+
invalid.push({ id, graphs: list.map((o) => o.graph), message: said });
|
|
414
|
+
}
|
|
415
|
+
else
|
|
416
|
+
named.push(list[0]);
|
|
417
|
+
}
|
|
418
|
+
let def = null;
|
|
419
|
+
const shown = graphs.get(m.graph);
|
|
420
|
+
if (!shown)
|
|
421
|
+
problems.push(`no default output: the manifest shows graph "${m.graph}", and graphs/ has no ${m.graph}.json`);
|
|
422
|
+
else if (!shown.output || !Object.hasOwn(shown.nodes, shown.output))
|
|
423
|
+
problems.push(`no default output: set "output" in graphs/${m.graph}.json (the graph the manifest shows); TopoTopo never picks an end node for a package`);
|
|
424
|
+
else {
|
|
425
|
+
const same = named.find((x) => x.graph === m.graph && x.node === shown.output), description = same ? same.description : describedAs(shown);
|
|
426
|
+
def = { name: null, graph: m.graph, spec: shown, node: shown.output, ...(same?.kind ? { kind: same.kind } : {}), tags: same?.tags ?? [], ...(description ? { description } : {}) };
|
|
427
|
+
}
|
|
428
|
+
return { named: named.sort((a, b) => (a.name < b.name ? -1 : 1)), default: def, problems, invalid };
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* What a package folder publishes, by the rule publishing uses (folderOutputs): every named output of every graph
|
|
432
|
+
* without "publish": false, and the default output (the output node of the graph the manifest shows), named after the
|
|
433
|
+
* package id when it is no named output. `invalid`: names that cannot be published as they are (two graphs naming one
|
|
434
|
+
* output, a default output whose name, the package id, a named output has too, an output naming no node or with a
|
|
435
|
+
* malformed field), each with why; `problems`: the rest of what is wrong (graphs that cannot be read, names that are no
|
|
436
|
+
* ids, no default output). Throws for a folder that is no package. Sorted by id.
|
|
437
|
+
*/
|
|
438
|
+
export function packageOutputs(dir) {
|
|
439
|
+
const m = readManifest(dir), id = packageId(dir);
|
|
440
|
+
const unread = [];
|
|
441
|
+
const graphs = readGraphs(dir, unread);
|
|
442
|
+
const files = graphFiles(dir);
|
|
443
|
+
const outs = folderOutputs(m, graphs);
|
|
444
|
+
const invalid = [];
|
|
445
|
+
for (const bad of outs.invalid) {
|
|
446
|
+
const have = invalid.find((x) => x.id === bad.id);
|
|
447
|
+
if (have) {
|
|
448
|
+
have.graphs = [...new Set([...have.graphs, ...bad.graphs])];
|
|
449
|
+
have.message += `; ${bad.message}`;
|
|
450
|
+
}
|
|
451
|
+
else
|
|
452
|
+
invalid.push({ ...bad, graphs: [...bad.graphs] });
|
|
453
|
+
}
|
|
454
|
+
// A valid declaration cannot rescue another declaration of the same name that is malformed.
|
|
455
|
+
for (const bad of invalid)
|
|
456
|
+
for (const good of outs.named) {
|
|
457
|
+
if (good.name === bad.id && !bad.graphs.includes(good.graph))
|
|
458
|
+
bad.graphs.push(good.graph);
|
|
459
|
+
}
|
|
460
|
+
const problems = [...unread, ...outs.problems.filter((p) => !invalid.some((x) => x.message === p) && !/^output "[^"]+" \(graph "[^"]+"\)(: | names no node)/.test(p))];
|
|
461
|
+
const one = (x, key, isDefault) => ({
|
|
462
|
+
id: key, name: x.name, graph: x.graph, file: files.get(x.graph) ?? path.join(dir, 'graphs', `${x.graph}.json`), spec: x.spec, node: x.node,
|
|
463
|
+
...(x.label ? { label: x.label } : {}), ...(x.kind ? { kind: x.kind } : {}), default: isDefault,
|
|
464
|
+
});
|
|
465
|
+
const outputs = outs.named.filter((x) => !invalid.some((bad) => bad.id === x.name))
|
|
466
|
+
.map((x) => one(x, x.name, !!outs.default && x.graph === outs.default.graph && x.node === outs.default.node));
|
|
467
|
+
const d = outs.default;
|
|
468
|
+
const invalidDefault = d && invalid.some((bad) => bad.graphs.includes(d.graph) && d.spec.outputs?.[bad.id]?.node === d.node);
|
|
469
|
+
if (d && !invalidDefault && !outputs.some((o) => o.default)) {
|
|
470
|
+
const clash = outputs.find((o) => o.id === id);
|
|
471
|
+
if (clash) {
|
|
472
|
+
invalid.push({
|
|
473
|
+
id, graphs: [...new Set([d.graph, clash.graph])],
|
|
474
|
+
message: `the default output ("${d.node}" of graph "${d.graph}") is named after the package, "${id}", and output "${id}" (graph "${clash.graph}") has that name too: rename that output, or publish "${d.node}" as a named output`,
|
|
475
|
+
});
|
|
476
|
+
outputs.splice(outputs.indexOf(clash), 1);
|
|
477
|
+
}
|
|
478
|
+
else if (!invalid.some((x) => x.id === id))
|
|
479
|
+
outputs.push(one(d, id, true));
|
|
480
|
+
}
|
|
481
|
+
return { outputs: outputs.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), invalid: invalid.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), problems };
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* The outputs of package `pkg` that name each other in a loop, through its own outputs by full name (ownOutputsNamed, in
|
|
485
|
+
* the package's scope): output (its name, "" for the default output) → the loop, said.
|
|
486
|
+
*/
|
|
487
|
+
function outputLoops(pkg, outs, scope) {
|
|
488
|
+
const refs = new Map(outs.map((o) => [o.name ?? '', ownOutputsNamed(pkg, o.spec, o.node, scope)]));
|
|
489
|
+
const label = (k) => (k ? `${pkg}/${k}` : pkg);
|
|
490
|
+
const loops = new Map(), state = new Map();
|
|
491
|
+
const visit = (k, stack) => {
|
|
492
|
+
if (state.get(k) === 2 || !refs.has(k))
|
|
493
|
+
return;
|
|
494
|
+
if (state.get(k) === 1) {
|
|
495
|
+
const loop = [...stack.slice(stack.indexOf(k)), k];
|
|
496
|
+
const said = loop.length === 2 ? `${label(k)} names itself` : `${loop.map(label).join(' → ')} name each other in a loop`;
|
|
497
|
+
for (const x of loop)
|
|
498
|
+
if (!loops.has(x))
|
|
499
|
+
loops.set(x, said);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
state.set(k, 1);
|
|
503
|
+
for (const r of refs.get(k))
|
|
504
|
+
visit(r, [...stack, k]);
|
|
505
|
+
state.set(k, 2);
|
|
506
|
+
};
|
|
507
|
+
for (const k of refs.keys())
|
|
508
|
+
visit(k, []);
|
|
509
|
+
return loops;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* An output's record: what it is (the kind it cooked to, its tags and description) and its interface, its params (the
|
|
513
|
+
* vars of its graph that its node reads, with their declarations: varsRead) and its inputs (its input nodes).
|
|
514
|
+
*/
|
|
515
|
+
function outputInfo(o, kind, maps) {
|
|
516
|
+
const sliders = {};
|
|
517
|
+
const read = new Set(varsRead(o.spec, o.node));
|
|
518
|
+
for (const [k, p] of Object.entries(graphInterface(o.spec).params)) {
|
|
519
|
+
if (!read.has(k))
|
|
520
|
+
continue;
|
|
521
|
+
const label = o.spec.params?.[k]?.label;
|
|
522
|
+
sliders[k] = {
|
|
523
|
+
type: p.type, default: p.default,
|
|
524
|
+
...(p.min !== undefined ? { min: p.min } : {}), ...(p.max !== undefined ? { max: p.max } : {}), ...(p.options ? { options: p.options } : {}),
|
|
525
|
+
...(typeof label === 'string' && label ? { label } : {}), ...(p.desc ? { desc: p.desc } : {}),
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
const inputs = [];
|
|
529
|
+
for (const n of Object.values(o.spec.nodes)) {
|
|
530
|
+
if (!n || typeof n.type !== 'string' || getNodeDef(n.type)?.type !== 'input')
|
|
531
|
+
continue;
|
|
532
|
+
inputs.push({ index: Number(n.params?.index ?? 0), label: String(n.params?.label ?? n.note ?? '') });
|
|
533
|
+
}
|
|
534
|
+
return {
|
|
535
|
+
graph: o.graph, node: o.node, ...(o.label ? { label: o.label } : {}), kind, tags: o.tags, ...(o.description ? { description: o.description } : {}),
|
|
536
|
+
sliders, inputs: inputs.sort((a, b) => a.index - b.index), ...(maps && Object.keys(maps).length ? { maps } : {}),
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
/** The maps of a material output: per material, each map slot's image size. */
|
|
540
|
+
function materialMaps(g) {
|
|
541
|
+
const table = readMaterials(g), images = referenceableImages(g), out = {};
|
|
542
|
+
for (const [name, m] of Object.entries(table)) {
|
|
543
|
+
const slots = {};
|
|
544
|
+
for (const [slot, ref] of Object.entries(m.textures ?? {})) {
|
|
545
|
+
const im = ref ? images.get(imageRef(ref) ?? '') : undefined;
|
|
546
|
+
if (im)
|
|
547
|
+
slots[slot] = [im.width, im.height];
|
|
548
|
+
}
|
|
549
|
+
out[name] = slots;
|
|
550
|
+
}
|
|
551
|
+
return out;
|
|
552
|
+
}
|
|
553
|
+
/** A folder as a library entry written from `base`: "./lib", "../lib", "." */
|
|
554
|
+
const pathFrom = (base, dir) => {
|
|
555
|
+
const rel = path.relative(base, dir).split(path.sep).join('/');
|
|
556
|
+
return !rel ? '.' : rel.startsWith('..') ? rel : `./${rel}`;
|
|
557
|
+
};
|
|
558
|
+
/** A workspace's name for messages (its folder's when its file cannot be read). */
|
|
559
|
+
const workspaceName = (ws) => { try {
|
|
560
|
+
return readWorkspace(ws).name;
|
|
561
|
+
}
|
|
562
|
+
catch {
|
|
563
|
+
return path.basename(ws);
|
|
564
|
+
} };
|
|
565
|
+
/** A workspace's copies are never imported by Godot (a .gdignore in their folder), should the game's root be its package. */
|
|
566
|
+
function gdignore(packages) {
|
|
567
|
+
const f = path.join(packages, '.gdignore');
|
|
568
|
+
if (!fs.existsSync(f))
|
|
569
|
+
try {
|
|
570
|
+
fs.writeFileSync(f, '');
|
|
571
|
+
}
|
|
572
|
+
catch { /* Godot imports them: harmless */ }
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Move the copies of the packages inside a workspace that keep their own (their manifest's "uses", their packages/)
|
|
576
|
+
* into the workspace's one shared copy, as topotopo workspace init does: each package at one version for the whole
|
|
577
|
+
* game (two packages that used different versions get the newer, said), the lock entries merged, the packages' uses
|
|
578
|
+
* and copies removed. A package that publishes versions keeps its own (its uses are published with it). A package whose
|
|
579
|
+
* copies differ from the workspace's for the same version (edited by hand) is left as it is, said. Returns what it did,
|
|
580
|
+
* a line each.
|
|
581
|
+
*/
|
|
582
|
+
export function gatherCopies(ws) {
|
|
583
|
+
const store = copiesFor(ws);
|
|
584
|
+
if (store.workspace !== path.resolve(ws))
|
|
585
|
+
return [];
|
|
586
|
+
let scan;
|
|
587
|
+
try {
|
|
588
|
+
scan = scanWorkspace(ws);
|
|
589
|
+
}
|
|
590
|
+
catch {
|
|
591
|
+
return [];
|
|
592
|
+
}
|
|
593
|
+
const packages = scan.packages.filter((p) => copiesFor(p.dir).workspace === store.workspace && Object.keys(p.manifest.uses).length);
|
|
594
|
+
if (!packages.length)
|
|
595
|
+
return [];
|
|
596
|
+
return withStoreLock(store, () => {
|
|
597
|
+
const out = [];
|
|
598
|
+
const uses = readUses(store), lock = readLockAt(store.packages);
|
|
599
|
+
// Godot imports none of the copies: the .gdignore is there before the first copy lands
|
|
600
|
+
fs.mkdirSync(store.packages, { recursive: true });
|
|
601
|
+
gdignore(store.packages);
|
|
602
|
+
let before = [];
|
|
603
|
+
try {
|
|
604
|
+
before = usesClosure(uses, lock);
|
|
605
|
+
}
|
|
606
|
+
catch { /* the lock misses a version: nothing is deleted */ }
|
|
607
|
+
for (const p of packages) {
|
|
608
|
+
const own = readLock(p.dir), ownUses = readManifest(p.dir).uses, from = path.join(p.dir, 'packages');
|
|
609
|
+
// a version the package's lock does not list may be one the workspace holds already
|
|
610
|
+
const both = { packages: {} };
|
|
611
|
+
for (const l of [lock, own])
|
|
612
|
+
for (const [pkg, vs] of Object.entries(l.packages))
|
|
613
|
+
Object.assign(both.packages[pkg] ??= {}, vs);
|
|
614
|
+
let closure;
|
|
615
|
+
try {
|
|
616
|
+
closure = usesClosure(ownUses, both);
|
|
617
|
+
}
|
|
618
|
+
catch (e) {
|
|
619
|
+
out.push(`left ${p.rel} as it is: ${e.message}`);
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
const clash = closure.find(([pkg, v]) => lock.packages[pkg]?.[v] && own.packages[pkg]?.[v] && lock.packages[pkg][v].hash !== own.packages[pkg][v].hash);
|
|
623
|
+
if (clash) {
|
|
624
|
+
out.push(`left ${p.rel} as it is: its copy of ${clash[0]} ${clash[1]} differs from the workspace's (edited by hand?)`);
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
const missing = closure.find(([pkg, v]) => ![from, store.packages].some((d) => fs.existsSync(path.join(copyAt(d, pkg, v), 'version.json'))));
|
|
628
|
+
if (missing) {
|
|
629
|
+
out.push(`left ${p.rel} as it is: its copy of ${missing[0]} ${missing[1]} is missing (${program()} use ${missing[0]} in it copies it again)`);
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
for (const [pkg, v] of closure) {
|
|
633
|
+
const to = copyAt(store.packages, pkg, v);
|
|
634
|
+
if (!fs.existsSync(path.join(to, 'version.json'))) {
|
|
635
|
+
fs.rmSync(to, { recursive: true, force: true });
|
|
636
|
+
copyTree(copyAt(from, pkg, v), to);
|
|
637
|
+
}
|
|
638
|
+
// a library the package's lock names by its path from the package, named from the workspace
|
|
639
|
+
const e = both.packages[pkg][v], k = libraryEntry(e.library);
|
|
640
|
+
const at = 'path' in k && own.packages[pkg]?.[v] === e ? path.resolve(p.dir, k.path) : null;
|
|
641
|
+
(lock.packages[pkg] ??= {})[v] = at && fs.statSync(at, { throwIfNoEntry: false })?.isDirectory() ? { ...e, library: pathFrom(store.root, at) } : e;
|
|
642
|
+
}
|
|
643
|
+
const moved = [];
|
|
644
|
+
for (const [pkg, v] of Object.entries(ownUses)) {
|
|
645
|
+
const was = uses[pkg];
|
|
646
|
+
if (was === undefined || compareVersions(v, was) > 0) {
|
|
647
|
+
if (was !== undefined)
|
|
648
|
+
out.push(`${pkg}: ${p.rel} used ${v}, another package ${was}; the workspace uses ${v} now (${program()} update shows the before/after of a version)`);
|
|
649
|
+
uses[pkg] = v;
|
|
650
|
+
}
|
|
651
|
+
else if (was !== v)
|
|
652
|
+
out.push(`${pkg}: ${p.rel} used ${v}, another package ${was}; the workspace uses ${was}`);
|
|
653
|
+
moved.push(`${pkg} ${v}`);
|
|
654
|
+
}
|
|
655
|
+
writeManifest(p.dir, { ...readManifest(p.dir), uses: {} });
|
|
656
|
+
fs.rmSync(from, { recursive: true, force: true });
|
|
657
|
+
godotIgnore(p.dir);
|
|
658
|
+
out.push(`moved the copies of ${p.rel} into the workspace's: ${moved.join(', ')}`);
|
|
659
|
+
}
|
|
660
|
+
writeLockAt(store.packages, lock);
|
|
661
|
+
writeUses(store, uses);
|
|
662
|
+
// the copies an older version needed that the game uses no more
|
|
663
|
+
let keep;
|
|
664
|
+
try {
|
|
665
|
+
keep = new Set(usesClosure(uses, lock).map(([pkg, v]) => `${pkg}@${v}`));
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
return out;
|
|
669
|
+
}
|
|
670
|
+
const all = Object.entries(lock.packages).flatMap(([pkg, vs]) => Object.keys(vs).map((v) => [pkg, v]));
|
|
671
|
+
const gone = [];
|
|
672
|
+
for (const [pkg, v] of [...before, ...all]) {
|
|
673
|
+
if (keep.has(`${pkg}@${v}`) || !lock.packages[pkg]?.[v])
|
|
674
|
+
continue;
|
|
675
|
+
delete lock.packages[pkg][v];
|
|
676
|
+
if (!Object.keys(lock.packages[pkg]).length)
|
|
677
|
+
delete lock.packages[pkg];
|
|
678
|
+
const at = copyAt(store.packages, pkg, v);
|
|
679
|
+
fs.rmSync(at, { recursive: true, force: true });
|
|
680
|
+
for (let d = path.dirname(at); d.length > store.packages.length; d = path.dirname(d)) {
|
|
681
|
+
try {
|
|
682
|
+
fs.rmdirSync(d);
|
|
683
|
+
}
|
|
684
|
+
catch {
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
gone.push(`${pkg} ${v}`);
|
|
689
|
+
}
|
|
690
|
+
if (gone.length) {
|
|
691
|
+
writeLockAt(store.packages, lock);
|
|
692
|
+
out.push(`deleted the copies no package uses any more: ${gone.join(', ')}`);
|
|
693
|
+
}
|
|
694
|
+
return out;
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* The packages of TopoTopo's built-in library at `dir`: topotopo/<name> for each folder <name> with versions/, a working
|
|
699
|
+
* folder too where it holds that package's manifest (in TopoTopo's repository). Sorted by name.
|
|
700
|
+
*/
|
|
701
|
+
function builtinPackages(dir, problems) {
|
|
702
|
+
let names = [];
|
|
703
|
+
try {
|
|
704
|
+
names = fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && ID_RE.test(e.name)).map((e) => e.name).sort();
|
|
705
|
+
}
|
|
706
|
+
catch {
|
|
707
|
+
return [];
|
|
708
|
+
}
|
|
709
|
+
return names.flatMap((name) => {
|
|
710
|
+
const at = path.join(dir, name), pkg = `${RESERVED_OWNER}/${name}`;
|
|
711
|
+
let working = false;
|
|
712
|
+
try {
|
|
713
|
+
if (manifestAt(at)) {
|
|
714
|
+
const m = readManifest(at);
|
|
715
|
+
if (m.name === pkg)
|
|
716
|
+
working = true;
|
|
717
|
+
else
|
|
718
|
+
problems.add(`${at} in TopoTopo's built-in library holds the versions of ${pkg}, and its manifest names ${m.name ? `the package ${m.name}` : 'no package'}`);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
catch (e) {
|
|
722
|
+
problems.add(e.message);
|
|
723
|
+
}
|
|
724
|
+
return working || fs.existsSync(path.join(at, 'versions')) ? [{ package: pkg, library: BUILTIN_LIBRARY.name, place: BUILTIN_TEXT, at: folderKey(dir), dir: at, working }] : [];
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* The label the lock records for a place: its path from the folder of the copies for a place found by its folder (the
|
|
729
|
+
* workspace's own store: "."; a publishing package's own store inside a workspace: "../.."), else its registered name.
|
|
730
|
+
* Labels look nothing up: they say where a version came from.
|
|
731
|
+
*/
|
|
732
|
+
function lockLabel(lib, store) {
|
|
733
|
+
return lib.byPath && store ? pathFrom(store.root, lib.root) : lib.name;
|
|
734
|
+
}
|
|
735
|
+
/** The places a folder's package looks in (librariesFor) and the packages in them, scanned (see Scanned). */
|
|
736
|
+
function scanPlaces(start, builtin, store) {
|
|
737
|
+
const { libs, problems, workspace } = librariesFor(start);
|
|
738
|
+
const unread = new Set(), builtins = builtinPackages(builtin, unread);
|
|
739
|
+
problems.push(...unread);
|
|
740
|
+
// a place that holds TopoTopo's built-in library (its repository, say) holds none of its packages again
|
|
741
|
+
const seen = new Set(builtins.map((p) => folderKey(p.dir)));
|
|
742
|
+
const packages = [];
|
|
743
|
+
for (const lib of libs) {
|
|
744
|
+
const place = placeText(lib), library = lockLabel(lib, store), at = folderKey(lib.root);
|
|
745
|
+
let scan;
|
|
746
|
+
try {
|
|
747
|
+
scan = lib.workspace ? scanWorkspace(lib.root) : scanTree(lib.name, lib.root);
|
|
748
|
+
}
|
|
749
|
+
catch (e) {
|
|
750
|
+
problems.push(e.message);
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
problems.push(...scan.problems.map((p) => `${place}: ${p}`));
|
|
754
|
+
for (const p of scan.packages) {
|
|
755
|
+
const name = p.manifest.name;
|
|
756
|
+
if (!name)
|
|
757
|
+
continue;
|
|
758
|
+
// a folder reached through two places counts once, in the first
|
|
759
|
+
const key = folderKey(p.dir);
|
|
760
|
+
if (seen.has(key))
|
|
761
|
+
continue;
|
|
762
|
+
seen.add(key);
|
|
763
|
+
if (name.split('/')[0] === RESERVED_OWNER) {
|
|
764
|
+
problems.push(`${place}: ${p.rel} publishes as ${name}, and the packages named "${RESERVED_OWNER}/…" are TopoTopo's built-in library's: it is left out (name it after its owner, "studio/${name.split('/')[1]}")`);
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
packages.push({ package: name, library, place, at, dir: p.dir, working: true });
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
packages.push(...builtins);
|
|
771
|
+
// a name is taken from the first place that has it
|
|
772
|
+
const taken = new Map();
|
|
773
|
+
for (const f of packages) {
|
|
774
|
+
const t = taken.get(f.package);
|
|
775
|
+
if (!t) {
|
|
776
|
+
taken.set(f.package, { folder: f, also: [] });
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
if (t.folder.at === f.at) {
|
|
780
|
+
if (!t.clash) {
|
|
781
|
+
t.clash = `${f.package} is published by two folders of ${f.place}, ${t.folder.dir} and ${f.dir}: TopoTopo never picks one, so the name is not used until one is renamed ("name" in its .topo)`;
|
|
782
|
+
problems.push(t.clash);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
else {
|
|
786
|
+
// a later place of the same name is told apart by the package's folder in it
|
|
787
|
+
const also = f.place === t.folder.place ? `${f.place} (${f.dir})` : f.place;
|
|
788
|
+
if (!t.also.includes(also))
|
|
789
|
+
t.also.push(also);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
return { libs, packages, problems, taken, workspace };
|
|
793
|
+
}
|
|
794
|
+
/** A name as the places give it: its folder and versions; null when no place has it; throws for two folders of one place. */
|
|
795
|
+
function foundIn(s, pkg) {
|
|
796
|
+
const t = s.taken.get(pkg);
|
|
797
|
+
if (!t)
|
|
798
|
+
return null;
|
|
799
|
+
if (t.clash)
|
|
800
|
+
throw new Error(t.clash);
|
|
801
|
+
const versions = new Map(readVersions(t.folder.dir, pkg, t.folder.library, t.folder.place, new Set()).map((p) => [p.info.version, p]));
|
|
802
|
+
return { package: pkg, library: t.folder.library, place: t.folder.place, dir: t.folder.dir, working: t.folder.working, versions, also: t.also };
|
|
803
|
+
}
|
|
804
|
+
/** " (did you mean studio/trees?)" over the names the places give, or ''. */
|
|
805
|
+
const dym = (pkg, s) => { const d = didYouMean(pkg, [...s.taken.keys()]); return d.length ? ` (did you mean ${d.join(', ')}?)` : ''; };
|
|
806
|
+
/** The places of a lookup in a line: the workspace "x" (D:/x), library "props" (D:/props), then TopoTopo's built-in library. */
|
|
807
|
+
const placesLine = (libs) => [...libs.map((l) => `${placeText(l)} (${l.root})`), BUILTIN_TEXT].join(', ');
|
|
808
|
+
/** An update asked for when there is none to make (the version in use is the newest of its big number): not a failure. */
|
|
809
|
+
export class NothingToUpdate extends Error {
|
|
810
|
+
constructor(message) { super(message); this.name = 'NothingToUpdate'; }
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* The packages one package uses, in one engine: the resolver of the engine's root scope (the package's uses), a scope per
|
|
814
|
+
* copied version (its own assets, graphs, files and uses), adding packages on first use, the session's followed
|
|
815
|
+
* working folders. openPackages attaches one to an engine.
|
|
816
|
+
*/
|
|
817
|
+
export class PackageUses {
|
|
818
|
+
engine;
|
|
819
|
+
/** the package folder; null when the folder belongs to no package */
|
|
820
|
+
dir;
|
|
821
|
+
/** where the package's copies, their lock and its uses are (copiesFor): its own, or its workspace's shared copy */
|
|
822
|
+
store;
|
|
823
|
+
/** the folder of TopoTopo's built-in library, which every package looks in */
|
|
824
|
+
builtin;
|
|
825
|
+
/** the folder it was opened for: the package's, or a folder in no package (a workspace's root, say), where lookups start */
|
|
826
|
+
start;
|
|
827
|
+
manifest = null;
|
|
828
|
+
/** the package id, its manifest's name (null while it cannot be read) */
|
|
829
|
+
id = null;
|
|
830
|
+
/** why the manifest or the lock could not be read */
|
|
831
|
+
error = null;
|
|
832
|
+
/**
|
|
833
|
+
* what the last look at TopoTopo's built-in library found wrong with its packages (the catalog's offer of them):
|
|
834
|
+
* replaced by each look
|
|
835
|
+
*/
|
|
836
|
+
libraryProblems = [];
|
|
837
|
+
/** what the engine's root scope resolves package names with */
|
|
838
|
+
resolver;
|
|
839
|
+
root;
|
|
840
|
+
loaded = new Map();
|
|
841
|
+
/** versions read apart from the copies (Context.library), by folder */
|
|
842
|
+
apart = new Map();
|
|
843
|
+
loading = new Set();
|
|
844
|
+
followed = new Map();
|
|
845
|
+
policy = null;
|
|
846
|
+
followLoaded = new Map();
|
|
847
|
+
/** the hash of every followed folder: what their outputs' results are keyed by */
|
|
848
|
+
joint = '';
|
|
849
|
+
/** the package itself, its graphs as they are now ("" until its graphs name one of its outputs) */
|
|
850
|
+
selfStamp = '';
|
|
851
|
+
selfLoaded = null;
|
|
852
|
+
/** the same, its uses resolving to the published copies whatever this session follows (publishing) */
|
|
853
|
+
selfPublished = null;
|
|
854
|
+
/** why first use could not add a package, said when a graph names it */
|
|
855
|
+
unavailable = new Map();
|
|
856
|
+
disk = '';
|
|
857
|
+
watchers = [];
|
|
858
|
+
watchTimer;
|
|
859
|
+
onChange = null;
|
|
860
|
+
/**
|
|
861
|
+
* `builtin`: the folder of TopoTopo's built-in library (default: the one TopoTopo ships, BUILTIN_LIBRARY); `start`: the
|
|
862
|
+
* folder it was opened for, when that is in no package (default: the package's folder, else the engine's)
|
|
863
|
+
*/
|
|
864
|
+
constructor(engine, dir, opts = {}) {
|
|
865
|
+
this.engine = engine;
|
|
866
|
+
this.dir = dir === null ? null : path.resolve(dir);
|
|
867
|
+
this.start = this.dir ?? path.resolve(opts.start ?? engine.root.files.resolvePath('.'));
|
|
868
|
+
this.store = this.dir === null ? null : copiesFor(this.dir);
|
|
869
|
+
this.builtin = path.resolve(opts.builtin ?? BUILTIN_LIBRARY.path);
|
|
870
|
+
this.root = { label: 'this package', uses: {}, packages: this.store ? this.store.packages : '', lock: { packages: {} }, follows: true };
|
|
871
|
+
this.resolver = { resolve: (name) => this.resolveIn(this.root, name), names: () => this.namesIn(this.root), offered: () => this.offered() };
|
|
872
|
+
if (this.store)
|
|
873
|
+
readShaCache(this.store);
|
|
874
|
+
this.reload();
|
|
875
|
+
}
|
|
876
|
+
/** "package lantern (D:/lib/props/lantern)" */
|
|
877
|
+
get label() { return this.manifest && this.id ? `package ${this.id}` : 'this folder'; }
|
|
878
|
+
/** Who it is for, for messages: the package, the workspace at whose root the folder is, or this folder. */
|
|
879
|
+
get who() {
|
|
880
|
+
if (this.dir)
|
|
881
|
+
return this.label;
|
|
882
|
+
const ws = locate(this.start).workspace;
|
|
883
|
+
return ws ? `the workspace "${workspaceName(ws)}"` : 'this folder';
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* The copies the uses of this folder are kept in: the package's (its own, or its workspace's), or at a workspace's
|
|
887
|
+
* root the workspace's; throws for a folder in no package and no workspace.
|
|
888
|
+
*/
|
|
889
|
+
lookStore() {
|
|
890
|
+
if (this.store)
|
|
891
|
+
return this.store;
|
|
892
|
+
const ws = locate(this.start).workspace;
|
|
893
|
+
if (ws)
|
|
894
|
+
return copiesFor(ws);
|
|
895
|
+
this.package();
|
|
896
|
+
throw new Error('unreachable');
|
|
897
|
+
}
|
|
898
|
+
/** The versions in use as they are on disk now: the package's (its own or its workspace's), or at a workspace's root the workspace's. */
|
|
899
|
+
usesHere() { return readUses(this.lookStore()); }
|
|
900
|
+
/** Who holds the uses and copies, for messages: the package, or its workspace (one copy for every package in it). */
|
|
901
|
+
get holder() {
|
|
902
|
+
return this.store?.workspace ? `workspace "${workspaceName(this.store.workspace)}"` : this.label;
|
|
903
|
+
}
|
|
904
|
+
/** The file whose "uses" name the versions in use, for messages: the package's manifest ("forest.topo"), or the workspace's file. */
|
|
905
|
+
get usesFileName() { return this.store?.workspace ? WORKSPACE_FILE : this.store ? path.basename(this.store.usesFile) : 'the manifest'; }
|
|
906
|
+
/** The versions the package uses (its own, or its workspace's), as last read. */
|
|
907
|
+
uses() { return this.root.uses; }
|
|
908
|
+
/**
|
|
909
|
+
* What exports and publishing resolve package names with: the published copies, whatever this session follows
|
|
910
|
+
* (following a working folder is for looking: the viewer, renders). The package's own resolver while nothing is
|
|
911
|
+
* followed.
|
|
912
|
+
*/
|
|
913
|
+
publishedResolver() {
|
|
914
|
+
if (!this.followed.size)
|
|
915
|
+
return this.resolver;
|
|
916
|
+
return { resolve: (name) => this.resolveIn({ ...this.root, follows: false }, name), names: () => this.namesIn({ ...this.root, follows: false }) };
|
|
917
|
+
}
|
|
918
|
+
publishedAt = null;
|
|
919
|
+
/**
|
|
920
|
+
* SessionPackages.published: while this session follows working folders, the scope exports cook in, like the root
|
|
921
|
+
* (its assets, graphs and folder) but resolving packages to their published copies; null while nothing is followed
|
|
922
|
+
* (exports cook in the root, as everything else).
|
|
923
|
+
*/
|
|
924
|
+
published() {
|
|
925
|
+
if (!this.followed.size)
|
|
926
|
+
return null;
|
|
927
|
+
const root = this.engine.root;
|
|
928
|
+
this.publishedAt ??= this.engine.createScope(`published copies ${sha(this.dir ?? '').slice(0, 12)}`, {
|
|
929
|
+
folder: root.files.resolvePath('.'), assets: root.assets, graphs: (n) => root.graphs?.(n), packages: this.publishedResolver(),
|
|
930
|
+
});
|
|
931
|
+
return this.publishedAt;
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* What an export of `graph` made while following says (null when the graph names no followed package): the
|
|
935
|
+
* published versions it used, the working folders being for looking only.
|
|
936
|
+
*/
|
|
937
|
+
publishedNote(graph) {
|
|
938
|
+
const named = new Set(packagesNamedIn(graph));
|
|
939
|
+
const live = [...this.followed.values()].filter((f) => named.has(f.package));
|
|
940
|
+
if (!live.length)
|
|
941
|
+
return null;
|
|
942
|
+
const used = live.map((f) => (this.root.uses[f.package] ? `${f.package} ${this.root.uses[f.package]}` : `${f.package} (no published version in use: publish one, and use it)`));
|
|
943
|
+
return `this session shows ${live.map((f) => f.package).join(', ')} live from ${live.length === 1 ? 'its working folder' : 'their working folders'}, for looking; the export used the published ${used.join(', ')}`;
|
|
944
|
+
}
|
|
945
|
+
/** SessionPackages: why the graphs cannot use packages (a folder in no package, a manifest that is not valid). */
|
|
946
|
+
notice() {
|
|
947
|
+
if (!this.dir)
|
|
948
|
+
return `this folder is in no package, so its graphs cannot use packages yet, TopoTopo's own among them: ${makePackage()}${oldManifestAbove(this.engine.root.files.resolvePath('.'))}`;
|
|
949
|
+
return this.error ? `the packages this package uses cannot be read: ${this.error}` : null;
|
|
950
|
+
}
|
|
951
|
+
/** Load afresh, when next named, the copies that could not load or loaded with a warning (edited by hand). */
|
|
952
|
+
forgetWarned() {
|
|
953
|
+
for (const [k, v] of this.loaded)
|
|
954
|
+
if ('error' in v || v.warned)
|
|
955
|
+
this.loaded.delete(k);
|
|
956
|
+
}
|
|
957
|
+
/** Read the manifest and the lock again (the tools wrote them, or another process did). */
|
|
958
|
+
reload() {
|
|
959
|
+
this.disk = this.diskStamp();
|
|
960
|
+
// a version that loaded stays as it is (it is frozen); one that could not load, or loaded with a warning, is tried again
|
|
961
|
+
this.forgetWarned();
|
|
962
|
+
// the package itself is read again with its uses and lock (its files are hashed again when next named)
|
|
963
|
+
this.selfLoaded = null;
|
|
964
|
+
this.selfPublished = null;
|
|
965
|
+
this.selfStamp = '';
|
|
966
|
+
if (!this.dir)
|
|
967
|
+
return;
|
|
968
|
+
try {
|
|
969
|
+
this.manifest = readManifest(this.dir);
|
|
970
|
+
this.id = packageId(this.dir);
|
|
971
|
+
const pkg = this.manifest.name, store = this.store;
|
|
972
|
+
if (store.workspace && Object.keys(this.manifest.uses).length)
|
|
973
|
+
throw new Error(`${manifestFile(this.dir)} lists "uses" (${Object.entries(this.manifest.uses).map(([k, v]) => `${k} ${v}`).join(', ')}), but the package is in the workspace ${store.workspace}, whose ${WORKSPACE_FILE} names the versions every package in it uses, with one copy of each: ${program()} workspace init ${store.workspace} moves them there`);
|
|
974
|
+
// the package that publishes versions: its graphs name their own outputs, which cook from its graphs as they are now
|
|
975
|
+
this.root = { ...this.root, uses: readUses(store), lock: readLockAt(store.packages), self: pkg ? { package: pkg, get: () => this.loadSelf(pkg) } : undefined };
|
|
976
|
+
this.error = null;
|
|
977
|
+
}
|
|
978
|
+
catch (e) {
|
|
979
|
+
this.error = e.message;
|
|
980
|
+
this.root = { ...this.root, uses: {}, lock: { packages: {} }, self: undefined };
|
|
981
|
+
}
|
|
982
|
+
if (this.policy)
|
|
983
|
+
this.applyPolicy();
|
|
984
|
+
}
|
|
985
|
+
diskStamp() {
|
|
986
|
+
if (!this.dir)
|
|
987
|
+
return '';
|
|
988
|
+
const st = (f) => { const s = fs.statSync(f, { throwIfNoEntry: false }); return s ? `${s.size}:${s.mtimeMs}` : '-'; };
|
|
989
|
+
return `${st(this.manifestPath())}|${st(this.store.usesFile)}|${st(path.join(this.store.packages, 'lock.json'))}`;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* PackageOutput.rootPath: a file as the root names it. Relative to the root's folder (where its relative paths read:
|
|
993
|
+
* the package's, or the folder of a graph file in it) when it lies in the folder of the package's copies (the
|
|
994
|
+
* package's, or its workspace's), as copies do, so exports name no folder of this machine; absolute when it lies
|
|
995
|
+
* elsewhere (a followed working folder in another library).
|
|
996
|
+
*/
|
|
997
|
+
rootPath = (abs) => {
|
|
998
|
+
const inStore = this.store ? path.relative(this.store.root, abs) : '..';
|
|
999
|
+
if (!inStore || inStore.startsWith('..') || path.isAbsolute(inStore))
|
|
1000
|
+
return abs;
|
|
1001
|
+
return path.relative(this.engine.root.files.resolvePath('.'), abs).split(path.sep).join('/');
|
|
1002
|
+
};
|
|
1003
|
+
/** A path for messages: relative to the package when inside it, else to the workspace that holds its copies. */
|
|
1004
|
+
shown(p) {
|
|
1005
|
+
for (const base of [this.dir, this.store?.workspace]) {
|
|
1006
|
+
if (!base)
|
|
1007
|
+
continue;
|
|
1008
|
+
const r = path.relative(base, p);
|
|
1009
|
+
if (r && !r.startsWith('..') && !path.isAbsolute(r))
|
|
1010
|
+
return r.split(path.sep).join('/');
|
|
1011
|
+
}
|
|
1012
|
+
return p;
|
|
1013
|
+
}
|
|
1014
|
+
/** The package's manifest file as it is on disk now ('' when it has none it can read). */
|
|
1015
|
+
manifestPath() {
|
|
1016
|
+
try {
|
|
1017
|
+
return this.dir ? manifestAt(this.dir)?.file ?? '' : '';
|
|
1018
|
+
}
|
|
1019
|
+
catch {
|
|
1020
|
+
return '';
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
/** The package folder and its manifest; throws when the folder is in no package or its manifest is not valid. */
|
|
1024
|
+
package() {
|
|
1025
|
+
if (!this.dir)
|
|
1026
|
+
throw new Error(`this folder is in no package: ${makePackage()}, whose graphs can use packages${oldManifestAbove(this.engine.root.files.resolvePath('.'))}`);
|
|
1027
|
+
if (!this.manifest)
|
|
1028
|
+
throw new Error(this.error ?? `the manifest of ${this.dir} cannot be read`);
|
|
1029
|
+
return { dir: this.dir, manifest: this.manifest };
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* The package itself (when it publishes versions) as its graphs are now, loaded as a package that uses it would: its own
|
|
1033
|
+
* scope with its graphs, assets, files and copies, a node type per published output. null for a package that names
|
|
1034
|
+
* no name to publish under.
|
|
1035
|
+
*/
|
|
1036
|
+
ownPackage(published = false) {
|
|
1037
|
+
if (!this.root.self)
|
|
1038
|
+
return null;
|
|
1039
|
+
return published && this.followed.size ? this.loadSelf(this.root.self.package, false) : this.root.self.get();
|
|
1040
|
+
}
|
|
1041
|
+
/** The package in use that needs version `v` of `pkg`: `pkg` itself, or one that uses it. */
|
|
1042
|
+
directUser(pkg, v) {
|
|
1043
|
+
if (this.root.uses[pkg] === v)
|
|
1044
|
+
return pkg;
|
|
1045
|
+
for (const [top, w] of Object.entries(this.root.uses)) {
|
|
1046
|
+
try {
|
|
1047
|
+
if (usesClosure({ [top]: w }, this.root.lock).some(([p, x]) => p === pkg && x === v))
|
|
1048
|
+
return top;
|
|
1049
|
+
}
|
|
1050
|
+
catch { /* the lock misses a version */ }
|
|
1051
|
+
}
|
|
1052
|
+
return undefined;
|
|
1053
|
+
}
|
|
1054
|
+
// ---------------------------------------------------------------------------------------------- resolution
|
|
1055
|
+
resolverOf(ctx) {
|
|
1056
|
+
return { resolve: (name) => this.resolveIn(ctx, name), names: () => this.namesIn(ctx) };
|
|
1057
|
+
}
|
|
1058
|
+
resolveIn(ctx, name) {
|
|
1059
|
+
const n = parsePackageName(name);
|
|
1060
|
+
if (typeof n === 'string')
|
|
1061
|
+
return { error: n };
|
|
1062
|
+
const p = this.packageIn(ctx, n.package);
|
|
1063
|
+
if ('error' in p)
|
|
1064
|
+
return p;
|
|
1065
|
+
const loop = p.loops.get(n.output ?? '');
|
|
1066
|
+
if (loop)
|
|
1067
|
+
return { error: `${n.output === null ? `the default output of ${packageAt(p)}` : `${packageAt(p)}: output "${n.output}"`} is in a loop: ${loop}`, hint: 'a package\'s outputs use each other by full name only without a loop: change one of their graphs so that it no longer names the other' };
|
|
1068
|
+
if (n.output === null)
|
|
1069
|
+
return p.default ?? { error: `${packageAt(p)} has no default output${p.noDefault ? `: ${p.noDefault}` : ''}`, hint: `name one of its outputs: ${[...p.named.keys()].map((k) => `${n.package}/${k}`).join(', ') || 'it has none'}` };
|
|
1070
|
+
const def = p.named.get(n.output);
|
|
1071
|
+
if (def)
|
|
1072
|
+
return def;
|
|
1073
|
+
const names = [...p.named.keys()], s = didYouMean(n.output, names);
|
|
1074
|
+
return {
|
|
1075
|
+
error: `${packageAt(p)} has no output "${n.output}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`,
|
|
1076
|
+
hint: `its outputs: ${names.join(', ') || 'none besides the default'}${p.default ? `; "${n.package}" alone is its default output` : ''}`,
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
namesIn(ctx) {
|
|
1080
|
+
const pkgs = new Set(Object.keys(ctx.uses));
|
|
1081
|
+
if (ctx.follows)
|
|
1082
|
+
for (const k of this.followed.keys())
|
|
1083
|
+
pkgs.add(k);
|
|
1084
|
+
if (ctx.self)
|
|
1085
|
+
pkgs.add(ctx.self.package);
|
|
1086
|
+
const out = [];
|
|
1087
|
+
for (const pkg of pkgs) {
|
|
1088
|
+
const p = this.packageIn(ctx, pkg);
|
|
1089
|
+
if ('error' in p)
|
|
1090
|
+
continue;
|
|
1091
|
+
if (p.default)
|
|
1092
|
+
out.push(pkg);
|
|
1093
|
+
for (const k of p.named.keys())
|
|
1094
|
+
out.push(`${pkg}/${k}`);
|
|
1095
|
+
}
|
|
1096
|
+
return out;
|
|
1097
|
+
}
|
|
1098
|
+
packageIn(ctx, pkg) {
|
|
1099
|
+
// the package's own outputs: the same version (or working folder), with no entry in its uses
|
|
1100
|
+
if (ctx.self?.package === pkg)
|
|
1101
|
+
return ctx.self.get();
|
|
1102
|
+
if (ctx.follows && this.followed.has(pkg))
|
|
1103
|
+
return this.loadFollowed(pkg);
|
|
1104
|
+
const v = ctx.uses[pkg];
|
|
1105
|
+
if (v !== undefined)
|
|
1106
|
+
return this.loadCopy(ctx, pkg, v);
|
|
1107
|
+
if (ctx !== this.root && !ctx.unavailable)
|
|
1108
|
+
return { error: `${ctx.label} does not use package ${pkg}`, hint: `its uses: ${Object.keys(ctx.uses).join(', ') || 'none'}` };
|
|
1109
|
+
if (!this.dir)
|
|
1110
|
+
return { error: `package ${pkg}: this graph is in no package, and only packages use packages`, hint: `${makePackage()}; then a graph of it that names ${pkg} adds the package (or ${program()} use ${pkg})` };
|
|
1111
|
+
if (this.error)
|
|
1112
|
+
return { error: `package ${pkg}: ${this.error}` };
|
|
1113
|
+
const why = (ctx.unavailable ?? this.unavailable).get(pkg);
|
|
1114
|
+
return {
|
|
1115
|
+
error: `package ${pkg} is not in this package's uses (${this.usesFileName})${why ? `, and it could not be added: ${why}` : ''}`,
|
|
1116
|
+
hint: why
|
|
1117
|
+
? 'a graph that names it adds it once that is solved'
|
|
1118
|
+
: `${program()} use ${pkg} (MCP: workspace {action:"use", package:"${pkg}"}) adds its newest version from the places the package looks in; build and edit add it when a graph first names it`,
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
loadCopy(ctx, pkg, v) {
|
|
1122
|
+
const key = `${pkg}@${v}`, dir = copyAt(ctx.packages, pkg, v);
|
|
1123
|
+
if (ctx.apart || ctx.library?.has(key)) {
|
|
1124
|
+
// Update's before/after: the package's own copy when it holds the version, else the version where it is
|
|
1125
|
+
const place = ctx.library?.get(key);
|
|
1126
|
+
const own = this.ownCopy(pkg, v, place ? place.info.hash : ctx.lock.packages[pkg]?.[v]?.hash, place ? place.dir : dir);
|
|
1127
|
+
return own ?? this.loadApart(ctx, pkg, v);
|
|
1128
|
+
}
|
|
1129
|
+
const have = this.loaded.get(key);
|
|
1130
|
+
if (have) {
|
|
1131
|
+
if ('error' in have || path.resolve(have.dir) === path.resolve(dir))
|
|
1132
|
+
return have;
|
|
1133
|
+
// the same version held in a second place (a followed folder's copies) must hold the same files
|
|
1134
|
+
let hash = '';
|
|
1135
|
+
try {
|
|
1136
|
+
hash = copyHash(dir, ctx.packages);
|
|
1137
|
+
}
|
|
1138
|
+
catch (e) {
|
|
1139
|
+
return { error: `${pkg} ${v} in ${dir}: ${e.message}` };
|
|
1140
|
+
}
|
|
1141
|
+
return hash === have.hash ? have : { error: `${pkg} ${v} has different files in ${have.dir} and in ${dir}: one of them was changed after publishing, and TopoTopo never picks one` };
|
|
1142
|
+
}
|
|
1143
|
+
if (this.loading.has(key))
|
|
1144
|
+
return { error: `${pkg} ${v} uses itself (through ${[...this.loading].join(' → ')})` };
|
|
1145
|
+
this.loading.add(key);
|
|
1146
|
+
let r;
|
|
1147
|
+
try {
|
|
1148
|
+
r = this.loadCopyNow(ctx, pkg, v, dir);
|
|
1149
|
+
}
|
|
1150
|
+
catch (e) {
|
|
1151
|
+
r = { error: `${pkg} ${v}: ${e.message}` };
|
|
1152
|
+
}
|
|
1153
|
+
finally {
|
|
1154
|
+
this.loading.delete(key);
|
|
1155
|
+
}
|
|
1156
|
+
this.loaded.set(key, r);
|
|
1157
|
+
return r;
|
|
1158
|
+
}
|
|
1159
|
+
loadCopyNow(ctx, pkg, v, dir) {
|
|
1160
|
+
// the package in use that needs it, whose `use` copies and records it again
|
|
1161
|
+
const direct = ctx.packages === this.root.packages ? this.directUser(pkg, v) : undefined;
|
|
1162
|
+
if (!fs.existsSync(path.join(dir, 'version.json')))
|
|
1163
|
+
return { error: missingCopy(pkg, v, this.shown(dir)), hint: `${ctx.label} uses it, and the copies are kept with the ${ctx.packages === this.root.packages && this.store?.workspace ? 'workspace' : 'package'} (commit ${this.shown(ctx.packages)}/): restore it, or run ${program()} use ${direct ?? pkg}, which copies what is missing` };
|
|
1164
|
+
const info = readVersionInfo(dir);
|
|
1165
|
+
const m = readManifest(dir);
|
|
1166
|
+
const hash = copyHash(dir, ctx.packages);
|
|
1167
|
+
const expected = ctx.lock.packages[pkg]?.[v]?.hash;
|
|
1168
|
+
let warning;
|
|
1169
|
+
if (expected === undefined)
|
|
1170
|
+
warning = `${this.shown(ctx.packages)}/lock.json does not list ${pkg} ${v}: ${program()} use ${direct ?? pkg} records it`;
|
|
1171
|
+
else if (expected !== hash)
|
|
1172
|
+
warning = editedCopy(pkg, v, this.shown(dir), direct);
|
|
1173
|
+
const vctx = { label: `${pkg} ${v}`, uses: m.uses, packages: ctx.packages, lock: ctx.lock, follows: false };
|
|
1174
|
+
// the scope is the files' too: a copy restored after an edit is another scope, with results of its own
|
|
1175
|
+
return this.build({ pkg, version: v, dir, hash, signature: hash, info, warning, manifest: m, ctx: vctx, scope: `${pkg}@${v}${warning ? `#${hash.slice(0, 16)}` : ''}` });
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* The package's copy of a version, when it holds one that loads: the same files as the version `elsewhere` (whose
|
|
1179
|
+
* hash is `expected`) must be there, TopoTopo never picks between two. null when the package has no such copy.
|
|
1180
|
+
*/
|
|
1181
|
+
ownCopy(pkg, v, expected, elsewhere) {
|
|
1182
|
+
if (expected === undefined || !this.dir || !this.root.lock.packages[pkg]?.[v] || !fs.existsSync(path.join(copyAt(this.root.packages, pkg, v), 'version.json')))
|
|
1183
|
+
return null;
|
|
1184
|
+
const own = this.loadCopy(this.root, pkg, v);
|
|
1185
|
+
if ('error' in own)
|
|
1186
|
+
return null;
|
|
1187
|
+
return own.hash === expected ? own : { error: `${pkg} ${v} has different files in ${own.dir} and in ${elsewhere}: one of them was changed after publishing, and TopoTopo never picks one` };
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* A version where a library holds it (Context.library), or a copy that such a version holds: read there without
|
|
1191
|
+
* copying it, apart from the package's copies, in a scope of its own whose results are keyed by its folder.
|
|
1192
|
+
*/
|
|
1193
|
+
loadApart(ctx, pkg, v) {
|
|
1194
|
+
const place = ctx.library?.get(`${pkg}@${v}`);
|
|
1195
|
+
const dir = path.resolve(place ? place.dir : copyAt(ctx.packages, pkg, v));
|
|
1196
|
+
const have = this.apart.get(dir);
|
|
1197
|
+
if (have)
|
|
1198
|
+
return have;
|
|
1199
|
+
const key = `${pkg}@${v} in ${dir}`;
|
|
1200
|
+
if (this.loading.has(key))
|
|
1201
|
+
return { error: `${pkg} ${v} uses itself (through ${[...this.loading].join(' → ')})` };
|
|
1202
|
+
this.loading.add(key);
|
|
1203
|
+
let r;
|
|
1204
|
+
try {
|
|
1205
|
+
const expected = place ? place.info.hash : ctx.lock.packages[pkg]?.[v]?.hash;
|
|
1206
|
+
if (expected === undefined)
|
|
1207
|
+
r = { error: `${ctx.label} uses ${pkg} ${v}, and its packages/lock.json does not list it` };
|
|
1208
|
+
else if (!fs.existsSync(path.join(dir, 'version.json')))
|
|
1209
|
+
r = { error: `${ctx.label} lists ${pkg} ${v} in its packages/lock.json but holds no copy of it (${dir})` };
|
|
1210
|
+
else {
|
|
1211
|
+
const info = readVersionInfo(dir), m = readManifest(dir);
|
|
1212
|
+
const hash = place ? versionHash(dir, true) : copyHash(dir, ctx.packages);
|
|
1213
|
+
if (hash !== expected)
|
|
1214
|
+
r = { error: `${pkg} ${v} in ${dir} was changed after publishing: its files do not match the hash it was published with` };
|
|
1215
|
+
else {
|
|
1216
|
+
const vctx = { label: `${pkg} ${v}`, uses: m.uses, packages: place ? path.join(dir, 'packages') : ctx.packages, lock: place ? readLock(dir) : ctx.lock, follows: false, apart: true };
|
|
1217
|
+
r = this.build({ pkg, version: v, dir, hash, signature: `${hash}|${dir}`, info, manifest: m, ctx: vctx, scope: `${pkg}@${v}|${dir}` });
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
catch (e) {
|
|
1222
|
+
r = { error: `${pkg} ${v} (${dir}): ${e.message}` };
|
|
1223
|
+
}
|
|
1224
|
+
finally {
|
|
1225
|
+
this.loading.delete(key);
|
|
1226
|
+
}
|
|
1227
|
+
this.apart.set(dir, r);
|
|
1228
|
+
return r;
|
|
1229
|
+
}
|
|
1230
|
+
loadFollowed(pkg) {
|
|
1231
|
+
const have = this.followLoaded.get(pkg);
|
|
1232
|
+
if (have)
|
|
1233
|
+
return have;
|
|
1234
|
+
const f = this.followed.get(pkg), key = `${pkg}@working`;
|
|
1235
|
+
if (this.loading.has(key))
|
|
1236
|
+
return { error: `${pkg} (working folder) uses itself (through ${[...this.loading].join(' → ')})` };
|
|
1237
|
+
this.loading.add(key);
|
|
1238
|
+
let r;
|
|
1239
|
+
try {
|
|
1240
|
+
const m = readManifest(f.dir);
|
|
1241
|
+
const ctx = { label: `${pkg} (working folder)`, uses: m.uses, packages: path.join(f.dir, 'packages'), lock: readLock(f.dir), follows: true };
|
|
1242
|
+
r = this.build({ pkg, version: null, dir: f.dir, hash: f.stamp, signature: this.joint, manifest: m, ctx, scope: `${pkg}@working-${this.joint.slice(0, 16)}` });
|
|
1243
|
+
}
|
|
1244
|
+
catch (e) {
|
|
1245
|
+
r = { error: `${pkg} (working folder ${f.dir}): ${e.message}` };
|
|
1246
|
+
}
|
|
1247
|
+
finally {
|
|
1248
|
+
this.loading.delete(key);
|
|
1249
|
+
}
|
|
1250
|
+
this.followLoaded.set(pkg, r);
|
|
1251
|
+
return r;
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* The package itself (it publishes as `pkg`) as its graphs are now: its graphs name their own
|
|
1255
|
+
* outputs, which cook from the package's folder, as they would from a working folder the session follows.
|
|
1256
|
+
*/
|
|
1257
|
+
loadSelf(pkg, follows = true) {
|
|
1258
|
+
if (!follows)
|
|
1259
|
+
return this.selfPublished ??= this.buildSelf(pkg, false);
|
|
1260
|
+
if (this.selfLoaded)
|
|
1261
|
+
return this.selfLoaded;
|
|
1262
|
+
return this.selfLoaded = this.buildSelf(pkg, true);
|
|
1263
|
+
}
|
|
1264
|
+
/** the package itself from its graphs as they are now, its uses following this session's folders or not */
|
|
1265
|
+
buildSelf(pkg, follows) {
|
|
1266
|
+
const key = `${pkg} (this package${follows ? '' : ', published copies'})`;
|
|
1267
|
+
if (this.loading.has(key))
|
|
1268
|
+
return { error: `${key} uses itself (through ${[...this.loading].join(' → ')})` };
|
|
1269
|
+
this.loading.add(key);
|
|
1270
|
+
let r;
|
|
1271
|
+
try {
|
|
1272
|
+
this.selfStamp ||= workingHash(this.dir);
|
|
1273
|
+
// its outputs may use the packages this session follows: their results are keyed by those folders too
|
|
1274
|
+
const signature = sha(`${this.selfStamp}|${follows ? this.joint : ''}`);
|
|
1275
|
+
const ctx = { label: key, uses: this.root.uses, packages: this.root.packages, lock: this.root.lock, follows };
|
|
1276
|
+
r = this.build({ pkg, version: null, dir: this.dir, hash: this.selfStamp, signature, manifest: this.manifest, ctx, scope: `${pkg}@package-${follows ? '' : 'published-'}${signature.slice(0, 16)}` });
|
|
1277
|
+
}
|
|
1278
|
+
catch (e) {
|
|
1279
|
+
r = { error: `${key} (${this.dir}): ${e.message}` };
|
|
1280
|
+
}
|
|
1281
|
+
finally {
|
|
1282
|
+
this.loading.delete(key);
|
|
1283
|
+
}
|
|
1284
|
+
return r;
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* A version's (or working folder's) scope with its graphs, assets and uses, and a node type per output: what each is
|
|
1288
|
+
* as the version's record (`info`) says, or in a working folder as its author pinned and tagged it. Its graphs and
|
|
1289
|
+
* assets name its own outputs by full name: they resolve to what this builds (Context.self).
|
|
1290
|
+
*/
|
|
1291
|
+
build(o) {
|
|
1292
|
+
const problems = [];
|
|
1293
|
+
const graphs = readGraphs(o.dir, problems);
|
|
1294
|
+
const scope = this.engine.createScope(o.scope, { folder: o.dir, graphs: (n) => graphs.get(n), packages: this.resolverOf(o.ctx) });
|
|
1295
|
+
const outs = folderOutputs(o.manifest, graphs);
|
|
1296
|
+
const def = (x) => {
|
|
1297
|
+
const rec = o.info && (x.name === null ? o.info.default : o.info.outputs[x.name]);
|
|
1298
|
+
const kind = rec ? rec.kind : x.kind, tags = rec ? rec.tags : x.tags;
|
|
1299
|
+
return packageOutputDef({
|
|
1300
|
+
package: o.pkg, version: o.version, hash: o.hash, signature: o.signature, output: x.name, graph: x.graph, spec: x.spec, node: x.node, scope,
|
|
1301
|
+
rootPath: this.rootPath,
|
|
1302
|
+
...(o.info?.note ? { note: o.info.note } : {}), ...(x.label ? { label: x.label } : {}), ...(kind ? { kind } : {}), ...(tags?.length ? { tags } : {}),
|
|
1303
|
+
...(o.warning ? { warning: o.warning } : {}),
|
|
1304
|
+
});
|
|
1305
|
+
};
|
|
1306
|
+
const loaded = {
|
|
1307
|
+
package: o.pkg, version: o.version, dir: o.dir, hash: o.hash, scope,
|
|
1308
|
+
named: new Map(outs.named.map((x) => [x.name, def(x)])),
|
|
1309
|
+
default: outs.default ? def(outs.default) : null,
|
|
1310
|
+
...(outs.default ? {} : { noDefault: outs.problems.find((p) => p.startsWith('no default output'))?.replace(/^no default output: /, '') }),
|
|
1311
|
+
loops: new Map(), problems: [], fileProblems: problems, warned: !!o.warning,
|
|
1312
|
+
deps: () => Object.keys(o.ctx.uses).filter((p) => p !== o.pkg).map((p) => this.packageIn(o.ctx, p)),
|
|
1313
|
+
};
|
|
1314
|
+
// its outputs exist before its assets register: an asset may name one
|
|
1315
|
+
o.ctx.self = { package: o.pkg, get: () => loaded };
|
|
1316
|
+
registerAssets(this.engine, scope, o.dir, problems);
|
|
1317
|
+
loaded.loops = outputLoops(o.pkg, [...outs.named, ...(outs.default ? [outs.default] : [])], scope);
|
|
1318
|
+
const at = packageAt({ package: o.pkg, version: o.version });
|
|
1319
|
+
loaded.problems = [...(o.warning ? [o.warning] : []), ...[...problems, ...outs.problems.filter((p) => !p.startsWith('no default output')), ...new Set(loaded.loops.values())].map((p) => `${at}: ${p}`)];
|
|
1320
|
+
return loaded;
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* What is wrong with the versions `start` reaches (each loaded as it is used, then those they use): copies edited by
|
|
1324
|
+
* hand, files they cannot read, versions that do not load. Each once.
|
|
1325
|
+
*/
|
|
1326
|
+
problemsOf(start) {
|
|
1327
|
+
const out = new Set(), seen = new Set();
|
|
1328
|
+
const visit = (p) => {
|
|
1329
|
+
if ('error' in p) {
|
|
1330
|
+
out.add(p.error);
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
if (seen.has(p))
|
|
1334
|
+
return;
|
|
1335
|
+
seen.add(p);
|
|
1336
|
+
for (const x of p.problems)
|
|
1337
|
+
out.add(x);
|
|
1338
|
+
for (const d of p.deps())
|
|
1339
|
+
visit(d);
|
|
1340
|
+
};
|
|
1341
|
+
for (const p of start)
|
|
1342
|
+
visit(p);
|
|
1343
|
+
return [...out];
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Check every version the package uses (and those they use) as the files are now: what is wrong with them, worked out
|
|
1347
|
+
* afresh each time (a copy restored by hand, a lock fixed since, shows no more). Also the package itself and
|
|
1348
|
+
* the working folders this session follows. Each problem once.
|
|
1349
|
+
*/
|
|
1350
|
+
check() {
|
|
1351
|
+
if (!this.dir || !this.manifest)
|
|
1352
|
+
return [];
|
|
1353
|
+
this.refresh();
|
|
1354
|
+
// a copy that loaded with a warning is hashed again: it may have been restored
|
|
1355
|
+
this.forgetWarned();
|
|
1356
|
+
const start = Object.keys(this.root.uses).filter((p) => !this.followed.has(p)).map((p) => this.packageIn(this.root, p));
|
|
1357
|
+
for (const p of this.followed.keys())
|
|
1358
|
+
start.push(this.loadFollowed(p));
|
|
1359
|
+
if (this.root.self && this.selfStamp)
|
|
1360
|
+
start.push(this.root.self.get());
|
|
1361
|
+
const out = this.problemsOf(start);
|
|
1362
|
+
writeShaCache(this.store);
|
|
1363
|
+
return out;
|
|
1364
|
+
}
|
|
1365
|
+
/** The copies the package's uses need, checked now: one the lock does not list, one missing, one edited by hand. */
|
|
1366
|
+
verifyCopies() {
|
|
1367
|
+
this.package();
|
|
1368
|
+
const store = this.store, packages = store.packages;
|
|
1369
|
+
let lock, closure;
|
|
1370
|
+
try {
|
|
1371
|
+
lock = readLockAt(packages);
|
|
1372
|
+
closure = usesClosure(readUses(store), lock);
|
|
1373
|
+
}
|
|
1374
|
+
catch (e) {
|
|
1375
|
+
return [e.message];
|
|
1376
|
+
}
|
|
1377
|
+
const out = [];
|
|
1378
|
+
for (const [pkg, v] of closure) {
|
|
1379
|
+
const at = copyAt(packages, pkg, v);
|
|
1380
|
+
if (!fs.existsSync(path.join(at, 'version.json')))
|
|
1381
|
+
out.push(missingCopy(pkg, v, this.shown(at), this.directUser(pkg, v)));
|
|
1382
|
+
else if (copyHash(at, packages) !== lock.packages[pkg][v].hash)
|
|
1383
|
+
out.push(editedCopy(pkg, v, this.shown(at), this.directUser(pkg, v)));
|
|
1384
|
+
}
|
|
1385
|
+
return out;
|
|
1386
|
+
}
|
|
1387
|
+
// ------------------------------------------------------------------------------------------------ first use
|
|
1388
|
+
/**
|
|
1389
|
+
* What keeps a graph from cooking with the package exactly as it is (a build machine's --locked): a package it names
|
|
1390
|
+
* that the package does not use, a copy missing or edited by hand. Writes nothing.
|
|
1391
|
+
*/
|
|
1392
|
+
locked(graph) {
|
|
1393
|
+
const adds = this.dryRun(graph).adds.map((a) => `the graph names ${a.package}, which ${this.usesFileName} does not use: ${program()} use ${a.package} adds it (a cook without --locked adds it)`);
|
|
1394
|
+
return [...adds, ...(this.dir && this.manifest ? this.verifyCopies() : [])];
|
|
1395
|
+
}
|
|
1396
|
+
/** The packages a graph names that the package does not use yet (nor follows, nor is). */
|
|
1397
|
+
freshIn(graph) {
|
|
1398
|
+
if (!this.dir || !this.manifest || this.error)
|
|
1399
|
+
return [];
|
|
1400
|
+
return packagesNamedIn(graph).filter((pkg) => this.root.uses[pkg] === undefined && !this.followed.has(pkg) && pkg !== this.manifest.name);
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* SessionPackages: add the packages a graph names that the package does not use yet, once the graph is valid as a
|
|
1404
|
+
* dry run checks it (dryRun: those packages at the version first use adds, read where their library holds them). A
|
|
1405
|
+
* graph that does not validate adds nothing and writes nothing; why a package could not be added is said when the
|
|
1406
|
+
* graph names it.
|
|
1407
|
+
*/
|
|
1408
|
+
addFor(graph) {
|
|
1409
|
+
const fresh = this.freshIn(graph);
|
|
1410
|
+
if (!fresh.length)
|
|
1411
|
+
return [];
|
|
1412
|
+
const d = this.dryRun(graph);
|
|
1413
|
+
for (const [pkg, why] of d.unavailable)
|
|
1414
|
+
this.unavailable.set(pkg, why);
|
|
1415
|
+
if (this.engine.validate(graph, '', { ...this.engine.root, id: d.id, packages: d.resolver }).errors.length)
|
|
1416
|
+
return [];
|
|
1417
|
+
const notes = [];
|
|
1418
|
+
for (const pkg of fresh) {
|
|
1419
|
+
try {
|
|
1420
|
+
notes.push(this.use(pkg).text);
|
|
1421
|
+
this.unavailable.delete(pkg);
|
|
1422
|
+
}
|
|
1423
|
+
catch (e) {
|
|
1424
|
+
this.unavailable.set(pkg, e.message);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
return notes;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Use a package: its newest version in the place the package finds it (or `version`), copied in with
|
|
1431
|
+
* the versions it uses, recorded in the manifest's "uses" and in the lock. For a package in use already, the
|
|
1432
|
+
* copies of the version in use (and of those it uses) that went missing are copied again.
|
|
1433
|
+
*/
|
|
1434
|
+
use(pkg, o = {}) {
|
|
1435
|
+
const { dir } = this.package();
|
|
1436
|
+
const at = /^([^@\s]+)@(.*)$/.exec(pkg);
|
|
1437
|
+
if (at && isPackageName(at[1]))
|
|
1438
|
+
throw new Error(`"${pkg}" is not a package name: name the version apart, ${program()} use ${at[1]} --version ${at[2] || '<version>'} (MCP: workspace {action:"use", package:"${at[1]}", version:"${at[2]}"})`);
|
|
1439
|
+
if (!isPackageName(pkg))
|
|
1440
|
+
throw new Error(`"${pkg}" is not a package name: write owner/name (lower-case letters, digits, - and _)`);
|
|
1441
|
+
if (o.version !== undefined && !VERSION_RE.test(o.version))
|
|
1442
|
+
throw new Error(`"${o.version}" is not a version: write big.small, such as ${/^\d+$/.test(o.version) ? `${o.version}.0` : '1.1'}`);
|
|
1443
|
+
const store = this.store;
|
|
1444
|
+
return withStoreLock(store, () => {
|
|
1445
|
+
const m = readManifest(dir), uses = readUses(store);
|
|
1446
|
+
if (pkg === m.name)
|
|
1447
|
+
throw new Error(`this package is ${pkg}: its graphs name its own outputs by full name, with no entry in "uses"`);
|
|
1448
|
+
const inUse = uses[pkg];
|
|
1449
|
+
if (inUse !== undefined && o.version !== undefined && o.version !== inUse)
|
|
1450
|
+
throw new Error(`${store.workspace ? `the ${this.holder} (every package in it)` : 'this package'} uses ${pkg} ${inUse}: ${program()} update ${pkg} --to ${o.version} shows the before/after of going to ${o.version}, and applies it when asked`);
|
|
1451
|
+
if (inUse !== undefined) {
|
|
1452
|
+
let complete = false;
|
|
1453
|
+
try {
|
|
1454
|
+
complete = usesClosure({ [pkg]: inUse }, readLockAt(store.packages)).every(([p, w]) => fs.existsSync(path.join(copyAt(store.packages, p, w), 'version.json')));
|
|
1455
|
+
}
|
|
1456
|
+
catch { /* the lock lacks one: copy again */ }
|
|
1457
|
+
if (complete)
|
|
1458
|
+
return { version: inUse, copied: [], text: `${this.holder} already uses ${pkg} ${inUse}` };
|
|
1459
|
+
}
|
|
1460
|
+
const { version: v, place } = this.versionToAdd(pkg, inUse ?? o.version);
|
|
1461
|
+
const copied = this.copyIn(pkg, v, place);
|
|
1462
|
+
if (inUse === undefined)
|
|
1463
|
+
writeUses(store, { ...uses, [pkg]: v });
|
|
1464
|
+
this.reload();
|
|
1465
|
+
writeShaCache(store);
|
|
1466
|
+
const deps = copied.filter((c) => c !== `${pkg} ${v}`);
|
|
1467
|
+
return {
|
|
1468
|
+
version: v, copied,
|
|
1469
|
+
text: inUse === undefined
|
|
1470
|
+
? `added ${pkg} ${v} to ${this.holder}${store.workspace ? ' (one copy for every package in it)' : ''} from ${place.place}${deps.length ? `, with ${deps.join(', ')}` : ''}: ${this.shown(copyAt(store.packages, pkg, v))}`
|
|
1471
|
+
: `copied what was missing of ${pkg} ${v} again from ${place.place}: ${copied.join(', ')}`,
|
|
1472
|
+
};
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* The version of a package that is added (`v`, else the newest in the place the package finds it, TopoTopo's built-in
|
|
1477
|
+
* library among the places) and where that place holds it; throws saying why there is none.
|
|
1478
|
+
*/
|
|
1479
|
+
versionToAdd(pkg, v, scanned) {
|
|
1480
|
+
const found = this.find(pkg, scanned);
|
|
1481
|
+
if (!found.versions.size)
|
|
1482
|
+
throw new Error(`${pkg} is in ${found.place} (${found.dir}) but has no published version yet: publish one in its folder (${program()} publish ${found.working ? `${found.dir} ` : ''}--note "...")`);
|
|
1483
|
+
const version = v ?? newestOf(found.versions.keys());
|
|
1484
|
+
const place = found.versions.get(version);
|
|
1485
|
+
if (!place)
|
|
1486
|
+
throw new Error(`${found.place} has no ${pkg} ${version}: it has ${[...found.versions.keys()].sort(compareVersions).join(', ')}`);
|
|
1487
|
+
return { version, place };
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* SessionPackages.dryRun: the packages a graph is checked with where nothing may be written (a dry run, a trial of
|
|
1491
|
+
* a person's values). A package it names for the first time is the version its first use would add, the newest in
|
|
1492
|
+
* the libraries the package looks in (TopoTopo's built-in library among them), read where that library holds it:
|
|
1493
|
+
* nothing is copied, and the manifest and the lock stay as they are. The notes say what build or edit add, and
|
|
1494
|
+
* `unavailable` why the others could not be added; `adds` the versions first use adds. Outside a package, and for a
|
|
1495
|
+
* graph that names nothing new, it is the package's own resolver. `id`: the id of a scope that resolves with it, the
|
|
1496
|
+
* root's own ("") for the package's resolver, else one for the uses it resolves by.
|
|
1497
|
+
*/
|
|
1498
|
+
dryRun(graph) {
|
|
1499
|
+
const fresh = this.freshIn(graph);
|
|
1500
|
+
if (!fresh.length)
|
|
1501
|
+
return { resolver: this.resolver, notes: [], adds: [], unavailable: new Map(), id: this.engine.root.id };
|
|
1502
|
+
const uses = { ...this.root.uses }, library = new Map(), unavailable = new Map(), notes = [];
|
|
1503
|
+
const adds = [];
|
|
1504
|
+
let scanned;
|
|
1505
|
+
for (const pkg of fresh) {
|
|
1506
|
+
try {
|
|
1507
|
+
const { version, place } = this.versionToAdd(pkg, undefined, scanned ??= this.scanLibraries());
|
|
1508
|
+
uses[pkg] = version;
|
|
1509
|
+
library.set(`${pkg}@${version}`, place);
|
|
1510
|
+
adds.push({ package: pkg, version });
|
|
1511
|
+
notes.push(`build or edit adds ${pkg} ${version} to ${this.label} on first use, from ${place.place}: this dry run read it there and copied nothing`);
|
|
1512
|
+
}
|
|
1513
|
+
catch (e) {
|
|
1514
|
+
unavailable.set(pkg, e.message);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
const ctx = { ...this.root, uses: sortKeys(uses), library, unavailable };
|
|
1518
|
+
const id = `dry run ${sha(JSON.stringify([ctx.uses, [...library.values()].map((p) => p.dir)])).slice(0, 16)}`;
|
|
1519
|
+
return { resolver: { ...this.resolverOf(ctx), offered: () => this.offered() }, notes, adds, unavailable, id };
|
|
1520
|
+
}
|
|
1521
|
+
/** Copy a version as published, and the versions it holds copies of, into the package; record them in the lock. */
|
|
1522
|
+
copyIn(pkg, v, place) {
|
|
1523
|
+
const store = this.store, packages = store.packages;
|
|
1524
|
+
if (versionHash(place.dir) !== place.info.hash)
|
|
1525
|
+
throw new Error(`${pkg} ${v} in ${place.dir} (${place.place}) was changed after publishing: its files do not match the hash in its version.json, so it is not copied`);
|
|
1526
|
+
// Godot imports none of the copies: the .gdignore is there before the first copy lands
|
|
1527
|
+
if (store.workspace) {
|
|
1528
|
+
fs.mkdirSync(packages, { recursive: true });
|
|
1529
|
+
gdignore(packages);
|
|
1530
|
+
}
|
|
1531
|
+
else
|
|
1532
|
+
godotIgnore(store.root, ['packages']);
|
|
1533
|
+
if (this.dir)
|
|
1534
|
+
godotIgnore(this.dir);
|
|
1535
|
+
const own = readLock(place.dir).packages;
|
|
1536
|
+
const byKey = new Map([[`${pkg}@${v}`, { pkg, v, from: place.dir, hash: place.info.hash, uses: readManifest(place.dir).uses, keep: (rel) => !nestedCopy(rel) }]]);
|
|
1537
|
+
for (const [p, vs] of Object.entries(own))
|
|
1538
|
+
for (const [w, e] of Object.entries(vs))
|
|
1539
|
+
byKey.set(`${p}@${w}`, { pkg: p, v: w, from: copyAt(path.join(place.dir, 'packages'), p, w), hash: e.hash, uses: e.uses });
|
|
1540
|
+
// the versions a version uses come before it, so a copy that is there already can be checked with them
|
|
1541
|
+
const wanted = [], placed = new Set();
|
|
1542
|
+
const visit = (key) => {
|
|
1543
|
+
const w = byKey.get(key);
|
|
1544
|
+
if (!w || placed.has(key))
|
|
1545
|
+
return;
|
|
1546
|
+
placed.add(key);
|
|
1547
|
+
for (const [p, x] of Object.entries(w.uses))
|
|
1548
|
+
visit(`${p}@${x}`);
|
|
1549
|
+
wanted.push(w);
|
|
1550
|
+
};
|
|
1551
|
+
for (const key of byKey.keys())
|
|
1552
|
+
visit(key);
|
|
1553
|
+
const lock = readLockAt(packages);
|
|
1554
|
+
const copied = [];
|
|
1555
|
+
for (const w of wanted) {
|
|
1556
|
+
if (!fs.existsSync(path.join(w.from, 'version.json')))
|
|
1557
|
+
throw new Error(`${pkg} ${v} in ${place.place} lists ${w.pkg} ${w.v} in its packages/lock.json but holds no copy of it (${w.from})`);
|
|
1558
|
+
const to = copyAt(packages, w.pkg, w.v), have = lock.packages[w.pkg]?.[w.v];
|
|
1559
|
+
if (have && have.hash !== w.hash)
|
|
1560
|
+
throw new Error(`${w.pkg} ${w.v} has different files in ${this.shown(to)} (from ${libraryText(have.library)}) and in ${w.from} (${place.place}): one of them was changed after publishing, and TopoTopo never picks one`);
|
|
1561
|
+
if (fs.existsSync(path.join(to, 'version.json'))) {
|
|
1562
|
+
// already here (another package uses it too): it must be this version
|
|
1563
|
+
if (!have && copyHash(to, packages) !== w.hash)
|
|
1564
|
+
throw new Error(`${this.shown(to)} holds other files than ${w.pkg} ${w.v} as published: move it away, then try again`);
|
|
1565
|
+
}
|
|
1566
|
+
else {
|
|
1567
|
+
if (fs.existsSync(to))
|
|
1568
|
+
throw new Error(`${this.shown(to)} is there but holds no version (no version.json): move it away, then try again`);
|
|
1569
|
+
copyTree(w.from, to, w.keep);
|
|
1570
|
+
copied.push(`${w.pkg} ${w.v}`);
|
|
1571
|
+
}
|
|
1572
|
+
// the lock keeps the library a copy came from
|
|
1573
|
+
if (!have || copied.includes(`${w.pkg} ${w.v}`))
|
|
1574
|
+
(lock.packages[w.pkg] ??= {})[w.v] = { hash: w.hash, library: place.library, uses: w.uses };
|
|
1575
|
+
}
|
|
1576
|
+
writeLockAt(packages, lock);
|
|
1577
|
+
return copied;
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* The places the package finds packages in (librariesFor), in order: its workspace and the shared libraries the
|
|
1581
|
+
* workspace lists, or outside a workspace the library it is in and every registered library; and what is wrong with
|
|
1582
|
+
* them (the others still count). TopoTopo's built-in library, which comes after them, is not one of them.
|
|
1583
|
+
*/
|
|
1584
|
+
libraries() {
|
|
1585
|
+
return librariesFor(this.start);
|
|
1586
|
+
}
|
|
1587
|
+
/** The packages of TopoTopo's built-in library: their versions, and in TopoTopo's repository their working folders. */
|
|
1588
|
+
builtinPackages(problems) {
|
|
1589
|
+
const found = new Set(), out = builtinPackages(this.builtin, found);
|
|
1590
|
+
problems.push(...found);
|
|
1591
|
+
return out;
|
|
1592
|
+
}
|
|
1593
|
+
/** The places the package looks in and the packages in them, TopoTopo's built-in library last (scanPlaces). */
|
|
1594
|
+
scanLibraries() {
|
|
1595
|
+
return scanPlaces(this.start, this.builtin, this.store);
|
|
1596
|
+
}
|
|
1597
|
+
/** Who looks, for messages: this package, or the workspace at whose root the folder is. */
|
|
1598
|
+
get looker() {
|
|
1599
|
+
if (this.dir)
|
|
1600
|
+
return 'this package';
|
|
1601
|
+
const ws = locate(this.start).workspace;
|
|
1602
|
+
return ws ? `the workspace "${workspaceName(ws)}"` : 'this folder';
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* A package where the places the package looks in have it (the first that has it); throws saying where it is not. A
|
|
1606
|
+
* name the last scan did not find is looked for once more in a new scan (a package made since).
|
|
1607
|
+
*/
|
|
1608
|
+
find(pkg, scanned) {
|
|
1609
|
+
let s = scanned ?? this.scanLibraries();
|
|
1610
|
+
let found = foundIn(s, pkg);
|
|
1611
|
+
if (!found && !s.fresh) {
|
|
1612
|
+
forgetScans();
|
|
1613
|
+
const again = this.scanLibraries();
|
|
1614
|
+
again.fresh = true;
|
|
1615
|
+
if (scanned)
|
|
1616
|
+
Object.assign(scanned, again);
|
|
1617
|
+
s = again;
|
|
1618
|
+
found = foundIn(s, pkg);
|
|
1619
|
+
}
|
|
1620
|
+
if (found)
|
|
1621
|
+
return found;
|
|
1622
|
+
const scanProblems = s.problems.length ? `; and could not check ${s.problems.length}: ${s.problems.join('; ')}` : '';
|
|
1623
|
+
if (pkg.split('/')[0] === RESERVED_OWNER)
|
|
1624
|
+
throw new Error(`${BUILTIN_TEXT}, which alone holds the packages named "${RESERVED_OWNER}/…", has no package ${pkg}${dym(pkg, s)}${scanProblems}`);
|
|
1625
|
+
if (s.workspace) {
|
|
1626
|
+
// in a registered library the workspace does not list? Then the command that lists it (not for a library inside
|
|
1627
|
+
// the workspace, whose packages are the workspace's, nor one holding it, which the workspace cannot list)
|
|
1628
|
+
let cfg = null;
|
|
1629
|
+
try {
|
|
1630
|
+
cfg = loadConfig();
|
|
1631
|
+
}
|
|
1632
|
+
catch { /* an unreadable config: only the listed libraries count */ }
|
|
1633
|
+
const listed = new Set(s.libs.map((l) => folderKey(l.root)));
|
|
1634
|
+
for (const lib of cfg?.libraries ?? []) {
|
|
1635
|
+
if (listed.has(folderKey(lib.path)) || within(lib.path, s.workspace) || within(s.workspace, lib.path))
|
|
1636
|
+
continue;
|
|
1637
|
+
if (scanTree(lib.name, lib.path).packages.some((p) => p.manifest.name === pkg))
|
|
1638
|
+
throw new Error(`${pkg} is in library "${lib.name}" (${lib.path}), which the workspace "${workspaceName(s.workspace)}" does not list: ${program()} workspace library add ${lib.name}${workspaceFlag(s.workspace)} lists it (MCP: workspace {action:"libraries", add:"${lib.name}"}, when the person says so)${scanProblems}`);
|
|
1639
|
+
}
|
|
1640
|
+
const shared = s.libs.some((l) => l.from === 'listed');
|
|
1641
|
+
throw new Error(`no place ${this.looker} looks in has a package ${pkg}${dym(pkg, s)}: it looks in ${placesLine(s.libs)}${shared ? '' : `; the workspace lists no shared library (${program()} workspace library add <name or folder>${workspaceFlag(s.workspace)} lists one; MCP: workspace {action:"libraries", add}, when the person says so)`}${scanProblems}`);
|
|
1642
|
+
}
|
|
1643
|
+
if (!s.libs.length)
|
|
1644
|
+
throw new Error(`no library has a package ${pkg}${dym(pkg, s)}: ${this.looker === 'this package' ? 'this package is' : `${this.looker} is`} in no workspace, so it looks in every registered library, and none is registered (${program()} library add <name> <folder> registers one); ${BUILTIN_TEXT} holds TopoTopo's own packages alone${scanProblems}`);
|
|
1645
|
+
throw new Error(`no place ${this.looker} looks in has a package ${pkg}${dym(pkg, s)}: outside a workspace it looks in ${placesLine(s.libs)}${scanProblems}`);
|
|
1646
|
+
}
|
|
1647
|
+
// ------------------------------------------------------------------------------------------------- following
|
|
1648
|
+
/** The packages followed this session, with their working folders. */
|
|
1649
|
+
following() {
|
|
1650
|
+
return [...this.followed.values()].map((f) => ({ package: f.package, dir: f.dir, place: f.place }));
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* Follow a package's working folder for this session, or stop: while it lasts the package resolves to its working
|
|
1654
|
+
* folder in the place the package finds it instead of its copy, under a scope that changes whenever its files do. Nothing
|
|
1655
|
+
* about it is saved.
|
|
1656
|
+
*/
|
|
1657
|
+
follow(pkg, on = true) {
|
|
1658
|
+
this.package();
|
|
1659
|
+
if (!isPackageName(pkg))
|
|
1660
|
+
throw new Error(`"${pkg}" is not a package name: write owner/name`);
|
|
1661
|
+
if (!on) {
|
|
1662
|
+
if (!this.followed.delete(pkg))
|
|
1663
|
+
return `${pkg} is not followed`;
|
|
1664
|
+
this.restamp();
|
|
1665
|
+
this.rewatch();
|
|
1666
|
+
const v = this.root.uses[pkg];
|
|
1667
|
+
return `stopped following ${pkg}: it resolves to ${v ? `its copy (${v})` : 'nothing in this package (it is not in its uses)'} again`;
|
|
1668
|
+
}
|
|
1669
|
+
if (pkg === this.manifest?.name)
|
|
1670
|
+
throw new Error(`this package is ${pkg}: its own graphs are its working folder already`);
|
|
1671
|
+
const found = this.find(pkg);
|
|
1672
|
+
if (!found.working)
|
|
1673
|
+
throw new Error(`${pkg} has no working folder: ${found.place} holds its versions alone${found.library === BUILTIN_LIBRARY.name ? ' (an installed TopoTopo ships its own packages without their working folders)' : ''}, and follow needs one`);
|
|
1674
|
+
this.followed.set(pkg, { package: pkg, dir: found.dir, place: found.place, stamp: '', by: 'name' });
|
|
1675
|
+
this.restamp();
|
|
1676
|
+
this.rewatch();
|
|
1677
|
+
const v = this.root.uses[pkg];
|
|
1678
|
+
return `following ${pkg} for this session: its working folder ${found.dir} (${found.place}) instead of ${v ? `the copy of ${v}` : 'a copy (the package does not use it yet)'}; its edits re-cook, for looking: exports and publishing use the published copy`;
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* Follow, for this session, every package in use whose one working folder the policy accepts (a
|
|
1682
|
+
* workspace's "follow my own packages live": the working folders inside the workspace), besides those followed by
|
|
1683
|
+
* name; null stops it. Applied again whenever the manifest changes (a package added, removed or updated). Returns
|
|
1684
|
+
* the packages it follows.
|
|
1685
|
+
*/
|
|
1686
|
+
setFollowPolicy(policy) {
|
|
1687
|
+
this.policy = policy;
|
|
1688
|
+
this.applyPolicy();
|
|
1689
|
+
return [...this.followed.values()].filter((f) => f.by === 'policy').map((f) => f.package);
|
|
1690
|
+
}
|
|
1691
|
+
applyPolicy() {
|
|
1692
|
+
// the policy's packages worked out afresh (the policy or the uses may have changed); a folder kept keeps its stamp
|
|
1693
|
+
const before = new Map([...this.followed].filter(([, f]) => f.by === 'policy'));
|
|
1694
|
+
for (const pkg of before.keys())
|
|
1695
|
+
this.followed.delete(pkg);
|
|
1696
|
+
let changed = false;
|
|
1697
|
+
if (this.policy && this.dir) {
|
|
1698
|
+
let scanned;
|
|
1699
|
+
for (const pkg of Object.keys(this.root.uses)) {
|
|
1700
|
+
if (this.followed.has(pkg))
|
|
1701
|
+
continue;
|
|
1702
|
+
let found;
|
|
1703
|
+
try {
|
|
1704
|
+
found = this.find(pkg, scanned ??= this.scanLibraries());
|
|
1705
|
+
}
|
|
1706
|
+
catch {
|
|
1707
|
+
continue;
|
|
1708
|
+
}
|
|
1709
|
+
if (!found.working || !this.policy({ package: pkg, dir: found.dir, place: found.place }))
|
|
1710
|
+
continue;
|
|
1711
|
+
const had = before.get(pkg);
|
|
1712
|
+
this.followed.set(pkg, had?.dir === found.dir ? had : { package: pkg, dir: found.dir, place: found.place, stamp: '', by: 'policy' });
|
|
1713
|
+
if (had?.dir !== found.dir)
|
|
1714
|
+
changed = true;
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
for (const pkg of before.keys())
|
|
1718
|
+
if (!this.followed.has(pkg))
|
|
1719
|
+
changed = true;
|
|
1720
|
+
if (changed) {
|
|
1721
|
+
this.restamp();
|
|
1722
|
+
this.rewatch();
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
restamp() {
|
|
1726
|
+
let changed = false;
|
|
1727
|
+
for (const f of this.followed.values()) {
|
|
1728
|
+
let s;
|
|
1729
|
+
try {
|
|
1730
|
+
s = workingHash(f.dir);
|
|
1731
|
+
}
|
|
1732
|
+
catch (e) {
|
|
1733
|
+
s = `unreadable: ${e.message}`;
|
|
1734
|
+
}
|
|
1735
|
+
if (s !== f.stamp) {
|
|
1736
|
+
f.stamp = s;
|
|
1737
|
+
changed = true;
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
const joint = this.followed.size ? sha([...this.followed.values()].map((f) => `${f.package} ${f.stamp}\n`).sort().join('')) : '';
|
|
1741
|
+
if (joint !== this.joint) {
|
|
1742
|
+
this.joint = joint;
|
|
1743
|
+
changed = true;
|
|
1744
|
+
}
|
|
1745
|
+
if (changed) {
|
|
1746
|
+
this.followLoaded.clear();
|
|
1747
|
+
this.selfLoaded = null;
|
|
1748
|
+
this.selfPublished = null;
|
|
1749
|
+
}
|
|
1750
|
+
return changed;
|
|
1751
|
+
}
|
|
1752
|
+
/** The package itself, once its graphs named one of its outputs: true when its files changed since. */
|
|
1753
|
+
restampSelf() {
|
|
1754
|
+
if (!this.selfStamp || !this.dir)
|
|
1755
|
+
return false;
|
|
1756
|
+
let s;
|
|
1757
|
+
try {
|
|
1758
|
+
s = workingHash(this.dir);
|
|
1759
|
+
}
|
|
1760
|
+
catch (e) {
|
|
1761
|
+
s = `unreadable: ${e.message}`;
|
|
1762
|
+
}
|
|
1763
|
+
if (s === this.selfStamp)
|
|
1764
|
+
return false;
|
|
1765
|
+
this.selfStamp = s;
|
|
1766
|
+
this.selfLoaded = null;
|
|
1767
|
+
this.selfPublished = null;
|
|
1768
|
+
return true;
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* SessionPackages: read again what changed on disk: the manifest and the lock, followed working folders, and the
|
|
1772
|
+
* package's own graphs when they name its own outputs.
|
|
1773
|
+
*/
|
|
1774
|
+
refresh() {
|
|
1775
|
+
// the places are scanned again when next looked in: packages may have been made, moved or renamed meanwhile
|
|
1776
|
+
forgetScans();
|
|
1777
|
+
let changed = false;
|
|
1778
|
+
if (this.diskStamp() !== this.disk) {
|
|
1779
|
+
this.reload();
|
|
1780
|
+
changed = true;
|
|
1781
|
+
}
|
|
1782
|
+
if (this.followed.size && this.restamp())
|
|
1783
|
+
changed = true;
|
|
1784
|
+
if (this.restampSelf())
|
|
1785
|
+
changed = true;
|
|
1786
|
+
return changed;
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* SessionPackages: a stamp of what package names resolve to: the manifest and the lock as they are on disk now,
|
|
1790
|
+
* and the files of the followed working folders and of the package itself as refresh() last found them.
|
|
1791
|
+
*/
|
|
1792
|
+
revision() {
|
|
1793
|
+
return `${this.diskStamp()}|${this.joint}|${this.selfStamp}`;
|
|
1794
|
+
}
|
|
1795
|
+
/** Call `onChange` after a followed working folder changed on disk (and refresh() has taken it in). */
|
|
1796
|
+
watch(onChange) {
|
|
1797
|
+
this.onChange = onChange;
|
|
1798
|
+
this.rewatch();
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* What a change in a followed working folder sets off, without waiting for the file watcher (which a test, or a host
|
|
1802
|
+
* that knows a folder changed, calls): refresh, and `onChange` when anything changed. Says whether it did.
|
|
1803
|
+
*/
|
|
1804
|
+
poke() {
|
|
1805
|
+
if (!this.refresh())
|
|
1806
|
+
return false;
|
|
1807
|
+
this.onChange?.();
|
|
1808
|
+
return true;
|
|
1809
|
+
}
|
|
1810
|
+
unwatch() {
|
|
1811
|
+
this.onChange = null;
|
|
1812
|
+
this.rewatch();
|
|
1813
|
+
}
|
|
1814
|
+
rewatch() {
|
|
1815
|
+
for (const w of this.watchers)
|
|
1816
|
+
w.close();
|
|
1817
|
+
this.watchers = [];
|
|
1818
|
+
clearTimeout(this.watchTimer);
|
|
1819
|
+
if (!this.onChange)
|
|
1820
|
+
return;
|
|
1821
|
+
for (const f of this.followed.values()) {
|
|
1822
|
+
try {
|
|
1823
|
+
const w = fs.watch(f.dir, { recursive: true }, () => {
|
|
1824
|
+
clearTimeout(this.watchTimer);
|
|
1825
|
+
this.watchTimer = setTimeout(() => this.poke(), 150);
|
|
1826
|
+
this.watchTimer.unref?.();
|
|
1827
|
+
});
|
|
1828
|
+
w.on('error', () => w.close());
|
|
1829
|
+
w.unref();
|
|
1830
|
+
this.watchers.push(w);
|
|
1831
|
+
}
|
|
1832
|
+
catch { /* not watchable: every cook reads it again (refresh) */ }
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
// --------------------------------------------------------------------------------------------- the places
|
|
1836
|
+
/**
|
|
1837
|
+
* Every package the places the package looks in give (each name from the first place that has it; a name two folders
|
|
1838
|
+
* of one place publish is left out, said): its folder (a working folder, or for one of TopoTopo's own the folder of
|
|
1839
|
+
* its versions), its versions with their records, and the later places that have it too. What is wrong with a place,
|
|
1840
|
+
* an entry of the workspace's "libraries" or a version goes into `problems`.
|
|
1841
|
+
*/
|
|
1842
|
+
catalog(problems = []) {
|
|
1843
|
+
const scanned = this.scanLibraries(), unread = new Set();
|
|
1844
|
+
const out = [...scanned.taken.values()].filter((t) => !t.clash)
|
|
1845
|
+
.map((t) => ({ ...t.folder, also: t.also, versions: readVersions(t.folder.dir, t.folder.package, t.folder.library, t.folder.place, unread).map((x) => x.info).sort((a, b) => compareVersions(a.version, b.version)) }))
|
|
1846
|
+
.sort((a, b) => (a.package < b.package ? -1 : a.package > b.package ? 1 : 0));
|
|
1847
|
+
problems.push(...scanned.problems, ...unread);
|
|
1848
|
+
return out;
|
|
1849
|
+
}
|
|
1850
|
+
/**
|
|
1851
|
+
* For each package in use: the version in use, the small and the big update, every version after it, in the place
|
|
1852
|
+
* the package finds it. What is wrong with a place or an entry of the workspace's "libraries" goes into `problems`; a
|
|
1853
|
+
* package whose versions could not be looked up says why (error).
|
|
1854
|
+
*/
|
|
1855
|
+
outdated(problems = []) {
|
|
1856
|
+
const uses = readUses(this.lookStore());
|
|
1857
|
+
let scanned = null, why = '';
|
|
1858
|
+
if (Object.keys(uses).length)
|
|
1859
|
+
try {
|
|
1860
|
+
scanned = this.scanLibraries();
|
|
1861
|
+
problems.push(...scanned.problems);
|
|
1862
|
+
}
|
|
1863
|
+
catch (e) {
|
|
1864
|
+
why = e.message;
|
|
1865
|
+
}
|
|
1866
|
+
return Object.entries(uses).map(([pkg, version]) => {
|
|
1867
|
+
const o = { package: pkg, version, newer: [], places: [], working: [] };
|
|
1868
|
+
if (!scanned)
|
|
1869
|
+
return { ...o, error: why };
|
|
1870
|
+
try {
|
|
1871
|
+
const f = this.find(pkg, scanned);
|
|
1872
|
+
const big = versionParts(version)[0];
|
|
1873
|
+
const after = [...f.versions.keys()].sort(compareVersions).filter((v) => compareVersions(v, version) > 0);
|
|
1874
|
+
const small = after.filter((v) => versionParts(v)[0] === big).at(-1), top = after.at(-1);
|
|
1875
|
+
o.newer = after.map((v) => f.versions.get(v).info);
|
|
1876
|
+
o.places = [f.place];
|
|
1877
|
+
o.also = f.also;
|
|
1878
|
+
o.working = f.working ? [{ place: f.place, dir: f.dir }] : [];
|
|
1879
|
+
if (small)
|
|
1880
|
+
o.small = small;
|
|
1881
|
+
if (top && versionParts(top)[0] > big)
|
|
1882
|
+
o.big = top;
|
|
1883
|
+
}
|
|
1884
|
+
catch (e) {
|
|
1885
|
+
o.error = e.message;
|
|
1886
|
+
}
|
|
1887
|
+
return o;
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* What an Update of a package in use goes to: `to`, or else the newest version with the same big number. A
|
|
1892
|
+
* big version is a step of its own: it is named. Throws saying why there is none.
|
|
1893
|
+
*/
|
|
1894
|
+
updateTarget(pkg, to) {
|
|
1895
|
+
this.package();
|
|
1896
|
+
if (!isPackageName(pkg))
|
|
1897
|
+
throw new Error(`"${pkg}" is not a package name: write owner/name`);
|
|
1898
|
+
this.refresh();
|
|
1899
|
+
const uses = readUses(this.store), from = uses[pkg];
|
|
1900
|
+
if (from === undefined) {
|
|
1901
|
+
const users = Object.entries(readLockAt(this.store.packages).packages).flatMap(([p, vs]) => Object.entries(vs).filter(([, e]) => e.uses[pkg]).map(([w, e]) => `${p} ${w} uses ${pkg} ${e.uses[pkg]}`));
|
|
1902
|
+
throw new Error(users.length
|
|
1903
|
+
? `this package does not use ${pkg} itself (${users.join('; ')}): a version keeps what it uses, so updating the package that uses it can bring another`
|
|
1904
|
+
: `this package does not use ${pkg}: its uses are ${Object.keys(uses).join(', ') || 'none'}`);
|
|
1905
|
+
}
|
|
1906
|
+
if (to !== undefined && !VERSION_RE.test(to))
|
|
1907
|
+
throw new Error(`"${to}" is not a version: write big.small, such as ${/^[1-9]\d*$/.test(to) ? `${to}.0` : '1.4'}`);
|
|
1908
|
+
const found = this.find(pkg);
|
|
1909
|
+
const all = [...found.versions.keys()].sort(compareVersions);
|
|
1910
|
+
const bigOf = (v) => versionParts(v)[0];
|
|
1911
|
+
let target = to;
|
|
1912
|
+
if (target === undefined) {
|
|
1913
|
+
target = all.filter((v) => bigOf(v) === bigOf(from) && compareVersions(v, from) > 0).at(-1);
|
|
1914
|
+
const big = all.filter((v) => bigOf(v) > bigOf(from)).at(-1);
|
|
1915
|
+
if (!target)
|
|
1916
|
+
throw new NothingToUpdate(big
|
|
1917
|
+
? `${pkg} ${from} is the newest ${bigOf(from)}.x in ${found.place}, and ${big} is a big version, a step of its own: name it, ${program()} update ${pkg} --to ${big} (workspace {action:"update", package:"${pkg}", to:"${big}"})`
|
|
1918
|
+
: `${pkg} ${from} is the newest version in ${found.place}: there is nothing to update`);
|
|
1919
|
+
}
|
|
1920
|
+
else if (target === from)
|
|
1921
|
+
throw new NothingToUpdate(`this package uses ${pkg} ${from} already: there is nothing to update`);
|
|
1922
|
+
const place = found.versions.get(target);
|
|
1923
|
+
if (!place)
|
|
1924
|
+
throw new Error(`${found.place} has no ${pkg} ${target}: it has ${all.join(', ') || 'no version of it'}`);
|
|
1925
|
+
const [lo, hi] = compareVersions(target, from) > 0 ? [from, target] : [target, from];
|
|
1926
|
+
return {
|
|
1927
|
+
package: pkg, from, to: target, big: bigOf(target) !== bigOf(from),
|
|
1928
|
+
fromInfo: this.copyInfo(pkg, from) ?? found.versions.get(from)?.info ?? null, toInfo: place.info,
|
|
1929
|
+
between: all.filter((v) => compareVersions(v, lo) > 0 && compareVersions(v, hi) <= 0).map((v) => found.versions.get(v).info),
|
|
1930
|
+
library: place.library, place: place.place, dir: place.dir,
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* The package resolvers of Update's before/after: the package as its copies cook it now (what this session follows
|
|
1935
|
+
* plays no part) and as it would after the update, which reads the new version where its library holds it. Nothing
|
|
1936
|
+
* is copied. `key` tells pairs apart, for the ids of scopes made with them; `problems` says what is wrong with the
|
|
1937
|
+
* version the update goes to and those it uses, as they load (worked out when asked, for this update only).
|
|
1938
|
+
*/
|
|
1939
|
+
updateResolvers(t) {
|
|
1940
|
+
const uses = sortKeys({ ...this.root.uses, [t.package]: t.to });
|
|
1941
|
+
const before = this.followed.size ? this.resolverOf({ ...this.root, follows: false }) : this.resolver;
|
|
1942
|
+
const ctx = {
|
|
1943
|
+
label: 'this package after the update', uses, packages: this.root.packages, lock: this.root.lock, follows: false, self: this.root.self,
|
|
1944
|
+
library: new Map([[`${t.package}@${t.to}`, { library: t.library, place: t.place, dir: t.dir, info: t.toInfo }]]),
|
|
1945
|
+
};
|
|
1946
|
+
return { before, after: this.resolverOf(ctx), key: sha(JSON.stringify([this.root.uses, uses, t.dir])).slice(0, 16), problems: () => this.problemsOf([this.packageIn(ctx, t.package)]) };
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* Apply an update: copy the version in with the versions it uses, name it in "uses" and the lock, and delete the
|
|
1950
|
+
* copies nothing uses any more (those the package's uses needed before and need no more).
|
|
1951
|
+
*/
|
|
1952
|
+
applyUpdate(t) {
|
|
1953
|
+
this.package();
|
|
1954
|
+
const store = this.store;
|
|
1955
|
+
const { copied, deleted } = withStoreLock(store, () => {
|
|
1956
|
+
const uses = readUses(store);
|
|
1957
|
+
if (uses[t.package] !== t.from)
|
|
1958
|
+
throw new Error(`${this.usesFileName} uses ${t.package} ${uses[t.package] ?? 'no more'} now, not ${t.from}: look at the before/after again`);
|
|
1959
|
+
let before = [];
|
|
1960
|
+
try {
|
|
1961
|
+
before = usesClosure(uses, readLockAt(store.packages));
|
|
1962
|
+
}
|
|
1963
|
+
catch { /* the lock misses a version: nothing is deleted */ }
|
|
1964
|
+
const copied = this.copyIn(t.package, t.to, { library: t.library, place: t.place, dir: t.dir, info: t.toInfo });
|
|
1965
|
+
const now = sortKeys({ ...uses, [t.package]: t.to });
|
|
1966
|
+
writeUses(store, now);
|
|
1967
|
+
return { copied, deleted: this.dropUnused(before, now) };
|
|
1968
|
+
});
|
|
1969
|
+
this.reload();
|
|
1970
|
+
const folder = `${this.shown(store.packages)}/`;
|
|
1971
|
+
return {
|
|
1972
|
+
copied, deleted,
|
|
1973
|
+
text: [
|
|
1974
|
+
`updated ${t.package} ${t.from} → ${t.to} in ${this.holder}${store.workspace ? ', for every package in it' : ''}: ${this.usesFileName} uses ${t.package} ${t.to}, from ${t.place}`,
|
|
1975
|
+
` copied into ${folder}: ${copied.length ? copied.join(', ') : `nothing (the ${store.workspace ? 'workspace' : 'package'} held it already)`}; ${folder}lock.json records them`,
|
|
1976
|
+
` deleted the copies nothing uses any more: ${deleted.length ? deleted.join(', ') : 'none (every other copy is still used)'}`,
|
|
1977
|
+
].join('\n'),
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Delete the copies the uses needed `before` and the package's uses (`uses`, as the manifest now holds them) need no
|
|
1982
|
+
* more, with their entries in the lock; the folders of a package and an owner go once they are empty. Says which.
|
|
1983
|
+
* When the lock misses a version, every copy stays.
|
|
1984
|
+
*/
|
|
1985
|
+
dropUnused(before, uses) {
|
|
1986
|
+
const packages = this.store.packages, lock = readLockAt(packages);
|
|
1987
|
+
let keep;
|
|
1988
|
+
try {
|
|
1989
|
+
keep = new Set(usesClosure(uses, lock).map(([p, v]) => `${p}@${v}`));
|
|
1990
|
+
}
|
|
1991
|
+
catch {
|
|
1992
|
+
return [];
|
|
1993
|
+
}
|
|
1994
|
+
const deleted = [];
|
|
1995
|
+
for (const [p, v] of before) {
|
|
1996
|
+
if (keep.has(`${p}@${v}`))
|
|
1997
|
+
continue;
|
|
1998
|
+
if (lock.packages[p]) {
|
|
1999
|
+
delete lock.packages[p][v];
|
|
2000
|
+
if (!Object.keys(lock.packages[p]).length)
|
|
2001
|
+
delete lock.packages[p];
|
|
2002
|
+
}
|
|
2003
|
+
const at = copyAt(packages, p, v);
|
|
2004
|
+
fs.rmSync(at, { recursive: true, force: true });
|
|
2005
|
+
for (let d = path.dirname(at); d.length > packages.length; d = path.dirname(d)) {
|
|
2006
|
+
try {
|
|
2007
|
+
fs.rmdirSync(d);
|
|
2008
|
+
}
|
|
2009
|
+
catch {
|
|
2010
|
+
break;
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
this.loaded.delete(`${p}@${v}`);
|
|
2014
|
+
deleted.push(`${p} ${v}`);
|
|
2015
|
+
}
|
|
2016
|
+
writeLockAt(packages, lock);
|
|
2017
|
+
return deleted;
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* Remove a package in use: drop it from "uses", and delete its copy and the copies it needed that nothing
|
|
2021
|
+
* else uses, with their entries in the lock. `places`: where the package's graphs still name it (file and node); while
|
|
2022
|
+
* one does, it is refused, listing them.
|
|
2023
|
+
*/
|
|
2024
|
+
remove(pkg, places) {
|
|
2025
|
+
this.package();
|
|
2026
|
+
if (!isPackageName(pkg))
|
|
2027
|
+
throw new Error(`"${pkg}" is not a package name: write owner/name`);
|
|
2028
|
+
const store = this.store, who = store.workspace ? `the ${this.holder}` : 'this package';
|
|
2029
|
+
const { v, deleted } = withStoreLock(store, () => {
|
|
2030
|
+
const uses = readUses(store), v = uses[pkg];
|
|
2031
|
+
if (v === undefined) {
|
|
2032
|
+
const users = Object.entries(readLockAt(store.packages).packages).flatMap(([p, vs]) => Object.entries(vs).filter(([, e]) => e.uses[pkg]).map(([w]) => `${p} ${w}`));
|
|
2033
|
+
throw new Error(users.length
|
|
2034
|
+
? `${who} does not use ${pkg} itself: ${users.join(', ')} ${users.length === 1 ? 'uses' : 'use'} it, and keeps it until ${users.length === 1 ? 'that package goes' : 'those packages go'}`
|
|
2035
|
+
: `${who} does not use ${pkg}: its uses are ${Object.keys(uses).join(', ') || 'none'}`);
|
|
2036
|
+
}
|
|
2037
|
+
const where = store.workspace ? `the workspace's packages` : 'the package';
|
|
2038
|
+
if (places.length)
|
|
2039
|
+
throw new Error(`${places.length === 1 ? `a graph of ${where} still names` : `${places.length} places in the graphs of ${where} still name`} ${pkg}: ${places.join(', ')}; change or remove ${places.length === 1 ? 'that node' : 'those nodes'} first, then remove the package`);
|
|
2040
|
+
let before = [];
|
|
2041
|
+
try {
|
|
2042
|
+
before = usesClosure(uses, readLockAt(store.packages));
|
|
2043
|
+
}
|
|
2044
|
+
catch { /* the lock misses a version: only the package goes from the uses */ }
|
|
2045
|
+
delete uses[pkg];
|
|
2046
|
+
writeUses(store, uses);
|
|
2047
|
+
return { v, deleted: this.dropUnused(before, uses) };
|
|
2048
|
+
});
|
|
2049
|
+
this.reload();
|
|
2050
|
+
return {
|
|
2051
|
+
deleted,
|
|
2052
|
+
text: `removed ${pkg} ${v} from ${this.holder}: ${this.usesFileName} no longer uses it; deleted the copies nothing uses any more: ${deleted.length ? deleted.join(', ') : 'none'}`,
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
/**
|
|
2056
|
+
* PackageResolver.offered: the outputs of TopoTopo's own packages it does not use, at the newest version its
|
|
2057
|
+
* built-in library holds, read there (nothing is copied): the catalog and help list them, and a graph's first use adds
|
|
2058
|
+
* the package. Outside a package as well, where naming one is an error that says how to make the folder a package.
|
|
2059
|
+
*/
|
|
2060
|
+
offered() {
|
|
2061
|
+
const out = [], problems = [], unread = new Set();
|
|
2062
|
+
for (const b of this.builtinPackages(problems)) {
|
|
2063
|
+
if (this.root.uses[b.package] !== undefined || this.followed.has(b.package) || b.package === this.root.self?.package)
|
|
2064
|
+
continue;
|
|
2065
|
+
const place = readVersions(b.dir, b.package, b.library, b.place, unread).at(-1);
|
|
2066
|
+
if (!place)
|
|
2067
|
+
continue;
|
|
2068
|
+
const p = this.readApart(place);
|
|
2069
|
+
if ('error' in p) {
|
|
2070
|
+
problems.push(p.error);
|
|
2071
|
+
continue;
|
|
2072
|
+
}
|
|
2073
|
+
problems.push(...p.problems);
|
|
2074
|
+
if (p.default && !p.loops.has(''))
|
|
2075
|
+
out.push(p.default);
|
|
2076
|
+
for (const [k, d] of p.named)
|
|
2077
|
+
if (!p.loops.has(k))
|
|
2078
|
+
out.push(d);
|
|
2079
|
+
}
|
|
2080
|
+
this.libraryProblems = [...new Set([...problems, ...unread])];
|
|
2081
|
+
return out;
|
|
2082
|
+
}
|
|
2083
|
+
/** A published version where its library holds it, read there apart from the package's copies (nothing is copied). */
|
|
2084
|
+
readApart(place) {
|
|
2085
|
+
const pkg = place.info.package, v = place.info.version;
|
|
2086
|
+
return this.packageIn({ label: `${pkg} ${v}`, uses: { [pkg]: v }, packages: '', lock: { packages: {} }, follows: false, library: new Map([[`${pkg}@${v}`, place]]) }, pkg);
|
|
2087
|
+
}
|
|
2088
|
+
/**
|
|
2089
|
+
* The node type of a package output the package does not use (yet), at the newest version in the libraries it looks in,
|
|
2090
|
+
* read where its library holds it, nothing copied: what help and the catalog say about an output search found. null
|
|
2091
|
+
* when no library it looks in has it (and for a package it uses: those resolve as they cook).
|
|
2092
|
+
*/
|
|
2093
|
+
describe(name) {
|
|
2094
|
+
const n = parsePackageName(name);
|
|
2095
|
+
if (typeof n === 'string' || !this.dir || !this.manifest || this.root.uses[n.package] !== undefined)
|
|
2096
|
+
return null;
|
|
2097
|
+
let found;
|
|
2098
|
+
try {
|
|
2099
|
+
found = this.find(n.package);
|
|
2100
|
+
}
|
|
2101
|
+
catch {
|
|
2102
|
+
return null;
|
|
2103
|
+
}
|
|
2104
|
+
const newest = newestOf(found.versions.keys());
|
|
2105
|
+
const place = newest ? found.versions.get(newest) : undefined;
|
|
2106
|
+
if (!place)
|
|
2107
|
+
return null;
|
|
2108
|
+
const p = this.readApart(place);
|
|
2109
|
+
if ('error' in p)
|
|
2110
|
+
return null;
|
|
2111
|
+
return (n.output === null ? p.default : p.named.get(n.output)) ?? null;
|
|
2112
|
+
}
|
|
2113
|
+
/** The version record of a copy the package holds, null when it is missing. */
|
|
2114
|
+
copyInfo(pkg, v) {
|
|
2115
|
+
let store;
|
|
2116
|
+
try {
|
|
2117
|
+
store = this.lookStore();
|
|
2118
|
+
}
|
|
2119
|
+
catch {
|
|
2120
|
+
return null;
|
|
2121
|
+
}
|
|
2122
|
+
try {
|
|
2123
|
+
return readVersionInfo(copyAt(store.packages, pkg, v));
|
|
2124
|
+
}
|
|
2125
|
+
catch {
|
|
2126
|
+
return null;
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
/** The lock's entries for the versions the package uses, and those they use. */
|
|
2130
|
+
lockEntries() {
|
|
2131
|
+
let lock = this.root.lock, uses = this.root.uses;
|
|
2132
|
+
if (!this.dir) {
|
|
2133
|
+
try {
|
|
2134
|
+
const st = this.lookStore();
|
|
2135
|
+
lock = readLockAt(st.packages);
|
|
2136
|
+
uses = readUses(st);
|
|
2137
|
+
}
|
|
2138
|
+
catch {
|
|
2139
|
+
return [];
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
const out = [];
|
|
2143
|
+
const seen = new Set();
|
|
2144
|
+
const visit = (pkg, v, direct) => {
|
|
2145
|
+
if (seen.has(`${pkg}@${v}`))
|
|
2146
|
+
return;
|
|
2147
|
+
seen.add(`${pkg}@${v}`);
|
|
2148
|
+
const e = lock.packages[pkg]?.[v] ?? null;
|
|
2149
|
+
out.push({ package: pkg, version: v, entry: e, direct });
|
|
2150
|
+
for (const [p, w] of Object.entries(e?.uses ?? {}))
|
|
2151
|
+
visit(p, w, false);
|
|
2152
|
+
};
|
|
2153
|
+
for (const [pkg, v] of Object.entries(uses))
|
|
2154
|
+
visit(pkg, v, true);
|
|
2155
|
+
return out;
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
/** The records of a package's published versions (its versions/ folder), oldest first; unreadable ones are left out. */
|
|
2159
|
+
export function publishedVersions(dir, pkg) {
|
|
2160
|
+
return readVersions(dir, pkg, '', '', new Set()).map((p) => p.info);
|
|
2161
|
+
}
|
|
2162
|
+
/** The records of the versions TopoTopo's built-in library holds of a package, oldest first (none of a package not TopoTopo's). */
|
|
2163
|
+
export function builtinVersions(pkg, builtin = BUILTIN_LIBRARY.path) {
|
|
2164
|
+
const [owner, name] = pkg.split('/');
|
|
2165
|
+
return owner === RESERVED_OWNER && name && ID_RE.test(name) ? publishedVersions(path.join(builtin, name), pkg) : [];
|
|
2166
|
+
}
|
|
2167
|
+
/** The packages of TopoTopo's built-in library, by id; one that cannot be read is left out. */
|
|
2168
|
+
export function builtinLibrary(builtin = BUILTIN_LIBRARY.path) {
|
|
2169
|
+
return builtinPackages(builtin, new Set()).flatMap((f) => {
|
|
2170
|
+
try {
|
|
2171
|
+
const versions = publishedVersions(f.dir, f.package), newest = versions.at(-1);
|
|
2172
|
+
const from = f.working ? f.dir : newest ? path.join(f.dir, 'versions', newest.version) : null;
|
|
2173
|
+
return from ? [{ id: path.basename(f.dir), name: f.package, dir: f.dir, from, manifest: readManifest(from), versions }] : [];
|
|
2174
|
+
}
|
|
2175
|
+
catch {
|
|
2176
|
+
return [];
|
|
2177
|
+
}
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
/** The record of a version a package holds a copy of (packages/<owner>/<name>/<version>/), null when it holds none. */
|
|
2181
|
+
export function copyRecord(dir, pkg, v) {
|
|
2182
|
+
try {
|
|
2183
|
+
return readVersionInfo(copyAt(path.join(dir, 'packages'), pkg, v));
|
|
2184
|
+
}
|
|
2185
|
+
catch {
|
|
2186
|
+
return null;
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
/** The versions in a package's versions/ folder; unreadable records are problems. */
|
|
2190
|
+
function readVersions(dir, pkg, library, place, problems) {
|
|
2191
|
+
const out = [];
|
|
2192
|
+
let names = [];
|
|
2193
|
+
try {
|
|
2194
|
+
names = fs.readdirSync(path.join(dir, 'versions')).filter((v) => VERSION_RE.test(v));
|
|
2195
|
+
}
|
|
2196
|
+
catch {
|
|
2197
|
+
return out;
|
|
2198
|
+
}
|
|
2199
|
+
for (const v of names.sort(compareVersions)) {
|
|
2200
|
+
const vdir = path.join(dir, 'versions', v);
|
|
2201
|
+
if (!fs.existsSync(path.join(vdir, 'version.json')))
|
|
2202
|
+
continue;
|
|
2203
|
+
try {
|
|
2204
|
+
const info = readVersionInfo(vdir);
|
|
2205
|
+
if (info.package !== pkg || info.version !== v) {
|
|
2206
|
+
problems.add(`${vdir}: its version.json says ${info.package} ${info.version}`);
|
|
2207
|
+
continue;
|
|
2208
|
+
}
|
|
2209
|
+
out.push({ library, place, dir: vdir, info });
|
|
2210
|
+
}
|
|
2211
|
+
catch (e) {
|
|
2212
|
+
problems.add(e.message);
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
return out;
|
|
2216
|
+
}
|
|
2217
|
+
/**
|
|
2218
|
+
* The packages used by the package a folder belongs to (the folder itself or the nearest one above with a .topo file),
|
|
2219
|
+
* attached to the engine's root scope, and the working folders to follow this session. `builtin`: the folder of
|
|
2220
|
+
* TopoTopo's built-in library (default: the one TopoTopo ships).
|
|
2221
|
+
*/
|
|
2222
|
+
export function openPackages(engine, start, opts = {}) {
|
|
2223
|
+
const pk = new PackageUses(engine, packageDirOf(start), { builtin: opts.builtin, start });
|
|
2224
|
+
engine.root.packages = pk.resolver;
|
|
2225
|
+
for (const f of opts.follow ?? [])
|
|
2226
|
+
pk.follow(f, true);
|
|
2227
|
+
// a workspace that follows its own packages ("follow": true): the used packages whose working folder is inside it
|
|
2228
|
+
const ws = pk.dir ? locate(pk.dir).workspace : null;
|
|
2229
|
+
let follow = false;
|
|
2230
|
+
if (ws)
|
|
2231
|
+
try {
|
|
2232
|
+
follow = readWorkspace(ws).follow;
|
|
2233
|
+
}
|
|
2234
|
+
catch { /* said by workspace and packages */ }
|
|
2235
|
+
if (ws && follow) {
|
|
2236
|
+
const inside = (d) => { const r = path.relative(ws, d); return !!r && !r.startsWith('..') && !path.isAbsolute(r); };
|
|
2237
|
+
pk.setFollowPolicy((w) => inside(w.dir));
|
|
2238
|
+
}
|
|
2239
|
+
return pk;
|
|
2240
|
+
}
|
|
2241
|
+
/**
|
|
2242
|
+
* A package's assets and graphs in a scope (default: the engine's root) as a session has them, read without writing
|
|
2243
|
+
* anything (a session makes its folders): for a command that cooks the package's graphs and leaves the package as it
|
|
2244
|
+
* is, or for the viewer of a graph file, whose session folder is not the package. Says what could not be read.
|
|
2245
|
+
*/
|
|
2246
|
+
export function loadPackage(engine, dir, scope = engine.root) {
|
|
2247
|
+
const problems = [];
|
|
2248
|
+
const graphs = readGraphs(dir, problems);
|
|
2249
|
+
scope.graphs = (n) => graphs.get(n);
|
|
2250
|
+
registerAssets(engine, scope, dir, problems);
|
|
2251
|
+
return problems;
|
|
2252
|
+
}
|
|
2253
|
+
// ------------------------------------------------------------------------------------------------------ publishing
|
|
2254
|
+
/**
|
|
2255
|
+
* What a version published from the package folder `dir` holds: its manifest, <id>.topo, without "libraries" (where the working
|
|
2256
|
+
* folder looks for packages is not part of the package), graphs/, assets/, inputs/, and the copies its uses need with
|
|
2257
|
+
* their lock. Files by path, or bytes for the files written anew.
|
|
2258
|
+
*/
|
|
2259
|
+
function versionFiles(dir, m, lock) {
|
|
2260
|
+
const file = manifestFile(dir), raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
2261
|
+
delete raw.libraries;
|
|
2262
|
+
const out = [{ rel: path.basename(file), bytes: Buffer.from(JSON.stringify(raw, null, 2) + '\n') }];
|
|
2263
|
+
for (const d of ['graphs', 'assets', 'inputs'])
|
|
2264
|
+
for (const f of filesBelow(path.join(dir, d)))
|
|
2265
|
+
out.push({ rel: `${d}/${f.rel}`, abs: f.abs });
|
|
2266
|
+
const closure = usesClosure(m.uses, lock);
|
|
2267
|
+
if (closure.length) {
|
|
2268
|
+
const own = { packages: {} };
|
|
2269
|
+
for (const [pkg, v] of closure) {
|
|
2270
|
+
(own.packages[pkg] ??= {})[v] = lock.packages[pkg][v];
|
|
2271
|
+
for (const f of filesBelow(copyAt(path.join(dir, 'packages'), pkg, v)))
|
|
2272
|
+
out.push({ rel: `packages/${pkg}/${v}/${f.rel}`, abs: f.abs });
|
|
2273
|
+
}
|
|
2274
|
+
out.push({ rel: 'packages/lock.json', bytes: Buffer.from(lockText(own)) });
|
|
2275
|
+
}
|
|
2276
|
+
return out.sort(byRel);
|
|
2277
|
+
}
|
|
2278
|
+
/** The changes of two lists of tags: "tags added conifer, low-poly", "tag removed tree" (none: the same tags). */
|
|
2279
|
+
const tagChanges = (a, b) => {
|
|
2280
|
+
const added = b.filter((t) => !a.includes(t)), gone = a.filter((t) => !b.includes(t));
|
|
2281
|
+
return [added.length ? `tag${added.length > 1 ? 's' : ''} added ${added.join(', ')}` : '', gone.length ? `tag${gone.length > 1 ? 's' : ''} removed ${gone.join(', ')}` : ''].filter(Boolean);
|
|
2282
|
+
};
|
|
2283
|
+
/**
|
|
2284
|
+
* What changed between two versions' interfaces: what makes a big version (an output, param or input that goes away
|
|
2285
|
+
* or means something else: removed or renamed, another type, a narrower range, a removed option, an input moved, an
|
|
2286
|
+
* output of another kind), and the rest (added outputs, params, options and inputs, wider ranges, changed defaults,
|
|
2287
|
+
* labels, tags and descriptions).
|
|
2288
|
+
*/
|
|
2289
|
+
export function compareInterfaces(prev, next) {
|
|
2290
|
+
const big = [], small = [];
|
|
2291
|
+
const range = (s) => `${s.min ?? ''}..${s.max ?? ''}`;
|
|
2292
|
+
const output = (what, a, b) => {
|
|
2293
|
+
if (a.graph !== b.graph || a.node !== b.node)
|
|
2294
|
+
small.push(`${what} now cooks "${b.node}" of graph "${b.graph}" (was "${a.node}" of "${a.graph}")`);
|
|
2295
|
+
if (a.kind !== b.kind)
|
|
2296
|
+
big.push(`${what}: kind ${a.kind} → ${b.kind}`);
|
|
2297
|
+
for (const c of tagChanges(a.tags ?? [], b.tags ?? []))
|
|
2298
|
+
small.push(`${what}: ${c}`);
|
|
2299
|
+
if ((a.description ?? '') !== (b.description ?? ''))
|
|
2300
|
+
small.push(`${what}: description ${!a.description ? 'added' : !b.description ? 'removed' : 'changed'}`);
|
|
2301
|
+
if ((a.label ?? '') !== (b.label ?? ''))
|
|
2302
|
+
small.push(`${what}: label "${a.label ?? ''}" → "${b.label ?? ''}"`);
|
|
2303
|
+
for (const [k, s] of Object.entries(a.sliders)) {
|
|
2304
|
+
const t = b.sliders[k];
|
|
2305
|
+
if (!t) {
|
|
2306
|
+
big.push(`${what}: param "${k}" removed`);
|
|
2307
|
+
continue;
|
|
2308
|
+
}
|
|
2309
|
+
if (t.type !== s.type) {
|
|
2310
|
+
big.push(`${what}: param "${k}" is now ${t.type} (was ${s.type})`);
|
|
2311
|
+
continue;
|
|
2312
|
+
}
|
|
2313
|
+
const narrower = (t.min !== undefined && (s.min === undefined || t.min > s.min)) || (t.max !== undefined && (s.max === undefined || t.max < s.max));
|
|
2314
|
+
const wider = (s.min !== undefined && (t.min === undefined || t.min < s.min)) || (s.max !== undefined && (t.max === undefined || t.max > s.max));
|
|
2315
|
+
if (narrower)
|
|
2316
|
+
big.push(`${what}: param "${k}" range ${range(s)} → ${range(t)} (narrower)`);
|
|
2317
|
+
else if (wider)
|
|
2318
|
+
small.push(`${what}: param "${k}" range ${range(s)} → ${range(t)} (wider)`);
|
|
2319
|
+
const gone = s.options && t.options ? s.options.filter((x) => !t.options.includes(x)) : [];
|
|
2320
|
+
if (gone.length)
|
|
2321
|
+
big.push(`${what}: param "${k}" lost option${gone.length > 1 ? 's' : ''} ${gone.map((x) => JSON.stringify(x)).join(', ')}`);
|
|
2322
|
+
const added = t.options && s.options ? t.options.filter((x) => !s.options.includes(x)) : [];
|
|
2323
|
+
if (added.length)
|
|
2324
|
+
small.push(`${what}: param "${k}" gained option${added.length > 1 ? 's' : ''} ${added.map((x) => JSON.stringify(x)).join(', ')}`);
|
|
2325
|
+
if (JSON.stringify(s.default) !== JSON.stringify(t.default))
|
|
2326
|
+
small.push(`${what}: param "${k}" default ${JSON.stringify(s.default)} → ${JSON.stringify(t.default)}`);
|
|
2327
|
+
if ((s.label ?? '') !== (t.label ?? '') || (s.desc ?? '') !== (t.desc ?? ''))
|
|
2328
|
+
small.push(`${what}: param "${k}" label or description changed`);
|
|
2329
|
+
}
|
|
2330
|
+
for (const k of Object.keys(b.sliders))
|
|
2331
|
+
if (!a.sliders[k])
|
|
2332
|
+
small.push(`${what}: param "${k}" added`);
|
|
2333
|
+
for (const i of a.inputs) {
|
|
2334
|
+
const at = b.inputs.find((x) => x.index === i.index);
|
|
2335
|
+
const moved = i.label ? b.inputs.find((x) => x.label === i.label && x.index !== i.index) : undefined;
|
|
2336
|
+
if (moved && (!at || at.label !== i.label))
|
|
2337
|
+
big.push(`${what}: input "${i.label}" moved from ${i.index} to ${moved.index}`);
|
|
2338
|
+
else if (!at)
|
|
2339
|
+
big.push(`${what}: input ${i.index}${i.label ? ` ("${i.label}")` : ''} removed`);
|
|
2340
|
+
else if (at.label !== i.label)
|
|
2341
|
+
small.push(`${what}: input ${i.index} label "${i.label}" → "${at.label}"`);
|
|
2342
|
+
}
|
|
2343
|
+
for (const i of b.inputs)
|
|
2344
|
+
if (!a.inputs.some((x) => x.index === i.index || (!!i.label && x.label === i.label)))
|
|
2345
|
+
small.push(`${what}: input ${i.index}${i.label ? ` ("${i.label}")` : ''} added`);
|
|
2346
|
+
};
|
|
2347
|
+
for (const [k, a] of Object.entries(prev.outputs)) {
|
|
2348
|
+
if (!next.outputs[k])
|
|
2349
|
+
big.push(`output "${k}" removed (or renamed, or marked "publish": false)`);
|
|
2350
|
+
else
|
|
2351
|
+
output(`output "${k}"`, a, next.outputs[k]);
|
|
2352
|
+
}
|
|
2353
|
+
for (const k of Object.keys(next.outputs))
|
|
2354
|
+
if (!prev.outputs[k])
|
|
2355
|
+
small.push(`output "${k}" added`);
|
|
2356
|
+
// a default output that is the same named output in both versions has its changes listed with that output
|
|
2357
|
+
const named = (o, outs) => Object.keys(outs).find((k) => outs[k].graph === o.graph && outs[k].node === o.node);
|
|
2358
|
+
const was = named(prev.default, prev.outputs);
|
|
2359
|
+
if (!was || was !== named(next.default, next.outputs))
|
|
2360
|
+
output('the default output', prev.default, next.default);
|
|
2361
|
+
return { big, small };
|
|
2362
|
+
}
|
|
2363
|
+
/** Files a version's graphs and assets read that it does not hold: URLs (their content can change) and paths outside it. */
|
|
2364
|
+
function unheldFiles(sources) {
|
|
2365
|
+
const out = [];
|
|
2366
|
+
const walk = (g, where, depth) => {
|
|
2367
|
+
if (depth > 64 || !g?.nodes || typeof g.nodes !== 'object')
|
|
2368
|
+
return;
|
|
2369
|
+
for (const [name, node] of Object.entries(g.nodes)) {
|
|
2370
|
+
if (!node || typeof node !== 'object' || typeof node.type !== 'string' || !node.params || typeof node.params !== 'object')
|
|
2371
|
+
continue;
|
|
2372
|
+
const def = getNodeDef(node.type);
|
|
2373
|
+
for (const [k, v] of Object.entries(node.params)) {
|
|
2374
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && v.nodes) {
|
|
2375
|
+
walk(v, `${where}${name}/`, depth + 1);
|
|
2376
|
+
continue;
|
|
2377
|
+
}
|
|
2378
|
+
const pn = def ? resolveParamName(def, k) : null;
|
|
2379
|
+
if (!pn || def.params[pn].type !== 'path' || typeof v !== 'string' || !v || v.startsWith('='))
|
|
2380
|
+
continue;
|
|
2381
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(v))
|
|
2382
|
+
out.push(`${where}${name} reads ${v}: a version holds no copy of a URL, so what it gives can change after publishing (put the file in inputs/)`);
|
|
2383
|
+
else if (!/^(image|embedded):/.test(v) && (path.isAbsolute(v) || /^[A-Za-z]:/.test(v) || path.posix.normalize(v.replace(/\\/g, '/')).startsWith('../')))
|
|
2384
|
+
out.push(`${where}${name} reads ${v}, outside the package folder: the version does not hold it (put the file in inputs/)`);
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
};
|
|
2388
|
+
for (const [where, g] of sources)
|
|
2389
|
+
walk(g, `${where}: `, 0);
|
|
2390
|
+
return out;
|
|
2391
|
+
}
|
|
2392
|
+
/** An output as publishing names it: output "pine" (graph "main"), or the default output ("out" of graph "main"). */
|
|
2393
|
+
const outputWhat = (x) => (x.name === null ? `the default output ("${x.node}" of graph "${x.graph}")` : `output "${x.name}" (graph "${x.graph}")`);
|
|
2394
|
+
/**
|
|
2395
|
+
* Publish the package as the next version of its package, in steps, each of which stops publishing (and a dry run)
|
|
2396
|
+
* when it blocks, so that a problem is said once, at its cause, and a version number only for what would publish:
|
|
2397
|
+
* 1. what the package declares: its name, the note, its outputs (names, kinds, tags, descriptions, clashes, the
|
|
2398
|
+
* default output), outputs that name each other in a loop, files it cannot read, its copies (none missing or
|
|
2399
|
+
* edited by hand), a package the session follows, versions/ of another package name;
|
|
2400
|
+
* 2. every published output cooked as a package that uses the package cooks it, through the package's own scope
|
|
2401
|
+
* (its graphs, assets, files and copies, as the version will hold them): an output that does not cook, cooks to
|
|
2402
|
+
* nothing or to another kind than its author pinned blocks, and the kind it cooks to is recorded;
|
|
2403
|
+
* 3. its files: nothing changed since the previous version blocks;
|
|
2404
|
+
* 4. the number, by comparing with the previous version (and the author's `big`), its changes and the warnings: an
|
|
2405
|
+
* output without tags or a description, one whose graph has vars it does not read (they are not its params), an
|
|
2406
|
+
* output of another kind than before, files it reads that the version does not hold, the size;
|
|
2407
|
+
* 5. versions/<big>.<small>/ written through a .part folder, never over one that is there.
|
|
2408
|
+
* A dry run (o.dryRun) goes through every step and writes nothing.
|
|
2409
|
+
*/
|
|
2410
|
+
export async function publishPackage(pk, o) {
|
|
2411
|
+
const { dir } = pk.package();
|
|
2412
|
+
// what its graphs name resolves as its files are now (its own outputs, the copies)
|
|
2413
|
+
pk.refresh();
|
|
2414
|
+
const m = readManifest(dir), file = path.basename(manifestFile(dir)), id = packageId(dir);
|
|
2415
|
+
// one line: a note says what changed
|
|
2416
|
+
const note = (o.note ?? '').replace(/\s+/g, ' ').trim();
|
|
2417
|
+
const dryRun = !!o.dryRun;
|
|
2418
|
+
const r = { ok: false, dryRun, package: m.name ?? '', note, bigBecause: [], changes: [], blocks: [], warnings: [] };
|
|
2419
|
+
const done = () => { r.blocks = [...new Set(r.blocks)]; r.warnings = [...new Set(r.warnings)]; return r; };
|
|
2420
|
+
// 1. what the package declares
|
|
2421
|
+
// TopoTopo's own packages: a folder of its built-in library, named as the package
|
|
2422
|
+
const inBuiltin = path.relative(pk.builtin, dir), isBuiltin = !!inBuiltin && !inBuiltin.startsWith('..') && !path.isAbsolute(inBuiltin) && !/[\\/]/.test(inBuiltin);
|
|
2423
|
+
if (!m.name)
|
|
2424
|
+
r.blocks.push(`${file} has no "name": the author names the package once, "name": "<owner>/${id}" (${program()} init --name <owner>/${id}; owner and name: lower-case letters, digits, - and _)`);
|
|
2425
|
+
else if (o.builtin) {
|
|
2426
|
+
if (!isBuiltin)
|
|
2427
|
+
r.blocks.push(`only a folder of TopoTopo's built-in library (${pk.builtin}) publishes one of TopoTopo's own packages, and ${dir} is none`);
|
|
2428
|
+
else if (m.name !== `${RESERVED_OWNER}/${inBuiltin}`)
|
|
2429
|
+
r.blocks.push(`the folder ${inBuiltin} of TopoTopo's built-in library holds the package ${RESERVED_OWNER}/${inBuiltin}, and its ${file} names ${m.name}`);
|
|
2430
|
+
}
|
|
2431
|
+
else if (m.name.split('/')[0] === RESERVED_OWNER)
|
|
2432
|
+
r.blocks.push(`the owner "${RESERVED_OWNER}" is reserved for TopoTopo's own packages, which TopoTopo's repository publishes into its built-in library: publish under your own owner`);
|
|
2433
|
+
if (!note && !dryRun)
|
|
2434
|
+
r.blocks.push('a version needs a note, one line on what changed: --note "..." (workspace {action:"publish", note})');
|
|
2435
|
+
const live = pk.following();
|
|
2436
|
+
if (live.length)
|
|
2437
|
+
r.warnings.push(`this session shows ${live.map((f) => f.package).join(', ')} live from ${live.length === 1 ? 'its working folder' : 'their working folders'}: the version was checked with the published copies the package uses, which it holds`);
|
|
2438
|
+
// a package keeps its name: versions/ of another name are not this package's
|
|
2439
|
+
if (m.name) {
|
|
2440
|
+
const others = new Map();
|
|
2441
|
+
let names = [];
|
|
2442
|
+
try {
|
|
2443
|
+
names = fs.readdirSync(path.join(dir, 'versions')).filter((v) => VERSION_RE.test(v));
|
|
2444
|
+
}
|
|
2445
|
+
catch { /* none yet */ }
|
|
2446
|
+
for (const v of names) {
|
|
2447
|
+
try {
|
|
2448
|
+
const info = readVersionInfo(path.join(dir, 'versions', v));
|
|
2449
|
+
if (info.package !== m.name)
|
|
2450
|
+
others.set(info.package, [...(others.get(info.package) ?? []), v]);
|
|
2451
|
+
}
|
|
2452
|
+
catch { /* said when its versions are read */ }
|
|
2453
|
+
}
|
|
2454
|
+
for (const [other, vs] of others)
|
|
2455
|
+
r.blocks.push(`versions/ holds the versions of ${other} (${vs.sort(compareVersions).join(', ')}), and ${file} names the package ${m.name}: a package keeps its name; put "name": "${other}" back, or move versions/ away to publish ${m.name} from 1.0`);
|
|
2456
|
+
// one name, one folder per workspace or library
|
|
2457
|
+
const own = librariesFor(dir).self;
|
|
2458
|
+
if (own && !isBuiltin) {
|
|
2459
|
+
let scan = null;
|
|
2460
|
+
try {
|
|
2461
|
+
scan = own.workspace ? scanWorkspace(own.root) : scanTree(own.name, own.root);
|
|
2462
|
+
}
|
|
2463
|
+
catch { /* said where the place is read */ }
|
|
2464
|
+
const twins = (scan?.packages ?? []).filter((p) => p.manifest.name === m.name && folderKey(p.dir) !== folderKey(dir)).map((p) => p.dir);
|
|
2465
|
+
if (twins.length)
|
|
2466
|
+
r.blocks.push(`${twins.join(' and ')} in ${placeText(own)} publish${twins.length === 1 ? 'es' : ''} as ${m.name} too: one name, one folder per workspace or library, or no package can use it; rename one of them ("name" in its .topo)`);
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
let lock = { packages: {} };
|
|
2470
|
+
try {
|
|
2471
|
+
lock = readLock(dir);
|
|
2472
|
+
}
|
|
2473
|
+
catch (e) {
|
|
2474
|
+
r.blocks.push(e.message);
|
|
2475
|
+
}
|
|
2476
|
+
// a version holds its copies as published: none missing, none edited by hand
|
|
2477
|
+
r.blocks.push(...pk.verifyCopies());
|
|
2478
|
+
const unread = [];
|
|
2479
|
+
const graphs = readGraphs(dir, unread);
|
|
2480
|
+
const outs = folderOutputs(m, graphs);
|
|
2481
|
+
// the package as a package that uses it cooks it: its own scope, its graphs as they are now
|
|
2482
|
+
const self = m.name ? pk.ownPackage(true) : null;
|
|
2483
|
+
if (self && 'error' in self)
|
|
2484
|
+
r.blocks.push(self.error);
|
|
2485
|
+
r.blocks.push(...(self && !('error' in self) ? self.fileProblems : unread), ...outs.problems);
|
|
2486
|
+
if (self && !('error' in self))
|
|
2487
|
+
r.blocks.push(...self.loops.values());
|
|
2488
|
+
if (r.blocks.length || !self || 'error' in self || !outs.default)
|
|
2489
|
+
return done();
|
|
2490
|
+
const all = [...outs.named, outs.default];
|
|
2491
|
+
// 2. every published output cooks, to something, and to the kind its author pinned; its kind is recorded. A default
|
|
2492
|
+
// output that is a named output is that output.
|
|
2493
|
+
const sameNamed = (x) => (x.name === null ? outs.named.find((n) => n.graph === x.graph && n.node === x.node) : undefined);
|
|
2494
|
+
const kinds = new Map();
|
|
2495
|
+
const maps = new Map();
|
|
2496
|
+
const published = pk.publishedResolver();
|
|
2497
|
+
const scope = pk.engine.root.packages === published ? pk.engine.root : { ...pk.engine.root, id: `publish ${m.name}${published === pk.resolver ? '' : ' published copies'}`, packages: published };
|
|
2498
|
+
// an output that builds on others of the package (a built-in package's line-up, a house of the package's walls) cooks after them, and
|
|
2499
|
+
// a warning of theirs is said once, under the output it belongs to, not again under each output that builds on it
|
|
2500
|
+
const byName = new Map(all.map((x) => [x.name ?? '', x]));
|
|
2501
|
+
const uses = new Map(all.map((x) => [x, ownOutputsNamed(m.name, x.spec, x.node, self.scope).map((n) => byName.get(n)).filter((y) => !!y && y !== x)]));
|
|
2502
|
+
const order = [], placed = new Set();
|
|
2503
|
+
const place = (x) => { if (placed.has(x))
|
|
2504
|
+
return; placed.add(x); for (const y of uses.get(x))
|
|
2505
|
+
place(y); order.push(x); };
|
|
2506
|
+
for (const x of all)
|
|
2507
|
+
place(x);
|
|
2508
|
+
const core = (s) => s.replace(/^(\[[^\]]*\]\s*)+/, '');
|
|
2509
|
+
const said = new Map();
|
|
2510
|
+
const below = (x, seen = new Set()) => {
|
|
2511
|
+
const out = new Set();
|
|
2512
|
+
for (const y of uses.get(x)) {
|
|
2513
|
+
if (seen.has(y))
|
|
2514
|
+
continue;
|
|
2515
|
+
seen.add(y);
|
|
2516
|
+
for (const k of said.get(y) ?? [])
|
|
2517
|
+
out.add(k);
|
|
2518
|
+
for (const k of below(y, seen))
|
|
2519
|
+
out.add(k);
|
|
2520
|
+
}
|
|
2521
|
+
return out;
|
|
2522
|
+
};
|
|
2523
|
+
for (const x of order) {
|
|
2524
|
+
if (sameNamed(x))
|
|
2525
|
+
continue;
|
|
2526
|
+
const what = outputWhat(x), type = x.name === null ? m.name : `${m.name}/${x.name}`;
|
|
2527
|
+
const c = await pk.engine.cook({ nodes: { output: { type } }, output: 'output' }, { scope });
|
|
2528
|
+
const theirs = below(x), mine = new Set();
|
|
2529
|
+
for (const w of c.warnings) {
|
|
2530
|
+
const k = core(w.message);
|
|
2531
|
+
if (theirs.has(k) || mine.has(k))
|
|
2532
|
+
continue;
|
|
2533
|
+
mine.add(k);
|
|
2534
|
+
r.warnings.push(`${what}: ${w.message}`);
|
|
2535
|
+
}
|
|
2536
|
+
said.set(x, mine);
|
|
2537
|
+
if (!c.ok || !c.geo) {
|
|
2538
|
+
r.blocks.push(`${what} does not cook: ${c.errors.map((e) => e.message.replace(`${type} (${packageAt(self)}) failed: `, '')).join('; ') || 'no geometry'}`);
|
|
2539
|
+
continue;
|
|
2540
|
+
}
|
|
2541
|
+
const info = outputKind(c.geo), kind = publishedKind(info);
|
|
2542
|
+
if (!kind) {
|
|
2543
|
+
r.blocks.push(`${what} cooks to nothing (no polygons, curves, points, instances, heightfields, images, materials or volumes): there is nothing to publish`);
|
|
2544
|
+
continue;
|
|
2545
|
+
}
|
|
2546
|
+
kinds.set(x, kind);
|
|
2547
|
+
if (kind === 'material')
|
|
2548
|
+
maps.set(x, materialMaps(c.geo));
|
|
2549
|
+
if (x.kind && x.kind !== kind)
|
|
2550
|
+
r.blocks.push(`${what}: ${kindMismatch(x.kind, info)}`);
|
|
2551
|
+
}
|
|
2552
|
+
for (const x of all) {
|
|
2553
|
+
const same = sameNamed(x);
|
|
2554
|
+
if (same && kinds.has(same))
|
|
2555
|
+
kinds.set(x, kinds.get(same));
|
|
2556
|
+
}
|
|
2557
|
+
if (r.blocks.length)
|
|
2558
|
+
return done();
|
|
2559
|
+
// 3. its files
|
|
2560
|
+
let hashed = [], hash = '';
|
|
2561
|
+
try {
|
|
2562
|
+
hashed = versionFiles(dir, m, lock).map((f) => ({ rel: f.rel, bytes: f.bytes ?? fs.readFileSync(f.abs) }));
|
|
2563
|
+
hash = filesHash(hashed.map((f) => ({ rel: f.rel, sha: contentSha(f.rel, f.bytes) })));
|
|
2564
|
+
}
|
|
2565
|
+
catch (e) {
|
|
2566
|
+
r.blocks.push(e.message);
|
|
2567
|
+
return done();
|
|
2568
|
+
}
|
|
2569
|
+
const bytes = hashed.reduce((s, f) => s + f.bytes.byteLength, 0);
|
|
2570
|
+
const prev = readVersions(dir, m.name, '', '', new Set()).at(-1)?.info;
|
|
2571
|
+
if (prev && prev.hash === hash) {
|
|
2572
|
+
r.blocks.push(`nothing changed since ${prev.version}`);
|
|
2573
|
+
return done();
|
|
2574
|
+
}
|
|
2575
|
+
// 4. the number, the changes and the warnings
|
|
2576
|
+
for (const x of all) {
|
|
2577
|
+
if (sameNamed(x))
|
|
2578
|
+
continue;
|
|
2579
|
+
const what = outputWhat(x);
|
|
2580
|
+
if (!x.tags.length)
|
|
2581
|
+
r.warnings.push(x.name === null
|
|
2582
|
+
? `${what} has no tags, which search finds an output by: tags go on a named output, so name it in its graph's "outputs" with "tags"`
|
|
2583
|
+
: `${what} has no tags, which search finds an output by: "tags": ["conifer", "low-poly"] in its graph's outputs`);
|
|
2584
|
+
if (!x.description)
|
|
2585
|
+
r.warnings.push(`${what} has no description: ${x.name === null ? 'describe its graph ("description")' : 'give it "description" in its graph\'s outputs, or describe its graph'}`);
|
|
2586
|
+
const read = new Set(varsRead(x.spec, x.node)), idle = Object.keys(x.spec.vars ?? {}).filter((k) => !read.has(k));
|
|
2587
|
+
if (idle.length)
|
|
2588
|
+
r.warnings.push(`${what} does not read ${idle.length === 1 ? 'the var' : 'the vars'} ${idle.map((k) => `"${k}"`).join(', ')} of its graph: ${idle.length === 1 ? 'it is not one of its params' : 'they are not its params'} (an output's params are the vars its node reads; move it to a graph of its own to give it params of its own)`);
|
|
2589
|
+
}
|
|
2590
|
+
const outputs = Object.fromEntries(outs.named.map((x) => [x.name, outputInfo(x, kinds.get(x), maps.get(x) ?? maps.get(sameNamed(x)))]));
|
|
2591
|
+
const def = outputInfo(outs.default, kinds.get(outs.default), maps.get(outs.default) ?? maps.get(sameNamed(outs.default)));
|
|
2592
|
+
let version = '1.0';
|
|
2593
|
+
if (prev) {
|
|
2594
|
+
const c = compareInterfaces(prev, { outputs, default: def });
|
|
2595
|
+
r.bigBecause = [...c.big, ...(o.big ? ['the author marked it big (--big)'] : [])];
|
|
2596
|
+
r.changes = c.small;
|
|
2597
|
+
const [b, s] = versionParts(prev.version);
|
|
2598
|
+
version = r.bigBecause.length ? `${b + 1}.0` : `${b}.${s + 1}`;
|
|
2599
|
+
r.previous = prev.version;
|
|
2600
|
+
// a package may rely on what an output is: an Unreal static mesh is not a level
|
|
2601
|
+
const was = (k, now, before) => {
|
|
2602
|
+
if (before && before.kind !== now.kind)
|
|
2603
|
+
r.warnings.push(`${k} is now ${now.kind} (it was ${before.kind} in ${prev.version}): a package that relies on what it is may have to change, and the version is big`);
|
|
2604
|
+
};
|
|
2605
|
+
for (const x of outs.named)
|
|
2606
|
+
was(outputWhat(x), outputs[x.name], prev.outputs[x.name]);
|
|
2607
|
+
if (!sameNamed(outs.default) && defaultOutputName(prev) === null)
|
|
2608
|
+
was(outputWhat(outs.default), def, prev.default);
|
|
2609
|
+
}
|
|
2610
|
+
Object.assign(r, { version, outputs, default: def });
|
|
2611
|
+
if (bytes > MAX_VERSION_BYTES)
|
|
2612
|
+
r.warnings.push(`the version holds ${(bytes / 2 ** 20).toFixed(0)} MB (above ${MAX_VERSION_BYTES / 2 ** 20} MB): every package that uses it keeps a copy`);
|
|
2613
|
+
const sources = new Map([...[...graphs].map(([k, g]) => [`graphs/${k}.json`, g])]);
|
|
2614
|
+
try {
|
|
2615
|
+
for (const f of fs.readdirSync(path.join(dir, 'assets')).filter((f) => f.endsWith('.json')))
|
|
2616
|
+
sources.set(`assets/${f}`, JSON.parse(fs.readFileSync(path.join(dir, 'assets', f), 'utf8')));
|
|
2617
|
+
}
|
|
2618
|
+
catch { /* no assets */ }
|
|
2619
|
+
r.warnings.push(...unheldFiles(sources));
|
|
2620
|
+
// 5. write it: through a .part folder renamed into place, never over a version that is there
|
|
2621
|
+
const at = path.join(dir, 'versions', version);
|
|
2622
|
+
if (fs.existsSync(at)) {
|
|
2623
|
+
r.blocks.push(`${at} is there already, and a version is never written over: move that folder away (it holds no version.json of ${m.name}), then publish again`);
|
|
2624
|
+
delete r.version;
|
|
2625
|
+
return done();
|
|
2626
|
+
}
|
|
2627
|
+
if (dryRun)
|
|
2628
|
+
return { ...done(), ok: true, hash, files: hashed.length, bytes };
|
|
2629
|
+
// inside a Godot project, Godot imports none of its versions: the .gdignore is there before the first lands
|
|
2630
|
+
godotIgnore(dir, ['versions']);
|
|
2631
|
+
const info = { package: m.name, version, note, published: new Date().toISOString(), big: !!o.big, hash, outputs, default: def, topotopo: TOPOTOPO_VERSION };
|
|
2632
|
+
const part = path.join(dir, 'versions', `.${version}.${process.pid}-${Date.now().toString(36)}.part`);
|
|
2633
|
+
try {
|
|
2634
|
+
for (const f of hashed) {
|
|
2635
|
+
const dest = path.join(part, ...f.rel.split('/'));
|
|
2636
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
2637
|
+
fs.writeFileSync(dest, f.bytes);
|
|
2638
|
+
}
|
|
2639
|
+
fs.writeFileSync(path.join(part, 'version.json'), JSON.stringify(info, null, 2) + '\n');
|
|
2640
|
+
renameInto(part, at);
|
|
2641
|
+
}
|
|
2642
|
+
catch (e) {
|
|
2643
|
+
fs.rmSync(part, { recursive: true, force: true });
|
|
2644
|
+
throw e;
|
|
2645
|
+
}
|
|
2646
|
+
return { ...done(), ok: true, version, dir: at, hash, files: hashed.length, bytes };
|
|
2647
|
+
}
|
|
2648
|
+
/**
|
|
2649
|
+
* An output's kind and tags, as every listing says them: "mesh [conifer, low-poly]", "instances" without tags. A kind
|
|
2650
|
+
* not known (a working folder's output that pins none) is "kind not pinned".
|
|
2651
|
+
*/
|
|
2652
|
+
export const kindTagsText = (o) => `${o.kind ?? 'kind not pinned'}${o.tags?.length ? ` [${o.tags.join(', ')}]` : ''}${o.maps ? ` ${mapsText(o.maps)}` : ''}`;
|
|
2653
|
+
/** A material output's maps in a few words: "maps baseColor 2048, normal 4096" (with the material when it has several). */
|
|
2654
|
+
export function mapsText(maps) {
|
|
2655
|
+
const several = Object.keys(maps).length > 1;
|
|
2656
|
+
const parts = Object.entries(maps).flatMap(([m, slots]) => Object.entries(slots).map(([slot, [w, h]]) => `${several ? `${m} ` : ''}${slot} ${w === h ? w : `${w}×${h}`}`));
|
|
2657
|
+
return parts.length ? `maps ${parts.join(', ')}` : 'no maps';
|
|
2658
|
+
}
|
|
2659
|
+
/** The outputs of version `b` whose kind differs from version `a`'s: 'output "pine": mesh → scene'. */
|
|
2660
|
+
export function kindChanges(a, b) {
|
|
2661
|
+
const out = [];
|
|
2662
|
+
const one = (what, x, y) => { if (x && y && x.kind !== y.kind)
|
|
2663
|
+
out.push(`${what}: ${x.kind} → ${y.kind}`); };
|
|
2664
|
+
for (const [k, o] of Object.entries(b.outputs))
|
|
2665
|
+
one(`output "${k}"`, a.outputs[k], o);
|
|
2666
|
+
const named = (v) => defaultOutputName(v) !== null;
|
|
2667
|
+
if (!named(a) && !named(b))
|
|
2668
|
+
one('the default output', a.default, b.default);
|
|
2669
|
+
return out;
|
|
2670
|
+
}
|
|
2671
|
+
/** A publish result as the CLI and the workspace tool say it; a dry run says what publishing would do. */
|
|
2672
|
+
export function publishText(r) {
|
|
2673
|
+
const kind = !r.previous ? 'the first version' : r.bigBecause.length ? `big, after ${r.previous}` : `small, after ${r.previous}`;
|
|
2674
|
+
const said = [
|
|
2675
|
+
...(r.outputs ? ['outputs:', ...Object.entries(r.outputs).map(([k, o]) => ` ${k} ${kindTagsText(o)}${o.label ? ` "${o.label}"` : ''}`)] : []),
|
|
2676
|
+
...(r.default && r.outputs && defaultOutputName({ outputs: r.outputs, default: r.default }) === null ? [` (default: "${r.default.node}" of graph "${r.default.graph}") ${kindTagsText(r.default)}`] : []),
|
|
2677
|
+
...(r.bigBecause.length ? ['big because:', ...r.bigBecause.map((c) => ` ${c}`)] : []),
|
|
2678
|
+
...(r.changes.length ? ['changes:', ...r.changes.map((c) => ` ${c}`)] : []),
|
|
2679
|
+
...(r.warnings.length ? ['warnings:', ...r.warnings.map((w) => ` ${w}`)] : []),
|
|
2680
|
+
];
|
|
2681
|
+
if (r.dryRun) {
|
|
2682
|
+
const number = r.version ? `${r.package} ${r.version} (${kind})` : r.package || 'the package';
|
|
2683
|
+
const noted = r.note ? `: "${r.note}"` : '; publishing it needs a note, one line on what changed (--note "...")';
|
|
2684
|
+
const problems = `${r.blocks.length} problem${r.blocks.length === 1 ? '' : 's'}`;
|
|
2685
|
+
return [
|
|
2686
|
+
r.ok ? `✓ would publish ${number}${noted}` : `✗ would not publish ${r.package || 'the package'} — ${problems}:`,
|
|
2687
|
+
...(r.ok ? [] : r.blocks.map((b) => ` ${b}`)),
|
|
2688
|
+
...(r.ok && r.hash ? [` ${r.files} files, ${((r.bytes ?? 0) / 1024).toFixed(1)} KB, hash ${r.hash.slice(0, 16)}…`] : []),
|
|
2689
|
+
...said,
|
|
2690
|
+
'a dry run: nothing was written',
|
|
2691
|
+
].join('\n');
|
|
2692
|
+
}
|
|
2693
|
+
if (!r.ok)
|
|
2694
|
+
return [`✗ not published — ${r.blocks.length} problem${r.blocks.length === 1 ? '' : 's'}:`, ...r.blocks.map((b) => ` ${b}`), ...(r.warnings.length ? ['warnings:', ...r.warnings.map((w) => ` ${w}`)] : [])].join('\n');
|
|
2695
|
+
return [
|
|
2696
|
+
`✓ published ${r.package} ${r.version} (${kind}): "${r.note}"`,
|
|
2697
|
+
` ${r.dir}: ${r.files} files, ${((r.bytes ?? 0) / 1024).toFixed(1)} KB, hash ${r.hash.slice(0, 16)}…`,
|
|
2698
|
+
...said,
|
|
2699
|
+
].join('\n');
|
|
2700
|
+
}
|
|
2701
|
+
/** How many outputs a version publishes: its named outputs, and its default output when it is none of them. */
|
|
2702
|
+
const outputCount = (v) => {
|
|
2703
|
+
const named = Object.values(v.outputs);
|
|
2704
|
+
const n = named.length + (defaultOutputName(v) !== null ? 0 : 1);
|
|
2705
|
+
return `${n} output${n === 1 ? '' : 's'}`;
|
|
2706
|
+
};
|
|
2707
|
+
/** How a package in use stands to its libraries: "up to date", "1.3 is out", "2.0 is out (big)". */
|
|
2708
|
+
const standing = (o) => o.error ? 'could not check' : o.small || o.big ? [o.small ? `${o.small} is out` : '', o.big ? `${o.big} is out (big)` : ''].filter(Boolean).join(', ') : 'up to date';
|
|
2709
|
+
/** "; also in library "game", not used": the later places that have a package too. */
|
|
2710
|
+
const alsoText = (also) => (also?.length ? `; also in ${also.join(', ')}, not used` : '');
|
|
2711
|
+
/** The places a lookup looks in, as the packages view ends with them, and how to list a shared library. */
|
|
2712
|
+
function placesText(libs, mcp) {
|
|
2713
|
+
const how = mcp ? 'workspace {action:"libraries", add}, when the person says so' : `${program()} workspace library add <name or folder>${libs.workspace ? workspaceFlag(libs.workspace) : ''}`;
|
|
2714
|
+
const hint = libs.workspace
|
|
2715
|
+
? (libs.libs.some((l) => l.from === 'listed') ? '' : `; the workspace lists no shared library (${how} lists one)`)
|
|
2716
|
+
: `; outside a workspace every registered library counts${libs.libs.some((l) => l.from === 'registered') ? '' : ` (none is registered: ${program()} library add <name> <folder>)`}`;
|
|
2717
|
+
return `looks in: ${placesLine(libs.libs)}${hint}`;
|
|
2718
|
+
}
|
|
2719
|
+
/**
|
|
2720
|
+
* The packages a package uses and can use, as `topotopo packages` and the workspace tool list them, one line each: those
|
|
2721
|
+
* it uses (version, outputs, up to date or the newer version that is out), then the others the places it looks in give,
|
|
2722
|
+
* each with its place (and the later places that have it too, not used); the places; what could not be checked. At a
|
|
2723
|
+
* workspace's root, in no package, the same for the workspace. `packages owner/name` (packageText) shows one with its
|
|
2724
|
+
* outputs.
|
|
2725
|
+
*/
|
|
2726
|
+
export function packagesText(pk, mcp = false) {
|
|
2727
|
+
const ws = pk.dir ? null : locate(pk.start).workspace;
|
|
2728
|
+
if (!pk.dir && !ws)
|
|
2729
|
+
return `this folder is in no package: ${makePackage()}, whose graphs can use packages`;
|
|
2730
|
+
if (pk.dir && !pk.manifest)
|
|
2731
|
+
return `${manifestFile(pk.dir)}: ${pk.error}`;
|
|
2732
|
+
const m = pk.manifest, lines = [];
|
|
2733
|
+
if (pk.dir) {
|
|
2734
|
+
lines.push(`${pk.label} (${pk.dir})${m.name ? `, the package ${m.name}` : ''}`);
|
|
2735
|
+
if (pk.store?.workspace)
|
|
2736
|
+
lines.push(`in ${pk.holder} (${pk.store.workspace}): its ${WORKSPACE_FILE} names the versions every package in it uses, one copy of each (${WORKSPACE_PACKAGES}/)`);
|
|
2737
|
+
}
|
|
2738
|
+
else
|
|
2739
|
+
lines.push(`${pk.who} (${ws}), at its root, in no package: its ${WORKSPACE_FILE} names the versions every package in it uses, one copy of each (${WORKSPACE_PACKAGES}/)`);
|
|
2740
|
+
const problems = pk.dir ? [...pk.verifyCopies(), ...pk.check()] : [];
|
|
2741
|
+
let uses = {};
|
|
2742
|
+
try {
|
|
2743
|
+
uses = pk.usesHere();
|
|
2744
|
+
}
|
|
2745
|
+
catch (e) {
|
|
2746
|
+
problems.push(e.message);
|
|
2747
|
+
}
|
|
2748
|
+
const outdated = Object.keys(uses).length ? pk.outdated(problems) : [];
|
|
2749
|
+
for (const o of outdated)
|
|
2750
|
+
if (o.error)
|
|
2751
|
+
problems.push(`${o.package}: ${o.error}`);
|
|
2752
|
+
const late = outdated.filter((o) => o.small || o.big).length, unchecked = outdated.filter((o) => o.error).length;
|
|
2753
|
+
lines.push(outdated.length
|
|
2754
|
+
? `uses ${outdated.length} package${outdated.length === 1 ? '' : 's'}: ${[late ? `${late} out of date` : '', outdated.length - late - unchecked ? `${outdated.length - late - unchecked} up to date` : '', unchecked ? `could not check ${unchecked}` : ''].filter(Boolean).join(', ')}`
|
|
2755
|
+
: `uses no packages yet: a graph that names "owner/name/output" adds the package (${mcp ? 'workspace {action:"use", package}' : `${program()} use owner/name`} adds one by hand)`);
|
|
2756
|
+
const width = Math.max(0, ...outdated.map((o) => `${o.package} ${o.version}`.length));
|
|
2757
|
+
for (const o of outdated) {
|
|
2758
|
+
const info = pk.copyInfo(o.package, o.version);
|
|
2759
|
+
lines.push(` ${`${o.package} ${o.version}`.padEnd(width)} ${info ? outputCount(info) : 'COPY MISSING'} ${standing(o)}${alsoText(o.also)}`);
|
|
2760
|
+
}
|
|
2761
|
+
const indirect = pk.lockEntries().filter((e) => !e.direct);
|
|
2762
|
+
if (indirect.length)
|
|
2763
|
+
lines.push(` and, used by those: ${indirect.map((e) => `${e.package} ${e.version}`).join(', ')}`);
|
|
2764
|
+
// the others the places give
|
|
2765
|
+
let cat = [];
|
|
2766
|
+
try {
|
|
2767
|
+
cat = pk.catalog(problems);
|
|
2768
|
+
}
|
|
2769
|
+
catch (e) {
|
|
2770
|
+
problems.push(e.message);
|
|
2771
|
+
}
|
|
2772
|
+
const held = new Set(pk.lockEntries().map((e) => e.package));
|
|
2773
|
+
const others = cat.filter((c) => !held.has(c.package) && uses[c.package] === undefined && c.package !== m?.name);
|
|
2774
|
+
if (others.length) {
|
|
2775
|
+
lines.push(`in the places it looks in, not used yet (${others.length}):`);
|
|
2776
|
+
const w2 = Math.max(0, ...others.map((c) => `${c.package} ${c.versions.at(-1)?.version ?? ''}`.length));
|
|
2777
|
+
for (const c of others) {
|
|
2778
|
+
const v = c.versions.at(-1);
|
|
2779
|
+
lines.push(` ${`${c.package} ${v?.version ?? ''}`.padEnd(w2)} ${v ? outputCount(v) : 'no version published yet'} [${c.place}]${alsoText(c.also)}`);
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
const followed = pk.following();
|
|
2783
|
+
if (followed.length)
|
|
2784
|
+
lines.push('following this session:', ...followed.map((f) => ` ${f.package} ${f.dir} (${f.place})`));
|
|
2785
|
+
let libs = { libs: [], problems: [], workspace: null, self: null };
|
|
2786
|
+
try {
|
|
2787
|
+
libs = pk.libraries();
|
|
2788
|
+
}
|
|
2789
|
+
catch (e) {
|
|
2790
|
+
problems.push(e.message);
|
|
2791
|
+
}
|
|
2792
|
+
lines.push(placesText(libs, mcp));
|
|
2793
|
+
const said = [...new Set(problems)];
|
|
2794
|
+
if (said.length)
|
|
2795
|
+
lines.push(`could not check ${said.length}:`, ...said.map((p) => ` ${p}`));
|
|
2796
|
+
lines.push(mcp ? 'workspace {action:"packages", package:"owner/name"} shows one with its outputs; {action:"outdated"} the notes of the newer versions' : `${program()} packages owner/name shows one with its outputs; ${program()} outdated the notes of the newer versions`);
|
|
2797
|
+
return lines.join('\n');
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* One package in the places this package looks in (`topotopo packages owner/name`): where it is, the version the
|
|
2801
|
+
* package uses, its versions with their notes, and the outputs of the version in use (else of the newest) with their
|
|
2802
|
+
* kinds, tags, params and inputs, by the node type a graph names them with. At a workspace's root, for the workspace.
|
|
2803
|
+
*/
|
|
2804
|
+
export function packageText(pk, pkg, mcp = false) {
|
|
2805
|
+
if (pk.dir || !locate(pk.start).workspace)
|
|
2806
|
+
pk.package();
|
|
2807
|
+
const n = parsePackageName(pkg);
|
|
2808
|
+
if (typeof n === 'string' || n.output !== null)
|
|
2809
|
+
throw new Error(`"${pkg}" is not a package name: write owner/name`);
|
|
2810
|
+
const problems = [];
|
|
2811
|
+
const all = pk.catalog(problems), c = all.find((x) => x.package === pkg);
|
|
2812
|
+
const used = pk.usesHere()[pkg], inUse = used ? pk.copyInfo(pkg, used) : null;
|
|
2813
|
+
if (!c && !inUse) {
|
|
2814
|
+
const s = didYouMean(pkg, all.map((x) => x.package));
|
|
2815
|
+
throw new Error(`no place ${pk.dir ? 'this package' : pk.who} looks in has a package ${pkg}${s.length ? ` — did you mean ${s.join(', ')}?` : ''}${problems.length ? `; could not check ${problems.length}: ${problems.join('; ')}` : ''}`);
|
|
2816
|
+
}
|
|
2817
|
+
const versions = c?.versions ?? [];
|
|
2818
|
+
const shown = inUse ?? versions.at(-1);
|
|
2819
|
+
const who = pk.dir ? pk.label : pk.who;
|
|
2820
|
+
const lines = [`${pkg}${c ? ` in ${c.place} (${c.dir})` : ''}${used ? `: ${who} uses ${used}` : `: ${who} does not use it yet (a graph that names one of its outputs adds it)`}${alsoText(c?.also)}`];
|
|
2821
|
+
if (versions.length)
|
|
2822
|
+
lines.push('versions:', ...versions.map((v) => ` ${v.version} "${v.note}"${v.version === used ? ' (in use)' : ''}`));
|
|
2823
|
+
else if (!inUse)
|
|
2824
|
+
lines.push('no version published yet');
|
|
2825
|
+
if (shown) {
|
|
2826
|
+
lines.push(`outputs of ${shown.version}:`);
|
|
2827
|
+
const isDefault = (o) => isDefaultOutput(shown, o);
|
|
2828
|
+
const one = (type, o) => {
|
|
2829
|
+
const params = Object.keys(o.sliders), inputs = o.inputs.map((i) => i.label || `input ${i.index}`);
|
|
2830
|
+
return ` ${type} ${kindTagsText(o)}${o.label ? ` "${o.label}"` : ''}${params.length ? ` params ${params.join(', ')}` : ''}${inputs.length ? ` inputs ${inputs.join(', ')}` : ''}${isDefault(o) ? ` (also ${pkg}, its default output)` : ''}`;
|
|
2831
|
+
};
|
|
2832
|
+
if (!Object.values(shown.outputs).some(isDefault))
|
|
2833
|
+
lines.push(one(pkg, shown.default));
|
|
2834
|
+
for (const [k, o] of Object.entries(shown.outputs))
|
|
2835
|
+
lines.push(one(`${pkg}/${k}`, o));
|
|
2836
|
+
const first = Object.keys(shown.outputs)[0], example = first ? `${pkg}/${first}` : pkg;
|
|
2837
|
+
lines.push(mcp ? `help {nodes:["${example}"]} gives an output's params and inputs` : `${program()} --help-node ${example} gives an output's params and inputs`);
|
|
2838
|
+
}
|
|
2839
|
+
if (problems.length)
|
|
2840
|
+
lines.push(`could not check ${problems.length}:`, ...problems.map((p) => ` ${p}`));
|
|
2841
|
+
return lines.join('\n');
|
|
2842
|
+
}
|
|
2843
|
+
/**
|
|
2844
|
+
* Search the outputs of the newest version of every package the places a folder's package looks in give (its
|
|
2845
|
+
* workspace and the shared libraries the workspace lists, or outside a workspace the library it is in and every
|
|
2846
|
+
* registered library; then TopoTopo's built-in library), by words, kind and tag; inside a workspace also the registered
|
|
2847
|
+
* libraries it does not list, said as such (the person lists one: the tools never do). A name later places have too is
|
|
2848
|
+
* found in the first, which says so. `start`: the open package's folder, or any folder (a workspace's root uses the
|
|
2849
|
+
* workspace's lookup). Throws for a kind that is none.
|
|
2850
|
+
*/
|
|
2851
|
+
export function searchPackages(start, q, opts = {}) {
|
|
2852
|
+
if (q.kind !== undefined && !isKind(q.kind))
|
|
2853
|
+
throw new Error(`"${q.kind}" is not a kind: ${KINDS.join(', ')}`);
|
|
2854
|
+
const problems = new Set();
|
|
2855
|
+
const builtin = path.resolve(opts.builtin ?? BUILTIN_LIBRARY.path);
|
|
2856
|
+
const dir = packageDirOf(start);
|
|
2857
|
+
let manifest = null, uses = {};
|
|
2858
|
+
const store = dir ? copiesFor(dir) : locate(start).workspace ? copiesFor(locate(start).workspace) : null;
|
|
2859
|
+
if (dir) {
|
|
2860
|
+
try {
|
|
2861
|
+
manifest = readManifest(dir);
|
|
2862
|
+
}
|
|
2863
|
+
catch (e) {
|
|
2864
|
+
problems.add(e.message);
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
if (store) {
|
|
2868
|
+
try {
|
|
2869
|
+
uses = readUses(store);
|
|
2870
|
+
}
|
|
2871
|
+
catch (e) {
|
|
2872
|
+
problems.add(e.message);
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
const scanned = scanPlaces(dir ?? start, builtin, store);
|
|
2876
|
+
for (const p of scanned.problems)
|
|
2877
|
+
problems.add(p);
|
|
2878
|
+
const standingOf = (l) => l.from;
|
|
2879
|
+
const libs = [
|
|
2880
|
+
...scanned.libs.map((l) => ({ name: l.name, place: placeText(l), root: l.root, standing: standingOf(l) })),
|
|
2881
|
+
{ name: BUILTIN_LIBRARY.name, place: BUILTIN_TEXT, root: builtin, standing: 'builtin' },
|
|
2882
|
+
];
|
|
2883
|
+
// in a workspace: the registered libraries it does not list, whose packages it does not use; not one inside the
|
|
2884
|
+
// workspace or a library it lists (its packages are found there already), nor one holding the workspace (which the
|
|
2885
|
+
// workspace cannot list), and no package folder a place looked in reaches already
|
|
2886
|
+
const unlisted = [];
|
|
2887
|
+
if (scanned.workspace) {
|
|
2888
|
+
const seen = new Set(scanned.libs.map((l) => folderKey(l.root)));
|
|
2889
|
+
const reached = new Set(scanned.packages.map((p) => folderKey(p.dir)));
|
|
2890
|
+
try {
|
|
2891
|
+
for (const l of [...loadConfig().libraries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
2892
|
+
if (seen.has(folderKey(l.path)) || scanned.libs.some((x) => within(l.path, x.root)) || within(scanned.workspace, l.path))
|
|
2893
|
+
continue;
|
|
2894
|
+
seen.add(folderKey(l.path));
|
|
2895
|
+
const scan = scanTree(l.name, l.path), place = `library "${l.name}"`;
|
|
2896
|
+
const folders = scan.packages.flatMap((p) => (p.manifest.name && p.manifest.name.split('/')[0] !== RESERVED_OWNER && !reached.has(folderKey(p.dir)) ? [{ package: p.manifest.name, library: l.name, place, at: folderKey(l.path), dir: p.dir, working: true }] : []));
|
|
2897
|
+
if (!folders.length && scan.packages.some((p) => reached.has(folderKey(p.dir))))
|
|
2898
|
+
continue;
|
|
2899
|
+
for (const p of scan.problems)
|
|
2900
|
+
problems.add(`${place}: ${p}`);
|
|
2901
|
+
unlisted.push({ name: l.name, root: l.path, folders });
|
|
2902
|
+
libs.push({ name: l.name, place, root: l.path, standing: 'unlisted' });
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
catch (e) {
|
|
2906
|
+
problems.add(e.message);
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
// each word of the query starts a word of what an output says about itself or of its package's title and package
|
|
2910
|
+
// tags: "tree" finds trees, not every output of topotopo/street; a package's description, which lists its contents,
|
|
2911
|
+
// would match every output of the package
|
|
2912
|
+
const wordsOf = (s) => s.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
|
|
2913
|
+
const words = wordsOf(String(q.query ?? ''));
|
|
2914
|
+
const hitsOf = (folders, also) => {
|
|
2915
|
+
const hits = [];
|
|
2916
|
+
for (const f of folders) {
|
|
2917
|
+
const place = readVersions(f.dir, f.package, f.library, f.place, problems).at(-1);
|
|
2918
|
+
if (!place)
|
|
2919
|
+
continue;
|
|
2920
|
+
let pm = null;
|
|
2921
|
+
try {
|
|
2922
|
+
pm = readManifest(place.dir);
|
|
2923
|
+
}
|
|
2924
|
+
catch (e) {
|
|
2925
|
+
problems.add(e.message);
|
|
2926
|
+
}
|
|
2927
|
+
const v = place.info, about = [pm?.title ?? '', ...(pm?.tags ?? [])];
|
|
2928
|
+
const isDefault = (o) => isDefaultOutput(v, o);
|
|
2929
|
+
const found = Object.entries(v.outputs).map(([k, o]) => [`${f.package}/${k}`, o, isDefault(o) ? f.package : undefined]);
|
|
2930
|
+
if (!Object.values(v.outputs).some(isDefault))
|
|
2931
|
+
found.unshift([f.package, v.default, undefined]);
|
|
2932
|
+
const later = also(f);
|
|
2933
|
+
for (const [type, o, alias] of found) {
|
|
2934
|
+
const tags = o.tags ?? [];
|
|
2935
|
+
if (q.kind !== undefined && o.kind !== q.kind)
|
|
2936
|
+
continue;
|
|
2937
|
+
if (q.tag !== undefined && !tags.includes(q.tag))
|
|
2938
|
+
continue;
|
|
2939
|
+
const hay = wordsOf([type, alias ?? '', o.label ?? '', o.description ?? '', ...tags, ...about].join(' '));
|
|
2940
|
+
if (!words.every((w) => hay.some((h) => h.startsWith(w))))
|
|
2941
|
+
continue;
|
|
2942
|
+
const used = uses[f.package];
|
|
2943
|
+
hits.push({
|
|
2944
|
+
type, ...(alias ? { alias } : {}), package: f.package, version: v.version, ...(o.label ? { label: o.label } : {}), kind: o.kind, tags,
|
|
2945
|
+
...(o.description ? { description: o.description } : {}), ...(used ? { used } : {}), ...(manifest?.name === f.package ? { self: true } : {}),
|
|
2946
|
+
...(later?.length ? { also: later } : {}),
|
|
2947
|
+
});
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
return hits.sort((a, b) => (a.type < b.type ? -1 : a.type > b.type ? 1 : 0));
|
|
2951
|
+
};
|
|
2952
|
+
// the names a lookup takes, by the place they are taken from (a later place's own copy is not used); a place is its
|
|
2953
|
+
// folder (two places may share a name)
|
|
2954
|
+
const byPlace = new Map();
|
|
2955
|
+
for (const t of scanned.taken.values())
|
|
2956
|
+
if (!t.clash)
|
|
2957
|
+
byPlace.set(t.folder.at, [...(byPlace.get(t.folder.at) ?? []), t.folder]);
|
|
2958
|
+
const libraries = libs.map((lib) => {
|
|
2959
|
+
const folders = lib.standing === 'unlisted' ? unlisted.find((u) => u.name === lib.name).folders : byPlace.get(folderKey(lib.root)) ?? [];
|
|
2960
|
+
return { ...lib, hits: hitsOf(folders, (f) => (lib.standing === 'unlisted' ? undefined : scanned.taken.get(f.package)?.also)) };
|
|
2961
|
+
});
|
|
2962
|
+
const ws = scanned.workspace;
|
|
2963
|
+
return { query: q, package: dir && manifest ? `package ${packageId(dir)}` : null, workspace: ws ? workspaceName(ws) : null, workspaceDir: ws, libraries, problems: [...problems] };
|
|
2964
|
+
}
|
|
2965
|
+
/** A search as the CLI (or, `mcp`, the workspace tool) says it: the hits by place, and whether the package can use them. */
|
|
2966
|
+
export function searchText(r, mcp = false) {
|
|
2967
|
+
const q = r.query, hits = r.libraries.flatMap((l) => l.hits);
|
|
2968
|
+
const asked = [q.query?.trim() ? `"${q.query.trim()}"` : '', q.kind ? `kind ${q.kind}` : '', q.tag ? `tag ${q.tag}` : ''].filter(Boolean).join(', ') || 'everything';
|
|
2969
|
+
const who = r.package ?? (r.workspace ? `the workspace "${r.workspace}"` : null);
|
|
2970
|
+
const lines = [hits.length
|
|
2971
|
+
? `search ${asked}: ${hits.length} output${hits.length === 1 ? '' : 's'} in ${r.libraries.filter((l) => l.hits.length).length} of the ${r.libraries.length} places looked in${who ? `, for ${who}` : ''}`
|
|
2972
|
+
: `search ${asked}: no output matches in ${r.libraries.map((l) => l.place).join(', ')}`];
|
|
2973
|
+
if (!r.package)
|
|
2974
|
+
lines.push(`this folder is in no package, and only a package's graphs use packages: ${mcp ? "workspace {action:\"init\"} makes the server's folder one, when the person says so" : makePackage()}`);
|
|
2975
|
+
for (const l of r.libraries) {
|
|
2976
|
+
if (!l.hits.length)
|
|
2977
|
+
continue;
|
|
2978
|
+
const standing = l.standing === 'builtin' ? 'TopoTopo\'s own packages, which every package can use: a graph that names one adds it'
|
|
2979
|
+
: l.standing === 'self' ? `${who ? `${who} is in it` : 'the folder is in it'}: a graph that names one of these adds its package`
|
|
2980
|
+
: l.standing === 'listed' ? `the workspace lists it: a graph that names one of these adds its package`
|
|
2981
|
+
: l.standing === 'registered' ? `a registered library: outside a workspace every registered library counts, and a graph that names one of these adds its package`
|
|
2982
|
+
: `the workspace "${r.workspace}" does not list it: to use these, ${mcp ? `workspace {action:"libraries", add:"${l.name}"} lists it, when the person says so (the tools never add a library by themselves)` : `${program()} workspace library add ${l.name}${r.workspaceDir ? workspaceFlag(r.workspaceDir) : ''} lists it`}`;
|
|
2983
|
+
lines.push(`${l.standing === 'builtin' ? `TopoTopo's built-in library "${l.name}"` : `${l.place} (${l.root})`}: ${standing}`);
|
|
2984
|
+
for (const h of l.hits) {
|
|
2985
|
+
const also = [h.alias ? `also ${h.alias}, its default output` : '', h.self ? 'this package\'s own output' : h.used ? `${r.package ? 'this package' : 'the workspace'} uses ${h.used}` : '', h.also?.length ? `also in ${h.also.join(', ')}, not used` : ''].filter(Boolean).join('; ');
|
|
2986
|
+
lines.push(` ${h.type} ${kindTagsText(h)}${h.label ? ` "${h.label}"` : ''} ${h.version}${also ? ` (${also})` : ''}`);
|
|
2987
|
+
if (h.description)
|
|
2988
|
+
lines.push(` ${h.description.length > 300 ? `${h.description.slice(0, 299)}…` : h.description}`);
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
if (hits.length && r.libraries.some((l) => !l.hits.length))
|
|
2992
|
+
lines.push(`nothing matches in ${r.libraries.filter((l) => !l.hits.length).map((l) => l.place).join(', ')}`);
|
|
2993
|
+
if (hits.length)
|
|
2994
|
+
lines.push(mcp ? `help {nodes:["${hits[0].type}"]} gives an output's params and inputs` : `${program()} --help-node ${hits[0].type} gives an output's params and inputs`);
|
|
2995
|
+
if (r.problems.length)
|
|
2996
|
+
lines.push(`could not check ${r.problems.length}:`, ...r.problems.map((p) => ` ${p}`));
|
|
2997
|
+
return lines.join('\n');
|
|
2998
|
+
}
|