@hraness/slopcamera 3.2.4
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/LICENSE +21 -0
- package/NOTICE.md +60 -0
- package/PRIVACY.md +46 -0
- package/README.md +311 -0
- package/SECURITY.md +21 -0
- package/apps/desktop/README.md +966 -0
- package/apps/desktop/analysis/protocol.ts +223 -0
- package/apps/desktop/application/capability-binding.ts +594 -0
- package/apps/desktop/application/context.ts +97 -0
- package/apps/desktop/application/creative-iteration.ts +1385 -0
- package/apps/desktop/application/default-registry.ts +146 -0
- package/apps/desktop/application/directing-contract.ts +218 -0
- package/apps/desktop/application/directing-plan.ts +178 -0
- package/apps/desktop/application/errors.ts +18 -0
- package/apps/desktop/application/gateway-port.ts +867 -0
- package/apps/desktop/application/html-overlay-browser-runtime.ts +687 -0
- package/apps/desktop/application/html-overlay-integrity.ts +337 -0
- package/apps/desktop/application/html-overlay-renderer.ts +45 -0
- package/apps/desktop/application/index.ts +13 -0
- package/apps/desktop/application/operation-completion-checkpoint.ts +333 -0
- package/apps/desktop/application/operation-effects.ts +94 -0
- package/apps/desktop/application/operation.ts +224 -0
- package/apps/desktop/application/operations/analysis/faces.ts +244 -0
- package/apps/desktop/application/operations/analysis/music.ts +248 -0
- package/apps/desktop/application/operations/analysis/project-auto-zooms.ts +302 -0
- package/apps/desktop/application/operations/analysis/project-inactivity.ts +381 -0
- package/apps/desktop/application/operations/analysis/scenes.ts +272 -0
- package/apps/desktop/application/operations/analysis/shared.ts +202 -0
- package/apps/desktop/application/operations/derive/edit-batch.ts +967 -0
- package/apps/desktop/application/operations/derive/follow-faces.ts +454 -0
- package/apps/desktop/application/operations/edit/bind-candidate-revision.ts +91 -0
- package/apps/desktop/application/operations/edit/create-candidate-revision.ts +377 -0
- package/apps/desktop/application/operations/edit/create-revision.ts +255 -0
- package/apps/desktop/application/operations/edit/freeze-revision.ts +182 -0
- package/apps/desktop/application/operations/gateway/image.ts +41 -0
- package/apps/desktop/application/operations/gateway/index.ts +17 -0
- package/apps/desktop/application/operations/gateway/shared.ts +122 -0
- package/apps/desktop/application/operations/gateway/speech.ts +41 -0
- package/apps/desktop/application/operations/gateway/transcription.ts +42 -0
- package/apps/desktop/application/operations/gateway/video.ts +41 -0
- package/apps/desktop/application/operations/index.ts +31 -0
- package/apps/desktop/application/operations/iteration/create-candidate.ts +240 -0
- package/apps/desktop/application/operations/iteration/create-matrix.ts +117 -0
- package/apps/desktop/application/operations/iteration/select.ts +155 -0
- package/apps/desktop/application/operations/iteration/shared.ts +250 -0
- package/apps/desktop/application/operations/media/audio-effects.ts +376 -0
- package/apps/desktop/application/operations/media/binding.ts +79 -0
- package/apps/desktop/application/operations/media/capabilities.ts +112 -0
- package/apps/desktop/application/operations/media/color-grade.ts +343 -0
- package/apps/desktop/application/operations/media/html-overlay.ts +802 -0
- package/apps/desktop/application/operations/media/index.ts +8 -0
- package/apps/desktop/application/operations/media/ingest.ts +303 -0
- package/apps/desktop/application/operations/media/overlay.ts +729 -0
- package/apps/desktop/application/operations/media/shared.ts +845 -0
- package/apps/desktop/application/operations/media/transform-platform.ts +120 -0
- package/apps/desktop/application/operations/project/commit-edits.ts +2054 -0
- package/apps/desktop/application/operations/project/promote-selection.ts +495 -0
- package/apps/desktop/application/operations/project/snapshot.ts +95 -0
- package/apps/desktop/application/operations/recording/index.ts +5 -0
- package/apps/desktop/application/operations/recording/pause.ts +34 -0
- package/apps/desktop/application/operations/recording/resume.ts +34 -0
- package/apps/desktop/application/operations/recording/shared.ts +199 -0
- package/apps/desktop/application/operations/recording/start.ts +169 -0
- package/apps/desktop/application/operations/recording/stop.ts +34 -0
- package/apps/desktop/application/operations/render/bind-candidate-output.ts +324 -0
- package/apps/desktop/application/operations/render/materialize-selection.ts +322 -0
- package/apps/desktop/application/operations/render/project-caption-plan.ts +287 -0
- package/apps/desktop/application/operations/render/project-plan.ts +939 -0
- package/apps/desktop/application/operations/render/project-spatial-receipt.ts +70 -0
- package/apps/desktop/application/operations/render/project.ts +1922 -0
- package/apps/desktop/application/operations/shared.ts +67 -0
- package/apps/desktop/application/operations/slopcamera-portable.ts +1188 -0
- package/apps/desktop/application/operations/slopcamera-visuals.ts +784 -0
- package/apps/desktop/application/operations/spatial-project.ts +209 -0
- package/apps/desktop/application/operations/spatial-render.ts +415 -0
- package/apps/desktop/application/operations/spatial-scene.ts +97 -0
- package/apps/desktop/application/operations/studio.ts +143 -0
- package/apps/desktop/application/output-publication-lease.ts +163 -0
- package/apps/desktop/application/project-publication-lease.ts +233 -0
- package/apps/desktop/application/project-store.ts +196 -0
- package/apps/desktop/application/receipts.ts +533 -0
- package/apps/desktop/application/registry.ts +182 -0
- package/apps/desktop/application/spatial-assets.ts +675 -0
- package/apps/desktop/application/spatial-compositor-cadence.ts +23 -0
- package/apps/desktop/application/spatial-project-authority.ts +35 -0
- package/apps/desktop/application/spatial-project-lease.ts +126 -0
- package/apps/desktop/application/spatial-project-render-preparation.ts +225 -0
- package/apps/desktop/application/spatial-project-store.ts +286 -0
- package/apps/desktop/application/spatial-render-projection.ts +201 -0
- package/apps/desktop/application/spatial-render.ts +677 -0
- package/apps/desktop/application/spatial-spz.ts +44 -0
- package/apps/desktop/application/spatial-world-import.ts +135 -0
- package/apps/desktop/application/spatial-world-provenance.ts +46 -0
- package/apps/desktop/application/studio-port.ts +58 -0
- package/apps/desktop/application/verified-receipt-reconciliation.ts +1574 -0
- package/apps/desktop/capture/protocol.ts +689 -0
- package/apps/desktop/cli/analyzer.ts +406 -0
- package/apps/desktop/cli/args.ts +3181 -0
- package/apps/desktop/cli/asset-ingest.ts +747 -0
- package/apps/desktop/cli/atomic-render-effects.ts +210 -0
- package/apps/desktop/cli/atomic-render-platform.ts +205 -0
- package/apps/desktop/cli/atomic-render.ts +50 -0
- package/apps/desktop/cli/audio-analysis.ts +252 -0
- package/apps/desktop/cli/bounded-map.ts +39 -0
- package/apps/desktop/cli/bundle-service.ts +256 -0
- package/apps/desktop/cli/capabilities.ts +212 -0
- package/apps/desktop/cli/capture-bundle.ts +1117 -0
- package/apps/desktop/cli/command-host-resources.ts +251 -0
- package/apps/desktop/cli/commands.ts +6836 -0
- package/apps/desktop/cli/directing-blob.ts +291 -0
- package/apps/desktop/cli/directing-media.ts +517 -0
- package/apps/desktop/cli/directing-quote.ts +89 -0
- package/apps/desktop/cli/directing-service.ts +288 -0
- package/apps/desktop/cli/emoji-assets.ts +538 -0
- package/apps/desktop/cli/errors.ts +29 -0
- package/apps/desktop/cli/face-analysis-service.ts +940 -0
- package/apps/desktop/cli/filter-script.ts +76 -0
- package/apps/desktop/cli/gateway-application-port.ts +1142 -0
- package/apps/desktop/cli/gateway-credential.ts +81 -0
- package/apps/desktop/cli/gateway-media-artifacts.ts +723 -0
- package/apps/desktop/cli/gateway-media-catalog.ts +922 -0
- package/apps/desktop/cli/gateway-media-service.ts +3106 -0
- package/apps/desktop/cli/gateway-media-signature.ts +122 -0
- package/apps/desktop/cli/gateway-provider-options.ts +562 -0
- package/apps/desktop/cli/gateway-scene-provider.ts +391 -0
- package/apps/desktop/cli/help.ts +501 -0
- package/apps/desktop/cli/html-overlay-gpu.ts +97 -0
- package/apps/desktop/cli/html-overlay-renderer.ts +2478 -0
- package/apps/desktop/cli/io.ts +290 -0
- package/apps/desktop/cli/main.ts +123 -0
- package/apps/desktop/cli/media-effects-service.ts +885 -0
- package/apps/desktop/cli/media-ingest-model.ts +364 -0
- package/apps/desktop/cli/media-ingest-platform.ts +227 -0
- package/apps/desktop/cli/media-ingest-program.ts +200 -0
- package/apps/desktop/cli/media-ingest.ts +30 -0
- package/apps/desktop/cli/music-analysis-service.ts +434 -0
- package/apps/desktop/cli/mutation-lock.ts +530 -0
- package/apps/desktop/cli/native-assets.d.ts +12 -0
- package/apps/desktop/cli/native-media-runtime.macos.ts +7 -0
- package/apps/desktop/cli/overlay-playback.ts +177 -0
- package/apps/desktop/cli/paths.ts +265 -0
- package/apps/desktop/cli/portable-surface.ts +242 -0
- package/apps/desktop/cli/project-camera-receipt.ts +112 -0
- package/apps/desktop/cli/project-face-camera.ts +394 -0
- package/apps/desktop/cli/project-inactivity-service.ts +552 -0
- package/apps/desktop/cli/project-media-integrity.ts +121 -0
- package/apps/desktop/cli/project-renderer.ts +1526 -0
- package/apps/desktop/cli/project-service.ts +519 -0
- package/apps/desktop/cli/project-state-transaction.ts +520 -0
- package/apps/desktop/cli/query-limits.ts +1 -0
- package/apps/desktop/cli/recording-controller.ts +1567 -0
- package/apps/desktop/cli/recording-daemon.ts +931 -0
- package/apps/desktop/cli/recording-ref.ts +56 -0
- package/apps/desktop/cli/renamed-environment.ts +6 -0
- package/apps/desktop/cli/renderer.ts +1439 -0
- package/apps/desktop/cli/run-cli-test-helper.ts +60 -0
- package/apps/desktop/cli/scene-analysis-service.ts +879 -0
- package/apps/desktop/cli/spatial-compositor-verifier.ts +213 -0
- package/apps/desktop/cli/spatial-project-service.ts +90 -0
- package/apps/desktop/cli/spatial-scene-service.ts +105 -0
- package/apps/desktop/cli/spatial-world-service.ts +39 -0
- package/apps/desktop/cli/speech-analysis-service.ts +682 -0
- package/apps/desktop/cli/studio-assemble.ts +58 -0
- package/apps/desktop/cli/studio-command.ts +60 -0
- package/apps/desktop/cli/studio-custody.ts +60 -0
- package/apps/desktop/cli/studio-encode.ts +216 -0
- package/apps/desktop/cli/studio-exr.ts +52 -0
- package/apps/desktop/cli/studio-files.ts +179 -0
- package/apps/desktop/cli/studio-output-validation.ts +162 -0
- package/apps/desktop/cli/studio-process.ts +145 -0
- package/apps/desktop/cli/studio-runtime.ts +77 -0
- package/apps/desktop/cli/studio-scaffold.ts +70 -0
- package/apps/desktop/cli/studio-service.ts +301 -0
- package/apps/desktop/cli/studio-spatial-asset.ts +248 -0
- package/apps/desktop/cli/studio-template-names.ts +3 -0
- package/apps/desktop/cli/studio-workflow.ts +19 -0
- package/apps/desktop/cli/time.ts +25 -0
- package/apps/desktop/cli/workflow-code.ts +584 -0
- package/apps/desktop/cli/workflow-runs.ts +576 -0
- package/apps/desktop/code/advanced.ts +139 -0
- package/apps/desktop/code/application-node-planner.ts +1288 -0
- package/apps/desktop/code/compiler.ts +329 -0
- package/apps/desktop/code/contracts.ts +13 -0
- package/apps/desktop/code/creative-recipes.ts +94 -0
- package/apps/desktop/code/define-workflow.ts +115 -0
- package/apps/desktop/code/editing.ts +284 -0
- package/apps/desktop/code/file-candidate-provenance.ts +420 -0
- package/apps/desktop/code/file-candidate.ts +69 -0
- package/apps/desktop/code/graph-builder.ts +10 -0
- package/apps/desktop/code/host-resource-policy.ts +55 -0
- package/apps/desktop/code/plan-contracts.ts +159 -0
- package/apps/desktop/code/planning.ts +361 -0
- package/apps/desktop/code/public.ts +134 -0
- package/apps/desktop/code/reference-projection.ts +62 -0
- package/apps/desktop/code/run-contracts.ts +466 -0
- package/apps/desktop/code/run-store.ts +2478 -0
- package/apps/desktop/code/runtime-identity.ts +328 -0
- package/apps/desktop/code/scheduler.ts +3067 -0
- package/apps/desktop/code/semantic-builder.ts +1436 -0
- package/apps/desktop/code/source-bundle.ts +1641 -0
- package/apps/desktop/code/source-typecheck.ts +211 -0
- package/apps/desktop/code/testing.ts +79 -0
- package/apps/desktop/code/worker-client.ts +1675 -0
- package/apps/desktop/code/worker-effects.ts +141 -0
- package/apps/desktop/code/worker-entry.ts +435 -0
- package/apps/desktop/code/worker-lease-guardian.ts +179 -0
- package/apps/desktop/code/worker-process-identity.ts +484 -0
- package/apps/desktop/code/worker-protocol.ts +211 -0
- package/apps/desktop/code/workflow-effects.ts +132 -0
- package/apps/desktop/contracts/analysis.ts +949 -0
- package/apps/desktop/contracts/edit.ts +576 -0
- package/apps/desktop/contracts/index.ts +9 -0
- package/apps/desktop/contracts/media-effects.ts +139 -0
- package/apps/desktop/contracts/project-render.ts +644 -0
- package/apps/desktop/contracts/project.ts +740 -0
- package/apps/desktop/contracts/recording.ts +1434 -0
- package/apps/desktop/contracts/render.ts +334 -0
- package/apps/desktop/contracts/runtime.ts +155 -0
- package/apps/desktop/contracts/spatial-compositor.ts +58 -0
- package/apps/desktop/contracts/spatial-project.ts +159 -0
- package/apps/desktop/contracts/spatial-world.ts +48 -0
- package/apps/desktop/contracts/video-effects.ts +120 -0
- package/apps/desktop/core/alignment-apply.ts +400 -0
- package/apps/desktop/core/audio-alignment.ts +466 -0
- package/apps/desktop/core/auto-zoom.ts +209 -0
- package/apps/desktop/core/canonical-json.ts +14 -0
- package/apps/desktop/core/emoji.ts +210 -0
- package/apps/desktop/core/events.ts +409 -0
- package/apps/desktop/core/face-framing.ts +533 -0
- package/apps/desktop/core/face-tracks.ts +326 -0
- package/apps/desktop/core/inactivity.ts +137 -0
- package/apps/desktop/core/index.ts +30 -0
- package/apps/desktop/core/intervals.ts +123 -0
- package/apps/desktop/core/montage.ts +236 -0
- package/apps/desktop/core/music-analysis.ts +518 -0
- package/apps/desktop/core/plan.ts +244 -0
- package/apps/desktop/core/project-auto-zoom.ts +75 -0
- package/apps/desktop/core/project-camera-spatial.ts +676 -0
- package/apps/desktop/core/project-camera.ts +403 -0
- package/apps/desktop/core/project-captions.ts +888 -0
- package/apps/desktop/core/project-inactivity.ts +125 -0
- package/apps/desktop/core/project-metadata.ts +927 -0
- package/apps/desktop/core/project-plan.ts +375 -0
- package/apps/desktop/core/project-render-plan.ts +303 -0
- package/apps/desktop/core/project-time.ts +469 -0
- package/apps/desktop/core/render-plan.ts +442 -0
- package/apps/desktop/core/scene-cache.ts +174 -0
- package/apps/desktop/core/scene-sampling.ts +448 -0
- package/apps/desktop/core/spatial-compositor.ts +22 -0
- package/apps/desktop/core/spatial-durability.ts +99 -0
- package/apps/desktop/core/spatial-project.ts +169 -0
- package/apps/desktop/core/spatial-shot-clock.ts +32 -0
- package/apps/desktop/core/speech-analysis.ts +333 -0
- package/apps/desktop/core/storage.ts +970 -0
- package/apps/desktop/core/time-map.ts +91 -0
- package/apps/desktop/core/time.ts +61 -0
- package/apps/desktop/core/video-effects.ts +660 -0
- package/apps/desktop/dist/cli/NebulaSans-Bold-26se8aek.otf +0 -0
- package/apps/desktop/dist/cli/NebulaSans-Bold-bcz7y08t.woff2 +0 -0
- package/apps/desktop/dist/cli/NebulaSans-Book-5ax05zvn.woff2 +0 -0
- package/apps/desktop/dist/cli/NebulaSans-Book-8cenzchw.otf +0 -0
- package/apps/desktop/dist/cli/main.js +5086 -0
- package/apps/desktop/html-overlay/catalog.ts +171 -0
- package/apps/desktop/html-overlay/contracts.ts +372 -0
- package/apps/desktop/html-overlay/execution-profile.ts +77 -0
- package/apps/desktop/html-overlay/index.ts +98 -0
- package/apps/desktop/html-overlay/libraries.ts +263 -0
- package/apps/desktop/html-overlay/random.ts +49 -0
- package/apps/desktop/html-overlay/runtime.ts +813 -0
- package/apps/desktop/html-overlay/scaffolds.ts +792 -0
- package/apps/desktop/html-overlay/spark-runtime.ts +88 -0
- package/apps/desktop/html-overlay/spatial-splat-runtime.ts +60 -0
- package/apps/desktop/html-overlay/spatial.ts +720 -0
- package/apps/desktop/studio/assets/README.md +39 -0
- package/apps/desktop/studio/assets/contracts.ts +129 -0
- package/apps/desktop/studio/assets/network.ts +64 -0
- package/apps/desktop/studio/assets/poly-haven.ts +148 -0
- package/apps/desktop/studio/drivers/blender_driver.py +466 -0
- package/apps/desktop/studio/drivers/cadquery_driver.py +176 -0
- package/apps/desktop/studio/education/driver.py +308 -0
- package/apps/desktop/studio/education/lesson.py +180 -0
- package/apps/desktop/studio/education/toolkit.py +249 -0
- package/apps/desktop/workflows/chaptered-demo.ts +48 -0
- package/apps/desktop/workflows/creative-iteration.ts +107 -0
- package/apps/desktop/workflows/creative-selection.ts +92 -0
- package/apps/desktop/workflows/fragments.ts +486 -0
- package/apps/desktop/workflows/index.ts +93 -0
- package/apps/desktop/workflows/polished-screen-demo.ts +128 -0
- package/apps/desktop/workflows/scene-direction.ts +12 -0
- package/apps/desktop/workflows/social-variants.ts +75 -0
- package/apps/desktop/workflows/talking-head-cleanup.ts +53 -0
- package/dist/NebulaSans-Bold-26se8aek.otf +0 -0
- package/dist/NebulaSans-Bold-bcz7y08t.woff2 +0 -0
- package/dist/NebulaSans-Book-5ax05zvn.woff2 +0 -0
- package/dist/NebulaSans-Book-8cenzchw.otf +0 -0
- package/dist/cli.js +479 -0
- package/dist/code/advanced.js +270 -0
- package/dist/code/index.js +2240 -0
- package/dist/generate.js +24 -0
- package/dist/host-resources.js +26 -0
- package/dist/index-42zsesc1.js +2257 -0
- package/dist/index-7308egqr.js +48 -0
- package/dist/index-8txs6fkn.js +712 -0
- package/dist/index-mcy8z0br.js +192 -0
- package/dist/index-p63wavx0.js +2029 -0
- package/dist/index-r7gdhmsp.js +424 -0
- package/dist/index-sh6xbav6.js +1219 -0
- package/dist/index-z1w83f81.js +4 -0
- package/dist/index-z7239b4h.js +2363 -0
- package/dist/index-zfeg9hmw.js +2013 -0
- package/dist/index.js +241 -0
- package/dist/operations.js +29 -0
- package/dist/skill-install-dh0ntqba.js +10 -0
- package/dist/vectorize/worker.js +142 -0
- package/dist/workflow.js +16 -0
- package/docs/README.md +38 -0
- package/docs/studio.md +215 -0
- package/examples/studio/blender/README.md +26 -0
- package/examples/studio/blender/character.py +152 -0
- package/examples/studio/blender/cloth.py +101 -0
- package/examples/studio/blender/color_chart.py +29 -0
- package/examples/studio/blender/fluid.py +78 -0
- package/examples/studio/blender/import_model.py +74 -0
- package/examples/studio/blender/product.py +53 -0
- package/examples/studio/blender/shaded_street.py +481 -0
- package/examples/studio/blender/studio_scene.py +147 -0
- package/examples/studio/cadquery/README.md +13 -0
- package/examples/studio/cadquery/bracket.py +36 -0
- package/examples/studio/cadquery/import_step.py +12 -0
- package/examples/studio/education/README.md +46 -0
- package/examples/studio/education/lesson.json +99 -0
- package/examples/studio/education/scene.py +7 -0
- package/examples/studio/hybrid-scene.ts +96 -0
- package/examples/studio/native-workflow.ts +14 -0
- package/examples/studio/vgpu/README.md +64 -0
- package/examples/studio/vgpu/heat-field.mjs +290 -0
- package/package.json +304 -0
- package/packages/scene/src/index.ts +1 -0
- package/packages/scene/src/scene.ts +215 -0
- package/schema/diagram.schema.json +334 -0
- package/skills/slopcamera/SKILL.md +45 -0
- package/skills/slopcamera/agents/openai.yaml +4 -0
- package/skills/slopcamera/references/customization.md +77 -0
- package/skills/slopcamera/references/diagrams.md +153 -0
- package/skills/slopcamera/references/directed-scenes.md +42 -0
- package/skills/slopcamera/references/directing-video.md +18 -0
- package/skills/slopcamera/references/educational-video.md +26 -0
- package/skills/slopcamera/references/gateway-media.md +134 -0
- package/skills/slopcamera/references/install.md +62 -0
- package/skills/slopcamera/references/native-studio.md +31 -0
- package/skills/slopcamera/references/reference-led-3d.md +140 -0
- package/skills/slopcamera/references/rubber-stamp-examples/poster-example-1.jpg +0 -0
- package/skills/slopcamera/references/rubber-stamp-examples/poster-example-2.jpg +0 -0
- package/skills/slopcamera/references/rubber-stamp-examples/stamp-style-1.png +0 -0
- package/skills/slopcamera/references/rubber-stamp-examples/stamp-style-2.png +0 -0
- package/skills/slopcamera/references/rubber-stamp-field-notes.md +144 -0
- package/skills/slopcamera/references/vectorization.md +29 -0
- package/skills/slopcamera/references/video-projects.md +187 -0
- package/skills/slopcamera/references/visual-communication.md +120 -0
- package/skills/slopcamera/references/workflows-sdk.md +45 -0
- package/skills/slopcamera/scripts/compose-rubber-stamp-field-note.ts +229 -0
- package/src/artifacts.ts +106 -0
- package/src/assets/fonts/nebula-sans/LICENSE.txt +96 -0
- package/src/assets/fonts/nebula-sans/NebulaSans-Bold.otf +0 -0
- package/src/assets/fonts/nebula-sans/NebulaSans-Bold.woff2 +0 -0
- package/src/assets/fonts/nebula-sans/NebulaSans-Book.otf +0 -0
- package/src/assets/fonts/nebula-sans/NebulaSans-Book.woff2 +0 -0
- package/src/assets/fonts/nebula-sans/PROVENANCE.md +21 -0
- package/src/assets.d.ts +9 -0
- package/src/cli.ts +601 -0
- package/src/cloud-errors.ts +26 -0
- package/src/code/advanced.ts +10 -0
- package/src/code/boundary.ts +21 -0
- package/src/code/canonical-json.ts +129 -0
- package/src/code/compiler.ts +953 -0
- package/src/code/contracts.ts +576 -0
- package/src/code/define-workflow.ts +334 -0
- package/src/code/errors.ts +41 -0
- package/src/code/graph-builder.ts +945 -0
- package/src/code/index.ts +121 -0
- package/src/code/json-snapshot.ts +899 -0
- package/src/code/json-utf8.ts +88 -0
- package/src/code/portable-builder.ts +136 -0
- package/src/code/projection.ts +378 -0
- package/src/code/public-operations.ts +450 -0
- package/src/code/runtime.ts +580 -0
- package/src/code/sha256.ts +36 -0
- package/src/config.ts +180 -0
- package/src/desktop.ts +253 -0
- package/src/fs.ts +10 -0
- package/src/generate.ts +704 -0
- package/src/host-resource-posix.ts +161 -0
- package/src/host-resources.ts +1749 -0
- package/src/icons.ts +58 -0
- package/src/index.ts +200 -0
- package/src/label-layout.ts +130 -0
- package/src/layout.ts +413 -0
- package/src/lint.ts +127 -0
- package/src/mcp/boundary.ts +354 -0
- package/src/mcp/index.ts +33 -0
- package/src/mcp/server.ts +272 -0
- package/src/mcp/tools.ts +963 -0
- package/src/mcp/types.ts +71 -0
- package/src/operations.ts +775 -0
- package/src/parse.ts +861 -0
- package/src/process-environment.ts +17 -0
- package/src/render.ts +437 -0
- package/src/skill-install.ts +49 -0
- package/src/spatial-scene/authoring.ts +27 -0
- package/src/spatial-scene/camera-track.ts +83 -0
- package/src/spatial-scene/contracts.ts +277 -0
- package/src/spatial-scene/evaluate.ts +145 -0
- package/src/spatial-scene/gltf.ts +558 -0
- package/src/spatial-scene/identity.ts +260 -0
- package/src/spatial-scene/index.ts +10 -0
- package/src/spatial-scene/inspect.ts +68 -0
- package/src/spatial-scene/math.ts +280 -0
- package/src/spatial-scene/patch.ts +131 -0
- package/src/spatial-scene/time.ts +53 -0
- package/src/studio/contracts.ts +129 -0
- package/src/studio/index.ts +2 -0
- package/src/studio/plan.ts +156 -0
- package/src/studio/shared.ts +41 -0
- package/src/theme.ts +68 -0
- package/src/tldr.ts +474 -0
- package/src/types.ts +212 -0
- package/src/vectorize/archive.ts +101 -0
- package/src/vectorize/command.ts +797 -0
- package/src/vectorize/index.ts +27 -0
- package/src/vectorize/limits.ts +61 -0
- package/src/vectorize/metrics.ts +351 -0
- package/src/vectorize/pixels.ts +323 -0
- package/src/vectorize/supervisor.ts +339 -0
- package/src/vectorize/svg.ts +188 -0
- package/src/vectorize/tool.ts +542 -0
- package/src/vectorize/types.ts +113 -0
- package/src/vectorize/vectorize.ts +634 -0
- package/src/vectorize/worker-protocol.ts +40 -0
- package/src/vectorize/worker.ts +209 -0
- package/src/version.ts +1 -0
- package/src/workflow.ts +409 -0
|
@@ -0,0 +1,2029 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/vectorize/types.ts
|
|
3
|
+
var vectorizeProfileNames = ["balanced", "detailed", "photo"];
|
|
4
|
+
|
|
5
|
+
class VectorizeError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
details;
|
|
8
|
+
constructor(code, message, details = {}, options) {
|
|
9
|
+
super(message, options);
|
|
10
|
+
this.name = "VectorizeError";
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.details = details;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/vectorize/limits.ts
|
|
17
|
+
var vectorizeHardLimits = Object.freeze({
|
|
18
|
+
maxDecodedPixels: 16777216,
|
|
19
|
+
maxDimension: 4096,
|
|
20
|
+
maxDurationMs: 120000,
|
|
21
|
+
maxInputBytes: 16 * 1024 * 1024,
|
|
22
|
+
maxOutputBytes: 2000000,
|
|
23
|
+
maxPaths: 12000
|
|
24
|
+
});
|
|
25
|
+
var vectorizeDefaultLimits = Object.freeze({
|
|
26
|
+
...vectorizeHardLimits,
|
|
27
|
+
maxDurationMs: 30000
|
|
28
|
+
});
|
|
29
|
+
var limitNames = Object.keys(vectorizeHardLimits);
|
|
30
|
+
function resolveVectorizeLimits(input) {
|
|
31
|
+
const resolved = {
|
|
32
|
+
maxDecodedPixels: input?.maxDecodedPixels ?? vectorizeDefaultLimits.maxDecodedPixels,
|
|
33
|
+
maxDimension: input?.maxDimension ?? vectorizeDefaultLimits.maxDimension,
|
|
34
|
+
maxDurationMs: input?.maxDurationMs ?? vectorizeDefaultLimits.maxDurationMs,
|
|
35
|
+
maxInputBytes: input?.maxInputBytes ?? vectorizeDefaultLimits.maxInputBytes,
|
|
36
|
+
maxOutputBytes: input?.maxOutputBytes ?? vectorizeDefaultLimits.maxOutputBytes,
|
|
37
|
+
maxPaths: input?.maxPaths ?? vectorizeDefaultLimits.maxPaths
|
|
38
|
+
};
|
|
39
|
+
for (const name of limitNames) {
|
|
40
|
+
const value = resolved[name];
|
|
41
|
+
const hardLimit = vectorizeHardLimits[name];
|
|
42
|
+
if (!Number.isInteger(value) || value < 1 || value > hardLimit) {
|
|
43
|
+
throw new VectorizeError("invalid_input", `${name} must be a positive integer no greater than ${hardLimit}.`, { hardLimit, name, value });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return Object.freeze(resolved);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
class VectorizeDeadline {
|
|
50
|
+
#deadline;
|
|
51
|
+
constructor(durationMs) {
|
|
52
|
+
this.#deadline = performance.now() + durationMs;
|
|
53
|
+
}
|
|
54
|
+
assert(stage) {
|
|
55
|
+
if (this.remainingMs() <= 0) {
|
|
56
|
+
throw new VectorizeError("timeout", `Vectorization timed out during ${stage}.`, { stage });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
remainingMs() {
|
|
60
|
+
return Math.max(0, Math.ceil(this.#deadline - performance.now()));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/vectorize/command.ts
|
|
65
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
66
|
+
import { constants } from "fs";
|
|
67
|
+
import {
|
|
68
|
+
lstat,
|
|
69
|
+
mkdtemp,
|
|
70
|
+
open,
|
|
71
|
+
rmdir,
|
|
72
|
+
unlink
|
|
73
|
+
} from "fs/promises";
|
|
74
|
+
import { join } from "path";
|
|
75
|
+
|
|
76
|
+
// src/process-environment.ts
|
|
77
|
+
var gatewayCredentialNames = new Set([
|
|
78
|
+
"AI_GATEWAY_API_KEY",
|
|
79
|
+
"VERCEL_OIDC_TOKEN"
|
|
80
|
+
]);
|
|
81
|
+
function nonGatewayChildEnvironment(source = process.env) {
|
|
82
|
+
const environment = { ...source };
|
|
83
|
+
for (const name of Object.keys(environment)) {
|
|
84
|
+
if (gatewayCredentialNames.has(name.toLocaleUpperCase("en-US"))) {
|
|
85
|
+
delete environment[name];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return environment;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/vectorize/command.ts
|
|
92
|
+
var MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
|
|
93
|
+
var PRIMARY_OUTPUT_READ_BYTES = 64 * 1024;
|
|
94
|
+
var PRIMARY_OUTPUT_POLL_MS = 2;
|
|
95
|
+
var PRIMARY_OUTPUT_EXIT_EMPTY_POLLS = 2;
|
|
96
|
+
var TERMINATION_GRACE_MS = 50;
|
|
97
|
+
var HARD_KILL_WAIT_MS = 500;
|
|
98
|
+
var MAX_INHERITED_FILE_DESCRIPTORS = 16;
|
|
99
|
+
var timeoutMarker = Symbol("bounded-command-timeout");
|
|
100
|
+
var noCommandFailure = Symbol("no-command-failure");
|
|
101
|
+
var activePosixProcessGroups = new Set;
|
|
102
|
+
var workerTerminationForwardingInstalled = false;
|
|
103
|
+
var inheritedCommandFileDescriptors = new AsyncLocalStorage;
|
|
104
|
+
function normalizedInheritedFileDescriptors(value) {
|
|
105
|
+
const descriptors = value ?? [];
|
|
106
|
+
if (descriptors.length > MAX_INHERITED_FILE_DESCRIPTORS || descriptors.some((descriptor, index) => !Number.isSafeInteger(descriptor) || descriptor < 0 || descriptor > 2147483647 || descriptors.indexOf(descriptor) !== index)) {
|
|
107
|
+
throw new VectorizeError("invalid_input", "Inherited vectorizer descriptors must be unique bounded integers.");
|
|
108
|
+
}
|
|
109
|
+
return Object.freeze([...descriptors]);
|
|
110
|
+
}
|
|
111
|
+
async function withInheritedCommandFileDescriptors(descriptors, callback) {
|
|
112
|
+
const normalized = normalizedInheritedFileDescriptors(descriptors);
|
|
113
|
+
return await inheritedCommandFileDescriptors.run(normalized, async () => await callback());
|
|
114
|
+
}
|
|
115
|
+
function forwardVectorizeWorkerTermination() {
|
|
116
|
+
if (process.platform === "win32" || workerTerminationForwardingInstalled) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
workerTerminationForwardingInstalled = true;
|
|
120
|
+
const signals = [
|
|
121
|
+
["SIGHUP", 129],
|
|
122
|
+
["SIGINT", 130],
|
|
123
|
+
["SIGTERM", 143]
|
|
124
|
+
];
|
|
125
|
+
for (const [signal, exitCode] of signals) {
|
|
126
|
+
process.once(signal, () => {
|
|
127
|
+
for (const pid of activePosixProcessGroups) {
|
|
128
|
+
safelyKillPosixProcessGroupByPid(pid, "SIGKILL");
|
|
129
|
+
}
|
|
130
|
+
process.exit(exitCode);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async function runBoundedCommand(command, timeoutMs, failureCode, options = {}) {
|
|
135
|
+
return runBoundedCommandInternal(command, timeoutMs, failureCode, options);
|
|
136
|
+
}
|
|
137
|
+
async function runBoundedPathOutputCommand(commandForOutput, timeoutMs, failureCode, options) {
|
|
138
|
+
if (process.platform === "win32") {
|
|
139
|
+
throw new VectorizeError("tool_platform", "Bounded pathname output is unavailable on Windows.", { platform: process.platform });
|
|
140
|
+
}
|
|
141
|
+
assertPositiveLimit(options.maxOutputBytes, "The command primary-output limit must be positive.");
|
|
142
|
+
if (timeoutMs < 1) {
|
|
143
|
+
throw new VectorizeError("timeout", "VTracer exceeded the conversion time limit.");
|
|
144
|
+
}
|
|
145
|
+
const startedAt = performance.now();
|
|
146
|
+
let anchorHandle;
|
|
147
|
+
let directoryHandle;
|
|
148
|
+
let outputDirectory;
|
|
149
|
+
let readerHandle;
|
|
150
|
+
let result;
|
|
151
|
+
let failure = noCommandFailure;
|
|
152
|
+
try {
|
|
153
|
+
outputDirectory = await mkdtemp(join(options.temporaryRoot, "slopcamera-command-output-"));
|
|
154
|
+
directoryHandle = await open(outputDirectory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
155
|
+
await assertOpenedPrivateDirectory(outputDirectory, directoryHandle);
|
|
156
|
+
const outputPath = join(outputDirectory, "output.svg");
|
|
157
|
+
await createPrivateFifo(outputPath, remainingCommandTime(startedAt, timeoutMs), failureCode);
|
|
158
|
+
anchorHandle = await open(outputPath, constants.O_RDWR | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
159
|
+
readerHandle = await open(outputPath, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
160
|
+
await assertOpenedPrivateFifo(outputPath, anchorHandle, readerHandle);
|
|
161
|
+
await directoryHandle.chmod(320);
|
|
162
|
+
const commandResult = await runBoundedCommandInternal(commandForOutput(outputPath), remainingCommandTime(startedAt, timeoutMs), failureCode, options, {
|
|
163
|
+
handle: readerHandle,
|
|
164
|
+
maximumBytes: options.maxOutputBytes
|
|
165
|
+
});
|
|
166
|
+
if (commandResult.primaryOutput === undefined) {
|
|
167
|
+
throw new VectorizeError(failureCode, "VTracer did not expose its bounded primary output.");
|
|
168
|
+
}
|
|
169
|
+
result = {
|
|
170
|
+
output: commandResult.primaryOutput,
|
|
171
|
+
stderr: commandResult.stderr,
|
|
172
|
+
stdout: commandResult.stdout
|
|
173
|
+
};
|
|
174
|
+
} catch (error) {
|
|
175
|
+
failure = error instanceof VectorizeError ? error : executionError(failureCode, error);
|
|
176
|
+
}
|
|
177
|
+
const cleanupError = await removePrimaryOutputEndpoint(outputDirectory, outputDirectory === undefined ? undefined : join(outputDirectory, "output.svg"), readerHandle, anchorHandle, directoryHandle);
|
|
178
|
+
if (failure !== noCommandFailure) {
|
|
179
|
+
if (cleanupError === undefined)
|
|
180
|
+
throw failure;
|
|
181
|
+
throw new VectorizeError(failure instanceof VectorizeError ? failure.code : failureCode, `${failure instanceof Error ? failure.message : String(failure)} The temporary primary-output endpoint also could not be removed.`, {
|
|
182
|
+
...failure instanceof VectorizeError ? failure.details : {},
|
|
183
|
+
cleanup: String(cleanupError)
|
|
184
|
+
}, { cause: failure instanceof Error ? failure : undefined });
|
|
185
|
+
}
|
|
186
|
+
if (cleanupError !== undefined) {
|
|
187
|
+
throw new VectorizeError(failureCode, "The temporary primary-output endpoint could not be removed.", { cleanup: String(cleanupError) }, { cause: cleanupError instanceof Error ? cleanupError : undefined });
|
|
188
|
+
}
|
|
189
|
+
if (result === undefined) {
|
|
190
|
+
throw new VectorizeError(failureCode, "The bounded command completed without a result.");
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
194
|
+
async function runBoundedCommandInternal(command, timeoutMs, failureCode, options, primaryOutput) {
|
|
195
|
+
if (command.length === 0) {
|
|
196
|
+
throw new VectorizeError("invalid_input", "A bounded command requires a command.");
|
|
197
|
+
}
|
|
198
|
+
if (timeoutMs < 1) {
|
|
199
|
+
throw new VectorizeError("timeout", "VTracer exceeded the conversion time limit.");
|
|
200
|
+
}
|
|
201
|
+
const maxStdoutBytes = options.maxStdoutBytes ?? MAX_COMMAND_OUTPUT_BYTES;
|
|
202
|
+
assertPositiveLimit(maxStdoutBytes, "The command stdout limit must be positive.");
|
|
203
|
+
const inheritedDescriptors = normalizedInheritedFileDescriptors(options.inheritedFileDescriptors ?? inheritedCommandFileDescriptors.getStore());
|
|
204
|
+
let child;
|
|
205
|
+
const ownsProcessGroup = process.platform !== "win32";
|
|
206
|
+
try {
|
|
207
|
+
child = Bun.spawn([...command], {
|
|
208
|
+
detached: ownsProcessGroup,
|
|
209
|
+
env: nonGatewayChildEnvironment(),
|
|
210
|
+
stdio: [
|
|
211
|
+
options.stdin ?? "ignore",
|
|
212
|
+
"pipe",
|
|
213
|
+
"pipe",
|
|
214
|
+
...inheritedDescriptors
|
|
215
|
+
],
|
|
216
|
+
windowsHide: true
|
|
217
|
+
});
|
|
218
|
+
} catch (error) {
|
|
219
|
+
throw executionError(failureCode, error);
|
|
220
|
+
}
|
|
221
|
+
if (process.platform !== "win32") {
|
|
222
|
+
activePosixProcessGroups.add(child.pid);
|
|
223
|
+
}
|
|
224
|
+
const streamAbort = new AbortController;
|
|
225
|
+
let childHasExited = false;
|
|
226
|
+
const childExitTask = child.exited.then((exitCode) => {
|
|
227
|
+
childHasExited = true;
|
|
228
|
+
if (ownsProcessGroup && process.platform !== "win32") {
|
|
229
|
+
safelyKillPosixProcessGroup(child, "SIGKILL");
|
|
230
|
+
}
|
|
231
|
+
return exitCode;
|
|
232
|
+
});
|
|
233
|
+
const stdoutTask = readBoundedText(child.stdout, maxStdoutBytes, streamAbort.signal, "VTracer emitted too much primary output.");
|
|
234
|
+
const stderrTask = readBoundedText(child.stderr, MAX_COMMAND_OUTPUT_BYTES, streamAbort.signal, "VTracer emitted too much diagnostic output.");
|
|
235
|
+
const primaryOutputTask = primaryOutput === undefined ? Promise.resolve(undefined) : readBoundedFifo(primaryOutput.handle, primaryOutput.maximumBytes, streamAbort.signal, () => childHasExited);
|
|
236
|
+
const executionTask = Promise.all([
|
|
237
|
+
childExitTask,
|
|
238
|
+
stdoutTask,
|
|
239
|
+
stderrTask,
|
|
240
|
+
primaryOutputTask
|
|
241
|
+
]).then(([exitCode, stdout, stderr, boundedPrimaryOutput]) => {
|
|
242
|
+
if (exitCode !== 0) {
|
|
243
|
+
throw new VectorizeError(failureCode, [
|
|
244
|
+
`Command failed (${exitCode}): ${command[0] ?? "unknown"}`,
|
|
245
|
+
stderr.trim()
|
|
246
|
+
].filter(Boolean).join(`
|
|
247
|
+
`), { exitCode });
|
|
248
|
+
}
|
|
249
|
+
return boundedPrimaryOutput === undefined ? { stderr, stdout } : { primaryOutput: boundedPrimaryOutput, stderr, stdout };
|
|
250
|
+
});
|
|
251
|
+
let timer;
|
|
252
|
+
const timeoutTask = new Promise((_resolve, reject) => {
|
|
253
|
+
timer = setTimeout(() => reject(timeoutMarker), timeoutMs);
|
|
254
|
+
});
|
|
255
|
+
try {
|
|
256
|
+
return await Promise.race([executionTask, timeoutTask]);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
let cleanupError;
|
|
259
|
+
try {
|
|
260
|
+
await terminateAndWait(child, ownsProcessGroup);
|
|
261
|
+
} catch (caught) {
|
|
262
|
+
cleanupError = caught;
|
|
263
|
+
} finally {
|
|
264
|
+
streamAbort.abort();
|
|
265
|
+
await settlesWithin(Promise.allSettled([stdoutTask, stderrTask, primaryOutputTask]), HARD_KILL_WAIT_MS);
|
|
266
|
+
}
|
|
267
|
+
if (error === timeoutMarker) {
|
|
268
|
+
throw new VectorizeError("timeout", cleanupError === undefined ? "VTracer exceeded the conversion time limit." : "VTracer exceeded the conversion time limit and did not terminate cleanly.", cleanupError === undefined ? {} : { cleanup: String(cleanupError) });
|
|
269
|
+
}
|
|
270
|
+
if (error instanceof VectorizeError)
|
|
271
|
+
throw error;
|
|
272
|
+
if (cleanupError instanceof VectorizeError)
|
|
273
|
+
throw cleanupError;
|
|
274
|
+
throw executionError(failureCode, error);
|
|
275
|
+
} finally {
|
|
276
|
+
if (timer !== undefined)
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
activePosixProcessGroups.delete(child.pid);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
function assertPositiveLimit(value, message) {
|
|
282
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
283
|
+
throw new VectorizeError("invalid_input", message);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function remainingCommandTime(startedAt, timeoutMs) {
|
|
287
|
+
return Math.floor(timeoutMs - (performance.now() - startedAt));
|
|
288
|
+
}
|
|
289
|
+
async function createPrivateFifo(path, timeoutMs, failureCode) {
|
|
290
|
+
await runBoundedCommandInternal(["mkfifo", "-m", "600", path], timeoutMs, failureCode, {});
|
|
291
|
+
}
|
|
292
|
+
async function assertOpenedPrivateDirectory(path, directory) {
|
|
293
|
+
const [pathMetadata, openedMetadata] = await Promise.all([
|
|
294
|
+
lstat(path),
|
|
295
|
+
directory.stat()
|
|
296
|
+
]);
|
|
297
|
+
if (!pathMetadata.isDirectory() || !openedMetadata.isDirectory() || pathMetadata.dev !== openedMetadata.dev || pathMetadata.ino !== openedMetadata.ino) {
|
|
298
|
+
throw new VectorizeError("trace_failed", "The bounded primary-output directory changed during setup.");
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async function assertOpenedPrivateFifo(path, anchor, reader) {
|
|
302
|
+
const [pathMetadata, anchorMetadata, readerMetadata] = await Promise.all([
|
|
303
|
+
lstat(path),
|
|
304
|
+
anchor.stat(),
|
|
305
|
+
reader.stat()
|
|
306
|
+
]);
|
|
307
|
+
if (!pathMetadata.isFIFO() || !anchorMetadata.isFIFO() || !readerMetadata.isFIFO() || pathMetadata.dev !== anchorMetadata.dev || pathMetadata.ino !== anchorMetadata.ino || anchorMetadata.dev !== readerMetadata.dev || anchorMetadata.ino !== readerMetadata.ino) {
|
|
308
|
+
throw new VectorizeError("trace_failed", "The bounded primary-output endpoint changed during setup.");
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
async function removePrimaryOutputEndpoint(directoryPath, path, reader, anchor, directoryHandle) {
|
|
312
|
+
let cleanupError;
|
|
313
|
+
if (directoryPath !== undefined && directoryHandle === undefined) {
|
|
314
|
+
try {
|
|
315
|
+
await rmdir(directoryPath);
|
|
316
|
+
} catch (error) {
|
|
317
|
+
cleanupError ??= error;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (directoryPath !== undefined && directoryHandle !== undefined) {
|
|
321
|
+
await directoryHandle.chmod(448).catch((error) => {
|
|
322
|
+
cleanupError ??= error;
|
|
323
|
+
});
|
|
324
|
+
try {
|
|
325
|
+
const [pathDirectoryMetadata, openedDirectoryMetadata] = await Promise.all([
|
|
326
|
+
lstat(directoryPath),
|
|
327
|
+
directoryHandle.stat()
|
|
328
|
+
]);
|
|
329
|
+
if (!pathDirectoryMetadata.isDirectory() || !openedDirectoryMetadata.isDirectory() || pathDirectoryMetadata.dev !== openedDirectoryMetadata.dev || pathDirectoryMetadata.ino !== openedDirectoryMetadata.ino) {
|
|
330
|
+
throw new VectorizeError("trace_failed", "The bounded primary-output directory changed before cleanup.");
|
|
331
|
+
}
|
|
332
|
+
if (path !== undefined && cleanupError === undefined) {
|
|
333
|
+
const pathMetadata = await lstat(path).catch((error) => {
|
|
334
|
+
if (isFileSystemError(error, "ENOENT"))
|
|
335
|
+
return;
|
|
336
|
+
throw error;
|
|
337
|
+
});
|
|
338
|
+
const openedMetadata = await (reader ?? anchor)?.stat();
|
|
339
|
+
if (pathMetadata === undefined && openedMetadata !== undefined) {
|
|
340
|
+
throw new VectorizeError("trace_failed", "The bounded primary-output endpoint disappeared before cleanup.");
|
|
341
|
+
}
|
|
342
|
+
if (pathMetadata !== undefined) {
|
|
343
|
+
if (!pathMetadata.isFIFO() || openedMetadata !== undefined && (pathMetadata.dev !== openedMetadata.dev || pathMetadata.ino !== openedMetadata.ino)) {
|
|
344
|
+
throw new VectorizeError("trace_failed", "The bounded primary-output endpoint changed before cleanup.");
|
|
345
|
+
}
|
|
346
|
+
await unlink(path);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (cleanupError === undefined)
|
|
350
|
+
await rmdir(directoryPath);
|
|
351
|
+
} catch (error) {
|
|
352
|
+
cleanupError ??= error;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const closes = await Promise.allSettled([
|
|
356
|
+
reader?.close(),
|
|
357
|
+
anchor?.close(),
|
|
358
|
+
directoryHandle?.close()
|
|
359
|
+
]);
|
|
360
|
+
cleanupError ??= closes.find((result) => result.status === "rejected")?.reason;
|
|
361
|
+
return cleanupError;
|
|
362
|
+
}
|
|
363
|
+
async function terminateAndWait(child, ownsProcessGroup) {
|
|
364
|
+
if (process.platform === "win32") {
|
|
365
|
+
await killWindowsProcessTree(child.pid);
|
|
366
|
+
} else if (!ownsProcessGroup) {
|
|
367
|
+
safelyKillChild(child, "SIGTERM");
|
|
368
|
+
await delay(TERMINATION_GRACE_MS);
|
|
369
|
+
safelyKillChild(child, "SIGKILL");
|
|
370
|
+
} else {
|
|
371
|
+
safelyKillPosixProcessGroup(child, "SIGTERM");
|
|
372
|
+
await delay(TERMINATION_GRACE_MS);
|
|
373
|
+
safelyKillPosixProcessGroup(child, "SIGKILL");
|
|
374
|
+
}
|
|
375
|
+
if (await settlesWithin(child.exited, HARD_KILL_WAIT_MS))
|
|
376
|
+
return;
|
|
377
|
+
throw new VectorizeError("trace_failed", "VTracer did not exit after forced termination.");
|
|
378
|
+
}
|
|
379
|
+
function safelyKillChild(child, signal) {
|
|
380
|
+
try {
|
|
381
|
+
child.kill(signal);
|
|
382
|
+
} catch {}
|
|
383
|
+
}
|
|
384
|
+
function safelyKillPosixProcessGroup(child, signal) {
|
|
385
|
+
if (!safelyKillPosixProcessGroupByPid(child.pid, signal)) {
|
|
386
|
+
try {
|
|
387
|
+
child.kill(signal);
|
|
388
|
+
} catch {}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
function safelyKillPosixProcessGroupByPid(pid, signal) {
|
|
392
|
+
try {
|
|
393
|
+
process.kill(-pid, signal);
|
|
394
|
+
return true;
|
|
395
|
+
} catch {
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
async function killWindowsProcessTree(pid) {
|
|
400
|
+
let killer;
|
|
401
|
+
try {
|
|
402
|
+
killer = Bun.spawn(["taskkill.exe", "/PID", String(pid), "/T", "/F"], {
|
|
403
|
+
detached: false,
|
|
404
|
+
env: nonGatewayChildEnvironment(),
|
|
405
|
+
stderr: "pipe",
|
|
406
|
+
stdin: "ignore",
|
|
407
|
+
stdout: "pipe",
|
|
408
|
+
windowsHide: true
|
|
409
|
+
});
|
|
410
|
+
} catch {
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const drain = Promise.all([
|
|
414
|
+
readBoundedText(killer.stdout, MAX_COMMAND_OUTPUT_BYTES, AbortSignal.timeout(HARD_KILL_WAIT_MS), "Process-tree cleanup emitted too much output."),
|
|
415
|
+
readBoundedText(killer.stderr, MAX_COMMAND_OUTPUT_BYTES, AbortSignal.timeout(HARD_KILL_WAIT_MS), "Process-tree cleanup emitted too much output.")
|
|
416
|
+
]);
|
|
417
|
+
if (!await settlesWithin(Promise.all([killer.exited, drain]), HARD_KILL_WAIT_MS)) {
|
|
418
|
+
try {
|
|
419
|
+
killer.kill("SIGKILL");
|
|
420
|
+
} catch {}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
async function settlesWithin(promise, durationMs) {
|
|
424
|
+
return new Promise((resolve) => {
|
|
425
|
+
let finished = false;
|
|
426
|
+
const timer = setTimeout(() => finish(false), durationMs);
|
|
427
|
+
promise.then(() => finish(true), () => finish(true));
|
|
428
|
+
function finish(settled) {
|
|
429
|
+
if (finished)
|
|
430
|
+
return;
|
|
431
|
+
finished = true;
|
|
432
|
+
clearTimeout(timer);
|
|
433
|
+
resolve(settled);
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
async function readBoundedText(stream, maximumBytes, signal, limitMessage) {
|
|
438
|
+
const reader = stream.getReader();
|
|
439
|
+
const chunks = [];
|
|
440
|
+
let bytes = 0;
|
|
441
|
+
const cancel = () => {
|
|
442
|
+
reader.cancel().catch(() => {
|
|
443
|
+
return;
|
|
444
|
+
});
|
|
445
|
+
};
|
|
446
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
447
|
+
try {
|
|
448
|
+
while (true) {
|
|
449
|
+
const { done, value } = await reader.read();
|
|
450
|
+
if (done)
|
|
451
|
+
break;
|
|
452
|
+
bytes += value.byteLength;
|
|
453
|
+
if (bytes > maximumBytes) {
|
|
454
|
+
await reader.cancel();
|
|
455
|
+
throw new VectorizeError("output_limit", limitMessage, {
|
|
456
|
+
bytes,
|
|
457
|
+
maximumBytes
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
chunks.push(value);
|
|
461
|
+
}
|
|
462
|
+
return Buffer.concat(chunks, bytes).toString("utf8");
|
|
463
|
+
} finally {
|
|
464
|
+
signal.removeEventListener("abort", cancel);
|
|
465
|
+
reader.releaseLock();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async function readBoundedFifo(handle, maximumBytes, signal, childHasExited) {
|
|
469
|
+
const buffer = Buffer.allocUnsafe(Math.min(PRIMARY_OUTPUT_READ_BYTES, maximumBytes + 1));
|
|
470
|
+
const chunks = [];
|
|
471
|
+
let bytes = 0;
|
|
472
|
+
let emptyPollsAfterExit = 0;
|
|
473
|
+
while (!signal.aborted) {
|
|
474
|
+
const maximumRead = Math.min(buffer.byteLength, maximumBytes - bytes + 1);
|
|
475
|
+
try {
|
|
476
|
+
const { bytesRead } = await handle.read(buffer, 0, maximumRead, null);
|
|
477
|
+
if (bytesRead > 0) {
|
|
478
|
+
emptyPollsAfterExit = 0;
|
|
479
|
+
bytes += bytesRead;
|
|
480
|
+
if (bytes > maximumBytes) {
|
|
481
|
+
throw new VectorizeError("output_limit", "VTracer emitted too much primary output.", { bytes, maximumBytes });
|
|
482
|
+
}
|
|
483
|
+
chunks.push(Uint8Array.from(buffer.subarray(0, bytesRead)));
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
} catch (error) {
|
|
487
|
+
if (!isWouldBlockError(error))
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
if (childHasExited()) {
|
|
491
|
+
emptyPollsAfterExit += 1;
|
|
492
|
+
if (emptyPollsAfterExit >= PRIMARY_OUTPUT_EXIT_EMPTY_POLLS)
|
|
493
|
+
break;
|
|
494
|
+
} else {
|
|
495
|
+
emptyPollsAfterExit = 0;
|
|
496
|
+
}
|
|
497
|
+
await delay(PRIMARY_OUTPUT_POLL_MS);
|
|
498
|
+
}
|
|
499
|
+
return Buffer.concat(chunks, bytes).toString("utf8");
|
|
500
|
+
}
|
|
501
|
+
function isWouldBlockError(error) {
|
|
502
|
+
return isFileSystemError(error) && ["EAGAIN", "EINTR", "EWOULDBLOCK"].includes(String(error.code));
|
|
503
|
+
}
|
|
504
|
+
function isFileSystemError(error, code) {
|
|
505
|
+
return error instanceof Error && "code" in error && (code === undefined || error.code === code);
|
|
506
|
+
}
|
|
507
|
+
function delay(durationMs) {
|
|
508
|
+
return new Promise((resolve) => {
|
|
509
|
+
setTimeout(resolve, durationMs);
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
function executionError(failureCode, cause) {
|
|
513
|
+
return new VectorizeError(failureCode, "VTracer could not be executed.", {}, { cause: cause instanceof Error ? cause : new Error(String(cause)) });
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// src/vectorize/tool.ts
|
|
517
|
+
import { createHash as createHash2, randomUUID } from "crypto";
|
|
518
|
+
import { constants as constants2 } from "fs";
|
|
519
|
+
import {
|
|
520
|
+
chmod,
|
|
521
|
+
mkdir,
|
|
522
|
+
open as open2,
|
|
523
|
+
realpath,
|
|
524
|
+
rename,
|
|
525
|
+
rm,
|
|
526
|
+
writeFile
|
|
527
|
+
} from "fs/promises";
|
|
528
|
+
import { homedir } from "os";
|
|
529
|
+
import { dirname, join as join2, resolve } from "path";
|
|
530
|
+
|
|
531
|
+
// src/vectorize/archive.ts
|
|
532
|
+
import { gunzipSync, inflateRawSync } from "zlib";
|
|
533
|
+
var MAX_BINARY_BYTES = 8 * 1024 * 1024;
|
|
534
|
+
function extractVTracerArchive(archive, format) {
|
|
535
|
+
return format === "tar.gz" ? extractTarEntry(gunzipSync(archive, { maxOutputLength: MAX_BINARY_BYTES }), "vtracer") : extractZipEntry(archive, "vtracer.exe");
|
|
536
|
+
}
|
|
537
|
+
function extractTarEntry(tar, expectedName) {
|
|
538
|
+
for (let offset = 0;offset + 512 <= tar.length; ) {
|
|
539
|
+
const header = tar.subarray(offset, offset + 512);
|
|
540
|
+
if (header.every((byte) => byte === 0))
|
|
541
|
+
break;
|
|
542
|
+
const name = readNullTerminatedAscii(header.subarray(0, 100));
|
|
543
|
+
const prefix = readNullTerminatedAscii(header.subarray(345, 500));
|
|
544
|
+
const fullName = prefix === "" ? name : `${prefix}/${name}`;
|
|
545
|
+
const sizeText = readNullTerminatedAscii(header.subarray(124, 136)).trim();
|
|
546
|
+
if (!/^[0-7]+$/u.test(sizeText)) {
|
|
547
|
+
throw new VectorizeError("tool_integrity", "VTracer tar contains an invalid size.");
|
|
548
|
+
}
|
|
549
|
+
const size = Number.parseInt(sizeText, 8);
|
|
550
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > MAX_BINARY_BYTES) {
|
|
551
|
+
throw new VectorizeError("tool_integrity", "VTracer tar entry exceeds its size limit.");
|
|
552
|
+
}
|
|
553
|
+
const contentStart = offset + 512;
|
|
554
|
+
const contentEnd = contentStart + size;
|
|
555
|
+
if (contentEnd > tar.length) {
|
|
556
|
+
throw new VectorizeError("tool_integrity", "VTracer tar entry is truncated.");
|
|
557
|
+
}
|
|
558
|
+
if (fullName === expectedName || fullName.endsWith(`/${expectedName}`)) {
|
|
559
|
+
return Uint8Array.from(tar.subarray(contentStart, contentEnd));
|
|
560
|
+
}
|
|
561
|
+
offset = contentStart + Math.ceil(size / 512) * 512;
|
|
562
|
+
}
|
|
563
|
+
throw new VectorizeError("tool_integrity", `VTracer archive omitted ${expectedName}.`);
|
|
564
|
+
}
|
|
565
|
+
function extractZipEntry(zip, expectedName) {
|
|
566
|
+
const bytes = Buffer.from(zip);
|
|
567
|
+
let offset = 0;
|
|
568
|
+
while (offset + 30 <= bytes.length) {
|
|
569
|
+
const signature = bytes.readUInt32LE(offset);
|
|
570
|
+
if (signature !== 67324752)
|
|
571
|
+
break;
|
|
572
|
+
const flags = bytes.readUInt16LE(offset + 6);
|
|
573
|
+
const compression = bytes.readUInt16LE(offset + 8);
|
|
574
|
+
const compressedSize = bytes.readUInt32LE(offset + 18);
|
|
575
|
+
const uncompressedSize = bytes.readUInt32LE(offset + 22);
|
|
576
|
+
const nameLength = bytes.readUInt16LE(offset + 26);
|
|
577
|
+
const extraLength = bytes.readUInt16LE(offset + 28);
|
|
578
|
+
if ((flags & 1) !== 0 || (flags & 8) !== 0) {
|
|
579
|
+
throw new VectorizeError("tool_integrity", "VTracer zip uses encryption or an unsupported data descriptor.");
|
|
580
|
+
}
|
|
581
|
+
if (uncompressedSize > MAX_BINARY_BYTES) {
|
|
582
|
+
throw new VectorizeError("tool_integrity", "VTracer zip entry exceeds its size limit.");
|
|
583
|
+
}
|
|
584
|
+
const nameStart = offset + 30;
|
|
585
|
+
const dataStart = nameStart + nameLength + extraLength;
|
|
586
|
+
const dataEnd = dataStart + compressedSize;
|
|
587
|
+
if (dataEnd > bytes.length) {
|
|
588
|
+
throw new VectorizeError("tool_integrity", "VTracer zip entry is truncated.");
|
|
589
|
+
}
|
|
590
|
+
const name = bytes.subarray(nameStart, nameStart + nameLength).toString("utf8");
|
|
591
|
+
if (name === expectedName || name.endsWith(`/${expectedName}`)) {
|
|
592
|
+
const compressed = bytes.subarray(dataStart, dataEnd);
|
|
593
|
+
const extracted = compression === 0 ? Buffer.from(compressed) : compression === 8 ? inflateRawSync(compressed, { maxOutputLength: MAX_BINARY_BYTES }) : undefined;
|
|
594
|
+
if (extracted === undefined) {
|
|
595
|
+
throw new VectorizeError("tool_integrity", `VTracer zip uses unsupported compression method ${compression}.`);
|
|
596
|
+
}
|
|
597
|
+
if (extracted.length !== uncompressedSize) {
|
|
598
|
+
throw new VectorizeError("tool_integrity", "VTracer zip size does not match its header.");
|
|
599
|
+
}
|
|
600
|
+
return Uint8Array.from(extracted);
|
|
601
|
+
}
|
|
602
|
+
offset = dataEnd;
|
|
603
|
+
}
|
|
604
|
+
throw new VectorizeError("tool_integrity", `VTracer archive omitted ${expectedName}.`);
|
|
605
|
+
}
|
|
606
|
+
function readNullTerminatedAscii(bytes) {
|
|
607
|
+
const end = bytes.indexOf(0);
|
|
608
|
+
return Buffer.from(end === -1 ? bytes : bytes.subarray(0, end)).toString("ascii");
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// src/vectorize/metrics.ts
|
|
612
|
+
import { createHash } from "crypto";
|
|
613
|
+
function sha256(input) {
|
|
614
|
+
return createHash("sha256").update(input).digest("hex");
|
|
615
|
+
}
|
|
616
|
+
function sanitizedTraceRgba(rgba, minimumAlpha) {
|
|
617
|
+
if (rgba.length === 0 || rgba.length % 4 !== 0) {
|
|
618
|
+
throw new VectorizeError("invalid_input", "Trace sanitation requires nonempty RGBA pixels.");
|
|
619
|
+
}
|
|
620
|
+
if (!Number.isInteger(minimumAlpha) || minimumAlpha < 1 || minimumAlpha > 64) {
|
|
621
|
+
throw new VectorizeError("invalid_input", "alphaCutoff must be an integer from 1 through 64.");
|
|
622
|
+
}
|
|
623
|
+
const sanitized = Uint8Array.from(rgba);
|
|
624
|
+
for (let index = 0;index < sanitized.length; index += 4) {
|
|
625
|
+
if (sanitized[index + 3] >= minimumAlpha)
|
|
626
|
+
continue;
|
|
627
|
+
sanitized[index] = 0;
|
|
628
|
+
sanitized[index + 1] = 0;
|
|
629
|
+
sanitized[index + 2] = 0;
|
|
630
|
+
sanitized[index + 3] = 0;
|
|
631
|
+
}
|
|
632
|
+
return sanitized;
|
|
633
|
+
}
|
|
634
|
+
function alphaPlaneTraceRgba(rgba) {
|
|
635
|
+
if (rgba.length === 0 || rgba.length % 4 !== 0) {
|
|
636
|
+
throw new VectorizeError("invalid_input", "An alpha trace requires nonempty RGBA pixels.");
|
|
637
|
+
}
|
|
638
|
+
const grayscale = new Uint8Array(rgba.length);
|
|
639
|
+
for (let index = 0;index < rgba.length; index += 4) {
|
|
640
|
+
const alpha = rgba[index + 3];
|
|
641
|
+
grayscale[index] = alpha;
|
|
642
|
+
grayscale[index + 1] = alpha;
|
|
643
|
+
grayscale[index + 2] = alpha;
|
|
644
|
+
grayscale[index + 3] = 255;
|
|
645
|
+
}
|
|
646
|
+
return grayscale;
|
|
647
|
+
}
|
|
648
|
+
function lowAlphaMassRatio(rgba, cutoff) {
|
|
649
|
+
if (rgba.length === 0 || rgba.length % 4 !== 0) {
|
|
650
|
+
throw new VectorizeError("invalid_input", "Low-alpha measurement requires nonempty RGBA pixels.");
|
|
651
|
+
}
|
|
652
|
+
if (!Number.isInteger(cutoff) || cutoff < 1 || cutoff > 255) {
|
|
653
|
+
throw new VectorizeError("invalid_input", "The low-alpha cutoff must be a byte.");
|
|
654
|
+
}
|
|
655
|
+
let lowAlphaMass = 0;
|
|
656
|
+
let visibleAlphaMass = 0;
|
|
657
|
+
for (let index = 3;index < rgba.length; index += 4) {
|
|
658
|
+
const alpha = rgba[index];
|
|
659
|
+
visibleAlphaMass += alpha;
|
|
660
|
+
if (alpha > 0 && alpha < cutoff)
|
|
661
|
+
lowAlphaMass += alpha;
|
|
662
|
+
}
|
|
663
|
+
return visibleAlphaMass === 0 ? 0 : lowAlphaMass / visibleAlphaMass;
|
|
664
|
+
}
|
|
665
|
+
function hasFractionalAlpha(rgba) {
|
|
666
|
+
for (let index = 3;index < rgba.length; index += 4) {
|
|
667
|
+
const alpha = rgba[index];
|
|
668
|
+
if (alpha > 0 && alpha < 255)
|
|
669
|
+
return true;
|
|
670
|
+
}
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
function normalizedPremultipliedRmse(source, candidate) {
|
|
674
|
+
assertComparableRgba(source, candidate, "RMSE");
|
|
675
|
+
let squaredError = 0;
|
|
676
|
+
for (let index = 0;index < source.length; index += 4) {
|
|
677
|
+
const sourceAlpha = source[index + 3] / 255;
|
|
678
|
+
const candidateAlpha = candidate[index + 3] / 255;
|
|
679
|
+
for (let channel = 0;channel < 3; channel += 1) {
|
|
680
|
+
const difference = source[index + channel] * sourceAlpha - candidate[index + channel] * candidateAlpha;
|
|
681
|
+
squaredError += difference * difference;
|
|
682
|
+
}
|
|
683
|
+
const alphaDifference = source[index + 3] - candidate[index + 3];
|
|
684
|
+
squaredError += alphaDifference * alphaDifference;
|
|
685
|
+
}
|
|
686
|
+
return Math.sqrt(squaredError / source.length) / 255;
|
|
687
|
+
}
|
|
688
|
+
function normalizedAlphaRmse(source, candidate) {
|
|
689
|
+
assertComparableRgba(source, candidate, "Alpha RMSE");
|
|
690
|
+
let squaredError = 0;
|
|
691
|
+
for (let index = 3;index < source.length; index += 4) {
|
|
692
|
+
const difference = source[index] - candidate[index];
|
|
693
|
+
squaredError += difference * difference;
|
|
694
|
+
}
|
|
695
|
+
return Math.sqrt(squaredError / (source.length / 4)) / 255;
|
|
696
|
+
}
|
|
697
|
+
function assertComparableRgba(source, candidate, label) {
|
|
698
|
+
if (source.length === 0 || source.length !== candidate.length || source.length % 4 !== 0) {
|
|
699
|
+
throw new VectorizeError("invalid_input", `${label} inputs must be equally sized nonempty RGBA buffers.`);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
function measureSupport(source, candidate, width, height, dilation = 1) {
|
|
703
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || source.length !== width * height * 4 || candidate.length !== source.length) {
|
|
704
|
+
throw new VectorizeError("invalid_input", "Support metrics require equally sized rectangular RGBA buffers.");
|
|
705
|
+
}
|
|
706
|
+
if (!Number.isInteger(dilation) || dilation < 0 || dilation > 4) {
|
|
707
|
+
throw new VectorizeError("invalid_input", "Support dilation must be an integer from 0 to 4.");
|
|
708
|
+
}
|
|
709
|
+
const support = new Uint8Array(width * height);
|
|
710
|
+
for (let y = 0;y < height; y += 1) {
|
|
711
|
+
for (let x = 0;x < width; x += 1) {
|
|
712
|
+
let covered = false;
|
|
713
|
+
for (let dy = -dilation;dy <= dilation && !covered; dy += 1) {
|
|
714
|
+
for (let dx = -dilation;dx <= dilation; dx += 1) {
|
|
715
|
+
const neighborX = x + dx;
|
|
716
|
+
const neighborY = y + dy;
|
|
717
|
+
if (neighborX >= 0 && neighborX < width && neighborY >= 0 && neighborY < height && source[(neighborY * width + neighborX) * 4 + 3] > 0) {
|
|
718
|
+
covered = true;
|
|
719
|
+
break;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
support[y * width + x] = covered ? 1 : 0;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
let candidateAlphaMass = 0;
|
|
727
|
+
let outsideAlphaMass = 0;
|
|
728
|
+
let recalledAlphaMass = 0;
|
|
729
|
+
let sourceAlphaMass = 0;
|
|
730
|
+
for (let pixel = 0;pixel < width * height; pixel += 1) {
|
|
731
|
+
const sourceAlpha = source[pixel * 4 + 3] / 255;
|
|
732
|
+
const candidateAlpha = candidate[pixel * 4 + 3] / 255;
|
|
733
|
+
sourceAlphaMass += sourceAlpha;
|
|
734
|
+
candidateAlphaMass += candidateAlpha;
|
|
735
|
+
recalledAlphaMass += Math.min(sourceAlpha, candidateAlpha);
|
|
736
|
+
if (support[pixel] === 0)
|
|
737
|
+
outsideAlphaMass += candidateAlpha;
|
|
738
|
+
}
|
|
739
|
+
if (sourceAlphaMass === 0 || candidateAlphaMass === 0) {
|
|
740
|
+
throw new VectorizeError("quality_limit", "Source and candidate must contain visible pixels.");
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
outsideAlphaRatio: outsideAlphaMass / candidateAlphaMass,
|
|
744
|
+
supportRecall: recalledAlphaMass / sourceAlphaMass
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
function parseHexColor(value) {
|
|
748
|
+
const shorthand = value.match(/^#([a-f0-9])([a-f0-9])([a-f0-9])$/iu);
|
|
749
|
+
if (shorthand !== null) {
|
|
750
|
+
return [
|
|
751
|
+
Number.parseInt(`${shorthand[1]}${shorthand[1]}`, 16),
|
|
752
|
+
Number.parseInt(`${shorthand[2]}${shorthand[2]}`, 16),
|
|
753
|
+
Number.parseInt(`${shorthand[3]}${shorthand[3]}`, 16)
|
|
754
|
+
];
|
|
755
|
+
}
|
|
756
|
+
const full = value.match(/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/iu);
|
|
757
|
+
if (full === null) {
|
|
758
|
+
throw new VectorizeError("invalid_input", `Expected a #rgb or #rrggbb color, received ${JSON.stringify(value)}.`);
|
|
759
|
+
}
|
|
760
|
+
return [
|
|
761
|
+
Number.parseInt(full[1], 16),
|
|
762
|
+
Number.parseInt(full[2], 16),
|
|
763
|
+
Number.parseInt(full[3], 16)
|
|
764
|
+
];
|
|
765
|
+
}
|
|
766
|
+
function normalizedHexColor(value) {
|
|
767
|
+
return `#${parseHexColor(value).map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
|
|
768
|
+
}
|
|
769
|
+
function srgbToOklab([red, green, blue]) {
|
|
770
|
+
const linear = (channel) => {
|
|
771
|
+
const value = channel / 255;
|
|
772
|
+
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
773
|
+
};
|
|
774
|
+
const r = linear(red);
|
|
775
|
+
const g = linear(green);
|
|
776
|
+
const b = linear(blue);
|
|
777
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
|
|
778
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
779
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
780
|
+
return [
|
|
781
|
+
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
|
|
782
|
+
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
|
|
783
|
+
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
|
|
784
|
+
];
|
|
785
|
+
}
|
|
786
|
+
function oklabDistance(left, right) {
|
|
787
|
+
return Math.hypot(left[0] - right[0], left[1] - right[1], left[2] - right[2]);
|
|
788
|
+
}
|
|
789
|
+
function otsuDistanceCutoff(colors, primary) {
|
|
790
|
+
const distances = colors.map(({ color, mass }) => ({
|
|
791
|
+
distance: oklabDistance(color, primary),
|
|
792
|
+
mass
|
|
793
|
+
}));
|
|
794
|
+
const maximum = Math.max(...distances.map(({ distance }) => distance));
|
|
795
|
+
if (maximum === 0)
|
|
796
|
+
return Number.POSITIVE_INFINITY;
|
|
797
|
+
const histogram = Array.from({ length: 256 }, () => ({ mass: 0, moment: 0 }));
|
|
798
|
+
for (const { distance, mass } of distances) {
|
|
799
|
+
const index = Math.min(255, Math.floor(distance / maximum * 255));
|
|
800
|
+
histogram[index].mass += mass;
|
|
801
|
+
histogram[index].moment += mass * distance;
|
|
802
|
+
}
|
|
803
|
+
const totalMass = histogram.reduce((sum, bin) => sum + bin.mass, 0);
|
|
804
|
+
const totalMoment = histogram.reduce((sum, bin) => sum + bin.moment, 0);
|
|
805
|
+
let nearMass = 0;
|
|
806
|
+
let nearMoment = 0;
|
|
807
|
+
let bestScore = -1;
|
|
808
|
+
let bestIndex = 254;
|
|
809
|
+
for (let index = 0;index < 255; index += 1) {
|
|
810
|
+
const bin = histogram[index];
|
|
811
|
+
nearMass += bin.mass;
|
|
812
|
+
nearMoment += bin.moment;
|
|
813
|
+
const farMass = totalMass - nearMass;
|
|
814
|
+
if (nearMass === 0 || farMass === 0)
|
|
815
|
+
continue;
|
|
816
|
+
const nearMean = nearMoment / nearMass;
|
|
817
|
+
const farMean = (totalMoment - nearMoment) / farMass;
|
|
818
|
+
const score = nearMass * farMass * (nearMean - farMean) ** 2;
|
|
819
|
+
if (score > bestScore) {
|
|
820
|
+
bestScore = score;
|
|
821
|
+
bestIndex = index;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
let cutoff = maximum * (bestIndex + 1) / 255;
|
|
825
|
+
const nearShare = () => distances.reduce((sum, { distance, mass }) => sum + (distance <= cutoff ? mass : 0), 0) / totalMass;
|
|
826
|
+
if (nearShare() < 0.5) {
|
|
827
|
+
let cumulativeMass = 0;
|
|
828
|
+
for (const { distance, mass } of [...distances].sort((left, right) => left.distance - right.distance)) {
|
|
829
|
+
cumulativeMass += mass;
|
|
830
|
+
cutoff = distance;
|
|
831
|
+
if (cumulativeMass >= totalMass / 2)
|
|
832
|
+
break;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
return cutoff;
|
|
836
|
+
}
|
|
837
|
+
function dominantOklabDuotoneModel(rgba) {
|
|
838
|
+
if (rgba.length === 0 || rgba.length % 4 !== 0) {
|
|
839
|
+
throw new VectorizeError("invalid_input", "A duotone model requires nonempty RGBA pixels.");
|
|
840
|
+
}
|
|
841
|
+
const bins = new Map;
|
|
842
|
+
for (let index = 0;index < rgba.length; index += 4) {
|
|
843
|
+
const alpha = rgba[index + 3] / 255;
|
|
844
|
+
if (alpha === 0)
|
|
845
|
+
continue;
|
|
846
|
+
const red = rgba[index];
|
|
847
|
+
const green = rgba[index + 1];
|
|
848
|
+
const blue = rgba[index + 2];
|
|
849
|
+
const key = red >> 4 << 8 | green >> 4 << 4 | blue >> 4;
|
|
850
|
+
const bin = bins.get(key) ?? { blue: 0, green: 0, mass: 0, red: 0 };
|
|
851
|
+
bin.mass += alpha;
|
|
852
|
+
bin.red += red * alpha;
|
|
853
|
+
bin.green += green * alpha;
|
|
854
|
+
bin.blue += blue * alpha;
|
|
855
|
+
bins.set(key, bin);
|
|
856
|
+
}
|
|
857
|
+
if (bins.size === 0) {
|
|
858
|
+
throw new VectorizeError("invalid_input", "A duotone model requires visible pixels.");
|
|
859
|
+
}
|
|
860
|
+
const colors = [...bins.entries()].map(([key, bin]) => ({
|
|
861
|
+
color: srgbToOklab([
|
|
862
|
+
bin.red / bin.mass,
|
|
863
|
+
bin.green / bin.mass,
|
|
864
|
+
bin.blue / bin.mass
|
|
865
|
+
]),
|
|
866
|
+
key,
|
|
867
|
+
mass: bin.mass
|
|
868
|
+
})).sort((left, right) => right.mass - left.mass || left.key - right.key);
|
|
869
|
+
const primary = colors[0].color;
|
|
870
|
+
const cutoff = otsuDistanceCutoff(colors, primary);
|
|
871
|
+
const totalMass = colors.reduce((sum, { mass }) => sum + mass, 0);
|
|
872
|
+
const primaryMass = colors.reduce((sum, { color, mass }) => sum + (oklabDistance(color, primary) <= cutoff ? mass : 0), 0);
|
|
873
|
+
return { cutoff, primary, primaryShare: primaryMass / totalMass };
|
|
874
|
+
}
|
|
875
|
+
function colorBelongsToPrimary(rgb, model) {
|
|
876
|
+
return oklabDistance(srgbToOklab(rgb), model.primary) <= model.cutoff;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// src/vectorize/tool.ts
|
|
880
|
+
var VTRACER_VERSION = "0.6.4";
|
|
881
|
+
var frozenRelease = (release) => Object.freeze(release);
|
|
882
|
+
var vtracerReleases = Object.freeze({
|
|
883
|
+
"darwin-arm64": frozenRelease({
|
|
884
|
+
archiveSha256: "4a597fd2df8b961d60620df40a7436109427d86e5c028758e6e8796b02d3d996",
|
|
885
|
+
binarySha256: "77e495bbe212448240387fba3b6d8bc62ba20ecfb6f3c22967e51600f1cc6e66",
|
|
886
|
+
format: "tar.gz",
|
|
887
|
+
url: `https://github.com/visioncortex/vtracer/releases/download/${VTRACER_VERSION}/vtracer-aarch64-apple-darwin.tar.gz`
|
|
888
|
+
}),
|
|
889
|
+
"darwin-x64": frozenRelease({
|
|
890
|
+
archiveSha256: "f0d755292c2602d772d63d658a3498b23eca8b5620d4b92a991bd035d5abed16",
|
|
891
|
+
binarySha256: "0f9f88f989b757e27973a5c4b42665153070183d0787656ee8af2249ab326b78",
|
|
892
|
+
format: "tar.gz",
|
|
893
|
+
url: `https://github.com/visioncortex/vtracer/releases/download/${VTRACER_VERSION}/vtracer-x86_64-apple-darwin.tar.gz`
|
|
894
|
+
}),
|
|
895
|
+
"linux-arm64": frozenRelease({
|
|
896
|
+
archiveSha256: "cbd05ad4f491d12dd139ada61485ca1d24db9f981cbe1658632a083cd0ac1a71",
|
|
897
|
+
binarySha256: "a4b33b6c4066a6b9187802c6efc8b89e211318e12a17164b9d1dd1f29ac5e502",
|
|
898
|
+
format: "tar.gz",
|
|
899
|
+
url: `https://github.com/visioncortex/vtracer/releases/download/${VTRACER_VERSION}/vtracer-aarch64-unknown-linux-musl.tar.gz`
|
|
900
|
+
}),
|
|
901
|
+
"linux-x64": frozenRelease({
|
|
902
|
+
archiveSha256: "9290ba0c90e224d6d212836dff5491407c1718bcb72f80b2b5a4a01816df5e40",
|
|
903
|
+
binarySha256: "6f31499257076bd94de3e976844cf7ca5643f1e194a2bf0599b13f3719452aec",
|
|
904
|
+
format: "tar.gz",
|
|
905
|
+
url: `https://github.com/visioncortex/vtracer/releases/download/${VTRACER_VERSION}/vtracer-x86_64-unknown-linux-musl.tar.gz`
|
|
906
|
+
}),
|
|
907
|
+
"win32-x64": frozenRelease({
|
|
908
|
+
archiveSha256: "6b5bc17a6b017129ee40461df254f65d16f3b494c001a8541d41861066b716bf",
|
|
909
|
+
binarySha256: "4ad8d35e566cd15caf582063b8349bd082b8fa2bd461e99d116fc63ad8fdeca0",
|
|
910
|
+
format: "zip",
|
|
911
|
+
url: `https://github.com/visioncortex/vtracer/releases/download/${VTRACER_VERSION}/vtracer-x86_64-pc-windows-msvc.zip`
|
|
912
|
+
})
|
|
913
|
+
});
|
|
914
|
+
var MAX_ARCHIVE_BYTES = 4 * 1024 * 1024;
|
|
915
|
+
var MAX_TOOL_BYTES = 16 * 1024 * 1024;
|
|
916
|
+
var FILE_CHUNK_BYTES = 64 * 1024;
|
|
917
|
+
function renamedEnvironmentValue(canonical) {
|
|
918
|
+
return process.env[canonical];
|
|
919
|
+
}
|
|
920
|
+
async function ensureVTracer(deadline, privateDirectory, cacheDirectory) {
|
|
921
|
+
const override = renamedEnvironmentValue("SLOPCAMERA_VTRACER_PATH");
|
|
922
|
+
if (override !== undefined) {
|
|
923
|
+
return copyAndInspectVTracer(resolve(override), resolve(privateDirectory), "override", deadline);
|
|
924
|
+
}
|
|
925
|
+
const key = `${process.platform}-${process.arch}`;
|
|
926
|
+
const release = vtracerReleases[key];
|
|
927
|
+
if (release === undefined) {
|
|
928
|
+
throw new VectorizeError("tool_platform", `VTracer is not pinned for ${process.platform}/${process.arch}.`, { arch: process.arch, platform: process.platform });
|
|
929
|
+
}
|
|
930
|
+
const cacheRoot = resolve(cacheDirectory ?? defaultCacheDirectory());
|
|
931
|
+
const suffix = process.platform === "win32" ? ".exe" : "";
|
|
932
|
+
const toolPath = join2(cacheRoot, "tools", `vtracer-${VTRACER_VERSION}-${process.platform}-${process.arch}${suffix}`);
|
|
933
|
+
const cachedHash = await hashCachedTool(toolPath, deadline);
|
|
934
|
+
if (cachedHash !== release.binarySha256) {
|
|
935
|
+
await removeInvalidCachedTool(toolPath);
|
|
936
|
+
await installOfficialVTracer(toolPath, release, deadline);
|
|
937
|
+
}
|
|
938
|
+
return copyAndInspectVTracer(toolPath, resolve(privateDirectory), "official-release", deadline, release.binarySha256);
|
|
939
|
+
}
|
|
940
|
+
function defaultCacheDirectory() {
|
|
941
|
+
const explicit = renamedEnvironmentValue("SLOPCAMERA_CACHE_DIR");
|
|
942
|
+
if (explicit !== undefined && explicit.trim() !== "")
|
|
943
|
+
return explicit;
|
|
944
|
+
if (process.platform === "win32") {
|
|
945
|
+
return join2(process.env.LOCALAPPDATA ?? homedir(), "slopcamera");
|
|
946
|
+
}
|
|
947
|
+
if (process.platform === "darwin")
|
|
948
|
+
return join2(homedir(), "Library", "Caches", "slopcamera");
|
|
949
|
+
return join2(process.env.XDG_CACHE_HOME ?? join2(homedir(), ".cache"), "slopcamera");
|
|
950
|
+
}
|
|
951
|
+
async function installOfficialVTracer(toolPath, release, deadline) {
|
|
952
|
+
deadline.assert("VTracer download");
|
|
953
|
+
const archive = await downloadBounded(release.url, deadline, MAX_ARCHIVE_BYTES);
|
|
954
|
+
const archiveSha256 = sha256(archive);
|
|
955
|
+
if (archiveSha256 !== release.archiveSha256) {
|
|
956
|
+
throw new VectorizeError("tool_integrity", `VTracer archive checksum mismatch: ${archiveSha256}`, { actual: archiveSha256, expected: release.archiveSha256 });
|
|
957
|
+
}
|
|
958
|
+
const binary = extractVTracerArchive(archive, release.format);
|
|
959
|
+
if (binary.byteLength < 1 || binary.byteLength > MAX_TOOL_BYTES) {
|
|
960
|
+
throw new VectorizeError("tool_integrity", "VTracer binary exceeds its verified installation limit.", { bytes: binary.byteLength, maximumBytes: MAX_TOOL_BYTES });
|
|
961
|
+
}
|
|
962
|
+
const binarySha256 = sha256(binary);
|
|
963
|
+
if (binarySha256 !== release.binarySha256) {
|
|
964
|
+
throw new VectorizeError("tool_integrity", `VTracer binary checksum mismatch: ${binarySha256}`, { actual: binarySha256, expected: release.binarySha256 });
|
|
965
|
+
}
|
|
966
|
+
deadline.assert("VTracer installation");
|
|
967
|
+
await mkdir(dirname(toolPath), { recursive: true });
|
|
968
|
+
const stagedPath = `${toolPath}.${randomUUID()}.tmp`;
|
|
969
|
+
try {
|
|
970
|
+
await writeFile(stagedPath, binary, { flag: "wx", mode: 448 });
|
|
971
|
+
if (process.platform !== "win32")
|
|
972
|
+
await chmod(stagedPath, 320);
|
|
973
|
+
deadline.assert("VTracer installation");
|
|
974
|
+
try {
|
|
975
|
+
await rename(stagedPath, toolPath);
|
|
976
|
+
} catch (error) {
|
|
977
|
+
const concurrentHash = await hashCachedTool(toolPath, deadline);
|
|
978
|
+
if (concurrentHash === release.binarySha256) {
|
|
979
|
+
await rm(stagedPath, { force: true });
|
|
980
|
+
} else {
|
|
981
|
+
throw error;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
} catch (error) {
|
|
985
|
+
await rm(stagedPath, { force: true });
|
|
986
|
+
if (error instanceof VectorizeError)
|
|
987
|
+
throw error;
|
|
988
|
+
throw new VectorizeError("tool_integrity", "Could not publish the verified VTracer binary.", {}, { cause: error });
|
|
989
|
+
}
|
|
990
|
+
const installedHash = await hashCachedTool(toolPath, deadline);
|
|
991
|
+
if (installedHash !== release.binarySha256) {
|
|
992
|
+
throw new VectorizeError("tool_integrity", "Installed VTracer differs from the verified release binary.", { actual: installedHash, expected: release.binarySha256 });
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
async function copyAndInspectVTracer(sourcePath, privateDirectory, source, deadline, expectedSha256) {
|
|
996
|
+
deadline.assert("VTracer private copy");
|
|
997
|
+
await mkdir(privateDirectory, { mode: 448, recursive: true });
|
|
998
|
+
const suffix = process.platform === "win32" ? ".exe" : "";
|
|
999
|
+
const privatePath = join2(privateDirectory, `vtracer-${randomUUID()}${suffix}`);
|
|
1000
|
+
const failureCode = source === "official-release" ? "tool_integrity" : "tool_version";
|
|
1001
|
+
let sourceHandle;
|
|
1002
|
+
let targetHandle;
|
|
1003
|
+
let copiedSha256;
|
|
1004
|
+
try {
|
|
1005
|
+
const resolvedSourcePath = await realpath(sourcePath);
|
|
1006
|
+
deadline.assert("VTracer private copy");
|
|
1007
|
+
sourceHandle = await open2(resolvedSourcePath, boundedReadFlags());
|
|
1008
|
+
const metadata = await sourceHandle.stat();
|
|
1009
|
+
assertBoundedRegularTool(metadata, sourcePath);
|
|
1010
|
+
targetHandle = await open2(privatePath, "wx", 320);
|
|
1011
|
+
copiedSha256 = await copyAndHash(sourceHandle, targetHandle, MAX_TOOL_BYTES, deadline);
|
|
1012
|
+
await targetHandle.sync();
|
|
1013
|
+
deadline.assert("VTracer private copy");
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
if (error instanceof VectorizeError)
|
|
1016
|
+
throw error;
|
|
1017
|
+
throw new VectorizeError(failureCode, "VTracer could not be copied into the private conversion directory.", {}, { cause: error });
|
|
1018
|
+
} finally {
|
|
1019
|
+
await Promise.allSettled([sourceHandle?.close(), targetHandle?.close()]);
|
|
1020
|
+
}
|
|
1021
|
+
try {
|
|
1022
|
+
if (copiedSha256.length === 0) {
|
|
1023
|
+
throw new VectorizeError(failureCode, "VTracer executable is empty.");
|
|
1024
|
+
}
|
|
1025
|
+
if (expectedSha256 !== undefined && copiedSha256 !== expectedSha256) {
|
|
1026
|
+
throw new VectorizeError("tool_integrity", "VTracer changed before it could be copied for conversion.", { actual: copiedSha256, expected: expectedSha256 });
|
|
1027
|
+
}
|
|
1028
|
+
if (process.platform !== "win32")
|
|
1029
|
+
await chmod(privatePath, 320);
|
|
1030
|
+
const privateSha256 = await hashRegularFile(privatePath, MAX_TOOL_BYTES, deadline, failureCode);
|
|
1031
|
+
if (privateSha256 !== copiedSha256) {
|
|
1032
|
+
throw new VectorizeError("tool_integrity", "The private VTracer copy failed its integrity check.", { actual: privateSha256, expected: copiedSha256 });
|
|
1033
|
+
}
|
|
1034
|
+
return inspectVTracer(privatePath, source, deadline, copiedSha256, expectedSha256);
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
await rm(privatePath, { force: true });
|
|
1037
|
+
throw error;
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
async function inspectVTracer(path, source, deadline, copiedSha256, expectedSha256) {
|
|
1041
|
+
deadline.assert("VTracer inspection");
|
|
1042
|
+
const { stderr, stdout } = await runBoundedCommand([path, "--version"], deadline.remainingMs(), "tool_version");
|
|
1043
|
+
if (!new RegExp(`\\b${VTRACER_VERSION.replaceAll(".", "\\.")}\\b`, "u").test(`${stdout}
|
|
1044
|
+
${stderr}`)) {
|
|
1045
|
+
throw new VectorizeError("tool_version", `Expected VTracer ${VTRACER_VERSION}.`);
|
|
1046
|
+
}
|
|
1047
|
+
const afterInspectionSha256 = await hashRegularFile(path, MAX_TOOL_BYTES, deadline, "tool_integrity");
|
|
1048
|
+
if (afterInspectionSha256 !== copiedSha256 || expectedSha256 !== undefined && afterInspectionSha256 !== expectedSha256) {
|
|
1049
|
+
throw new VectorizeError("tool_integrity", "The private VTracer executable changed during inspection.", {
|
|
1050
|
+
actual: afterInspectionSha256,
|
|
1051
|
+
expected: expectedSha256 ?? copiedSha256
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
return {
|
|
1055
|
+
path,
|
|
1056
|
+
sha256: afterInspectionSha256,
|
|
1057
|
+
source,
|
|
1058
|
+
version: VTRACER_VERSION
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
async function hashCachedTool(path, deadline) {
|
|
1062
|
+
try {
|
|
1063
|
+
return await hashRegularFile(path, MAX_TOOL_BYTES, deadline, "tool_integrity");
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
if (error instanceof VectorizeError && error.code === "timeout")
|
|
1066
|
+
throw error;
|
|
1067
|
+
if (isFileSystemError2(error, "ENOENT"))
|
|
1068
|
+
return;
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
async function removeInvalidCachedTool(path) {
|
|
1073
|
+
try {
|
|
1074
|
+
await rm(path, { force: true });
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
throw new VectorizeError("tool_integrity", "Could not remove an invalid cached VTracer binary.", {}, { cause: error });
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
async function hashRegularFile(path, maximumBytes, deadline, failureCode) {
|
|
1080
|
+
let handle;
|
|
1081
|
+
try {
|
|
1082
|
+
deadline.assert("VTracer hash");
|
|
1083
|
+
const resolvedPath = await realpath(path);
|
|
1084
|
+
deadline.assert("VTracer hash");
|
|
1085
|
+
handle = await open2(resolvedPath, boundedReadFlags());
|
|
1086
|
+
const metadata = await handle.stat();
|
|
1087
|
+
if (!metadata.isFile() || metadata.size < 1 || metadata.size > maximumBytes) {
|
|
1088
|
+
throw new VectorizeError(failureCode, "VTracer must be a non-empty regular file within its size limit.", { bytes: metadata.size, maximumBytes });
|
|
1089
|
+
}
|
|
1090
|
+
const hash = createHash2("sha256");
|
|
1091
|
+
const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, maximumBytes + 1));
|
|
1092
|
+
let bytes = 0;
|
|
1093
|
+
while (true) {
|
|
1094
|
+
deadline.assert("VTracer hash");
|
|
1095
|
+
const maximumRead = Math.min(buffer.byteLength, maximumBytes - bytes + 1);
|
|
1096
|
+
const { bytesRead } = await handle.read(buffer, 0, maximumRead, null);
|
|
1097
|
+
if (bytesRead === 0)
|
|
1098
|
+
break;
|
|
1099
|
+
bytes += bytesRead;
|
|
1100
|
+
if (bytes > maximumBytes) {
|
|
1101
|
+
throw new VectorizeError(failureCode, "VTracer grew beyond its executable size limit while being hashed.", { bytes, maximumBytes });
|
|
1102
|
+
}
|
|
1103
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
1104
|
+
}
|
|
1105
|
+
deadline.assert("VTracer hash");
|
|
1106
|
+
return hash.digest("hex");
|
|
1107
|
+
} catch (error) {
|
|
1108
|
+
if (error instanceof VectorizeError)
|
|
1109
|
+
throw error;
|
|
1110
|
+
throw new VectorizeError(failureCode, "VTracer executable could not be read safely.", {}, { cause: error });
|
|
1111
|
+
} finally {
|
|
1112
|
+
await handle?.close().catch(() => {
|
|
1113
|
+
return;
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
async function copyAndHash(source, target, maximumBytes, deadline) {
|
|
1118
|
+
const hash = createHash2("sha256");
|
|
1119
|
+
const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, maximumBytes + 1));
|
|
1120
|
+
let bytes = 0;
|
|
1121
|
+
while (true) {
|
|
1122
|
+
deadline.assert("VTracer private copy");
|
|
1123
|
+
const maximumRead = Math.min(buffer.byteLength, maximumBytes - bytes + 1);
|
|
1124
|
+
const { bytesRead } = await source.read(buffer, 0, maximumRead, null);
|
|
1125
|
+
if (bytesRead === 0)
|
|
1126
|
+
break;
|
|
1127
|
+
bytes += bytesRead;
|
|
1128
|
+
if (bytes > maximumBytes) {
|
|
1129
|
+
throw new VectorizeError("tool_integrity", "VTracer grew beyond its executable size limit while being copied.", { bytes, maximumBytes });
|
|
1130
|
+
}
|
|
1131
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
1132
|
+
let written = 0;
|
|
1133
|
+
while (written < bytesRead) {
|
|
1134
|
+
const result = await target.write(buffer, written, bytesRead - written, null);
|
|
1135
|
+
if (result.bytesWritten < 1) {
|
|
1136
|
+
throw new VectorizeError("tool_integrity", "VTracer private copy stopped before completion.");
|
|
1137
|
+
}
|
|
1138
|
+
written += result.bytesWritten;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
return bytes === 0 ? "" : hash.digest("hex");
|
|
1142
|
+
}
|
|
1143
|
+
function assertBoundedRegularTool(metadata, path) {
|
|
1144
|
+
if (!metadata.isFile() || metadata.size < 1 || metadata.size > MAX_TOOL_BYTES) {
|
|
1145
|
+
throw new VectorizeError("tool_version", `VTracer must be a non-empty regular file: ${path}`, { bytes: metadata.size, maximumBytes: MAX_TOOL_BYTES });
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
async function downloadBounded(url, deadline, maximumBytes) {
|
|
1149
|
+
const controller = new AbortController;
|
|
1150
|
+
const timer = setTimeout(() => controller.abort(), deadline.remainingMs());
|
|
1151
|
+
try {
|
|
1152
|
+
const response = await fetch(url, {
|
|
1153
|
+
headers: { "user-agent": "hraness-slopcamera-vectorizer" },
|
|
1154
|
+
redirect: "follow",
|
|
1155
|
+
signal: controller.signal
|
|
1156
|
+
});
|
|
1157
|
+
if (!response.ok || response.body === null) {
|
|
1158
|
+
throw new VectorizeError("tool_download", `Could not download VTracer: ${response.status} ${response.statusText}`);
|
|
1159
|
+
}
|
|
1160
|
+
const declaredLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
|
|
1161
|
+
if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {
|
|
1162
|
+
throw new VectorizeError("tool_download", "VTracer archive exceeds its download limit.");
|
|
1163
|
+
}
|
|
1164
|
+
const chunks = [];
|
|
1165
|
+
const reader = response.body.getReader();
|
|
1166
|
+
let bytes = 0;
|
|
1167
|
+
while (true) {
|
|
1168
|
+
deadline.assert("VTracer download");
|
|
1169
|
+
const { done, value } = await reader.read();
|
|
1170
|
+
if (done)
|
|
1171
|
+
break;
|
|
1172
|
+
bytes += value.byteLength;
|
|
1173
|
+
if (bytes > maximumBytes) {
|
|
1174
|
+
await reader.cancel();
|
|
1175
|
+
throw new VectorizeError("tool_download", "VTracer archive exceeds its download limit.");
|
|
1176
|
+
}
|
|
1177
|
+
chunks.push(value);
|
|
1178
|
+
}
|
|
1179
|
+
return Uint8Array.from(Buffer.concat(chunks, bytes));
|
|
1180
|
+
} catch (error) {
|
|
1181
|
+
if (error instanceof VectorizeError)
|
|
1182
|
+
throw error;
|
|
1183
|
+
if (controller.signal.aborted) {
|
|
1184
|
+
throw new VectorizeError("timeout", "VTracer download exceeded the conversion time limit.");
|
|
1185
|
+
}
|
|
1186
|
+
throw new VectorizeError("tool_download", "Could not download VTracer.", {}, { cause: error });
|
|
1187
|
+
} finally {
|
|
1188
|
+
clearTimeout(timer);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
function isFileSystemError2(error, code) {
|
|
1192
|
+
return error instanceof Error && "code" in error && error.code === code;
|
|
1193
|
+
}
|
|
1194
|
+
function boundedReadFlags() {
|
|
1195
|
+
if (process.platform === "win32")
|
|
1196
|
+
return constants2.O_RDONLY;
|
|
1197
|
+
return constants2.O_RDONLY | constants2.O_NONBLOCK | constants2.O_NOFOLLOW;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// src/vectorize/pixels.ts
|
|
1201
|
+
import { constants as constants3 } from "fs";
|
|
1202
|
+
import { open as open3, realpath as realpath2 } from "fs/promises";
|
|
1203
|
+
import { resolve as resolve2 } from "path";
|
|
1204
|
+
import sharp from "sharp";
|
|
1205
|
+
var allowedFormats = new Set(["avif", "gif", "heif", "jpeg", "png", "tiff", "webp"]);
|
|
1206
|
+
var METRIC_MAX_EDGE = 512;
|
|
1207
|
+
var VECTORIZE_SHARP_CONCURRENCY = 1;
|
|
1208
|
+
function configureVectorizeSharpConcurrency() {
|
|
1209
|
+
const actual = sharp.concurrency(VECTORIZE_SHARP_CONCURRENCY);
|
|
1210
|
+
if (actual !== VECTORIZE_SHARP_CONCURRENCY) {
|
|
1211
|
+
throw new VectorizeError("trace_failed", "The vectorization worker could not bind its Sharp CPU budget.");
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
async function loadRaster(input, limits, deadline) {
|
|
1215
|
+
deadline.assert("input read");
|
|
1216
|
+
const bytes = await readInputBytes(input, limits.maxInputBytes, deadline);
|
|
1217
|
+
deadline.assert("input metadata");
|
|
1218
|
+
try {
|
|
1219
|
+
const metadata = await sharp(bytes, {
|
|
1220
|
+
failOn: "error",
|
|
1221
|
+
limitInputPixels: limits.maxDecodedPixels,
|
|
1222
|
+
sequentialRead: true
|
|
1223
|
+
}).metadata();
|
|
1224
|
+
const format = metadata.format;
|
|
1225
|
+
if (format === undefined || !allowedFormats.has(format)) {
|
|
1226
|
+
throw new VectorizeError("invalid_input", `Expected a supported raster image, received ${format ?? "an unknown format"}.`);
|
|
1227
|
+
}
|
|
1228
|
+
if ((metadata.pages ?? 1) !== 1) {
|
|
1229
|
+
throw new VectorizeError("invalid_input", "Animated and multipage raster inputs are rejected.");
|
|
1230
|
+
}
|
|
1231
|
+
if (metadata.width === undefined || metadata.height === undefined || metadata.width < 1 || metadata.height < 1) {
|
|
1232
|
+
throw new VectorizeError("invalid_input", "Raster dimensions are missing or invalid.");
|
|
1233
|
+
}
|
|
1234
|
+
assertDimensions(metadata.width, metadata.height, limits);
|
|
1235
|
+
const decoded = await sharp(bytes, {
|
|
1236
|
+
failOn: "error",
|
|
1237
|
+
limitInputPixels: limits.maxDecodedPixels,
|
|
1238
|
+
sequentialRead: true
|
|
1239
|
+
}).rotate().ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
1240
|
+
const { channels, height, width } = decoded.info;
|
|
1241
|
+
if (channels !== 4) {
|
|
1242
|
+
throw new VectorizeError("invalid_input", "Raster decoding did not produce RGBA pixels.");
|
|
1243
|
+
}
|
|
1244
|
+
assertDimensions(width, height, limits);
|
|
1245
|
+
const pixels = Uint8Array.from(decoded.data);
|
|
1246
|
+
if (!containsVisiblePixel(pixels)) {
|
|
1247
|
+
throw new VectorizeError("invalid_input", "A fully transparent image cannot be vectorized.");
|
|
1248
|
+
}
|
|
1249
|
+
deadline.assert("raster decode");
|
|
1250
|
+
const scoreScale = Math.min(1, METRIC_MAX_EDGE / Math.max(width, height));
|
|
1251
|
+
const scoreWidth = Math.max(1, Math.round(width * scoreScale));
|
|
1252
|
+
const scoreHeight = Math.max(1, Math.round(height * scoreScale));
|
|
1253
|
+
const scorePixels = scoreWidth === width && scoreHeight === height ? pixels : Uint8Array.from(await sharp(pixels, { raw: { channels: 4, height, width } }).resize(scoreWidth, scoreHeight, { fit: "fill", kernel: "lanczos3" }).raw().toBuffer());
|
|
1254
|
+
deadline.assert("metric sample");
|
|
1255
|
+
return {
|
|
1256
|
+
bytes,
|
|
1257
|
+
format,
|
|
1258
|
+
height,
|
|
1259
|
+
inputBytes: bytes.byteLength,
|
|
1260
|
+
pixels,
|
|
1261
|
+
scoreHeight,
|
|
1262
|
+
scorePixels,
|
|
1263
|
+
scoreWidth,
|
|
1264
|
+
sourceSha256: sha256(bytes),
|
|
1265
|
+
width
|
|
1266
|
+
};
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
if (error instanceof VectorizeError)
|
|
1269
|
+
throw error;
|
|
1270
|
+
throw new VectorizeError("invalid_input", "Raster input could not be decoded safely.", {}, {
|
|
1271
|
+
cause: error
|
|
1272
|
+
});
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
async function readInputBytes(input, maximumBytes, deadline) {
|
|
1276
|
+
if (typeof input === "string") {
|
|
1277
|
+
return readRegularInput(resolve2(input), maximumBytes, deadline);
|
|
1278
|
+
}
|
|
1279
|
+
const view = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
|
|
1280
|
+
if (view.byteLength === 0) {
|
|
1281
|
+
throw new VectorizeError("invalid_input", "Raster input is empty.");
|
|
1282
|
+
}
|
|
1283
|
+
if (view.byteLength > maximumBytes) {
|
|
1284
|
+
throw new VectorizeError("input_limit", `Raster input exceeds the ${maximumBytes}-byte limit.`, { bytes: view.byteLength, maximumBytes });
|
|
1285
|
+
}
|
|
1286
|
+
deadline.assert("input read");
|
|
1287
|
+
const bytes = Uint8Array.from(view);
|
|
1288
|
+
deadline.assert("input read");
|
|
1289
|
+
return bytes;
|
|
1290
|
+
}
|
|
1291
|
+
async function readRegularInput(path, maximumBytes, deadline) {
|
|
1292
|
+
let handle;
|
|
1293
|
+
try {
|
|
1294
|
+
deadline.assert("input read");
|
|
1295
|
+
const targetPath = await realpath2(path);
|
|
1296
|
+
deadline.assert("input read");
|
|
1297
|
+
handle = await open3(targetPath, boundedReadFlags2());
|
|
1298
|
+
const metadata = await handle.stat();
|
|
1299
|
+
if (!metadata.isFile()) {
|
|
1300
|
+
throw new VectorizeError("invalid_input", `Raster input is not a file: ${path}`);
|
|
1301
|
+
}
|
|
1302
|
+
if (metadata.size < 1) {
|
|
1303
|
+
throw new VectorizeError("invalid_input", "Raster input is empty.");
|
|
1304
|
+
}
|
|
1305
|
+
if (metadata.size > maximumBytes) {
|
|
1306
|
+
throw new VectorizeError("input_limit", `Raster input exceeds the ${maximumBytes}-byte limit.`, { bytes: metadata.size, maximumBytes });
|
|
1307
|
+
}
|
|
1308
|
+
const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maximumBytes + 1));
|
|
1309
|
+
const chunks = [];
|
|
1310
|
+
let bytes = 0;
|
|
1311
|
+
while (true) {
|
|
1312
|
+
deadline.assert("input read");
|
|
1313
|
+
const maximumRead = Math.min(chunk.byteLength, maximumBytes - bytes + 1);
|
|
1314
|
+
const { bytesRead } = await handle.read(chunk, 0, maximumRead, null);
|
|
1315
|
+
if (bytesRead === 0)
|
|
1316
|
+
break;
|
|
1317
|
+
bytes += bytesRead;
|
|
1318
|
+
if (bytes > maximumBytes) {
|
|
1319
|
+
throw new VectorizeError("input_limit", `Raster input exceeds the ${maximumBytes}-byte limit.`, { bytes, maximumBytes });
|
|
1320
|
+
}
|
|
1321
|
+
chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
|
|
1322
|
+
}
|
|
1323
|
+
if (bytes === 0) {
|
|
1324
|
+
throw new VectorizeError("invalid_input", "Raster input is empty.");
|
|
1325
|
+
}
|
|
1326
|
+
deadline.assert("input read");
|
|
1327
|
+
return Buffer.concat(chunks, bytes);
|
|
1328
|
+
} catch (error) {
|
|
1329
|
+
if (error instanceof VectorizeError)
|
|
1330
|
+
throw error;
|
|
1331
|
+
throw new VectorizeError("invalid_input", "Raster input could not be read safely.", {}, { cause: error });
|
|
1332
|
+
} finally {
|
|
1333
|
+
await handle?.close().catch(() => {
|
|
1334
|
+
return;
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
function assertDimensions(width, height, limits) {
|
|
1339
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > limits.maxDimension || height > limits.maxDimension || width * height > limits.maxDecodedPixels) {
|
|
1340
|
+
throw new VectorizeError("input_limit", `Raster dimensions must fit ${limits.maxDimension}px and ${limits.maxDecodedPixels} decoded pixels.`, { height, width });
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
function containsVisiblePixel(rgba) {
|
|
1344
|
+
for (let index = 3;index < rgba.length; index += 4) {
|
|
1345
|
+
if (rgba[index] > 0)
|
|
1346
|
+
return true;
|
|
1347
|
+
}
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
function boundedReadFlags2() {
|
|
1351
|
+
if (process.platform === "win32")
|
|
1352
|
+
return constants3.O_RDONLY;
|
|
1353
|
+
return constants3.O_RDONLY | constants3.O_NONBLOCK | constants3.O_NOFOLLOW;
|
|
1354
|
+
}
|
|
1355
|
+
async function encodeTracePng(pixels, width, height) {
|
|
1356
|
+
return Uint8Array.from(await sharp(pixels, { raw: { channels: 4, height, width } }).png({ adaptiveFiltering: false, compressionLevel: 9, palette: false }).toBuffer());
|
|
1357
|
+
}
|
|
1358
|
+
async function renderSvgRgba(svg, width, height, maxDecodedPixels) {
|
|
1359
|
+
try {
|
|
1360
|
+
return Uint8Array.from(await sharp(Buffer.from(svg), {
|
|
1361
|
+
density: 72,
|
|
1362
|
+
failOn: "error",
|
|
1363
|
+
limitInputPixels: maxDecodedPixels
|
|
1364
|
+
}).resize(width, height, { fit: "fill" }).ensureAlpha().raw().toBuffer());
|
|
1365
|
+
} catch (error) {
|
|
1366
|
+
throw new VectorizeError("trace_failed", "Canonical SVG could not be rendered for quality measurement.", {}, { cause: error });
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
function sharpProvenance() {
|
|
1370
|
+
const sharpVersions = normalizedPixelToolchain(sharp.versions);
|
|
1371
|
+
const sharpVersion = sharpVersions.sharp;
|
|
1372
|
+
const vipsVersion = sharpVersions.vips;
|
|
1373
|
+
if (sharpVersion === undefined || vipsVersion === undefined) {
|
|
1374
|
+
throw new VectorizeError("tool_version", "Sharp must report its own and libvips version metadata.");
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
sharp: sharpVersion,
|
|
1378
|
+
sharpVersions,
|
|
1379
|
+
vips: vipsVersion
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
function normalizedPixelToolchain(versions) {
|
|
1383
|
+
const entries = Object.entries(versions).filter((entry) => entry[1] !== undefined).sort(([left], [right]) => left.localeCompare(right));
|
|
1384
|
+
if (entries.length === 0 || entries.some(([name, version]) => name.length === 0 || version.length === 0)) {
|
|
1385
|
+
throw new VectorizeError("tool_version", "Pixel toolchain versions must be nonempty strings.");
|
|
1386
|
+
}
|
|
1387
|
+
return Object.freeze(Object.fromEntries(entries));
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
// src/vectorize/worker-protocol.ts
|
|
1391
|
+
var VECTORIZE_WORKER_PROTOCOL = 1;
|
|
1392
|
+
var MAX_VECTORIZE_REQUEST_BYTES = Math.ceil(vectorizeHardLimits.maxInputBytes / 3) * 4 + 512 * 1024;
|
|
1393
|
+
var MAX_VECTORIZE_RESPONSE_BYTES = vectorizeHardLimits.maxOutputBytes * 2 + 512 * 1024;
|
|
1394
|
+
|
|
1395
|
+
// src/vectorize/vectorize.ts
|
|
1396
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1397
|
+
import {
|
|
1398
|
+
mkdir as mkdir2,
|
|
1399
|
+
rename as rename2,
|
|
1400
|
+
rm as rm3,
|
|
1401
|
+
writeFile as writeFile2
|
|
1402
|
+
} from "fs/promises";
|
|
1403
|
+
import { dirname as dirname3, join as join4, resolve as resolve3 } from "path";
|
|
1404
|
+
|
|
1405
|
+
// src/vectorize/svg.ts
|
|
1406
|
+
var PATH_DATA = /^[MmZzLlHhVvCcSsQqTtAaEe0-9+,.\s-]+$/u;
|
|
1407
|
+
var TRANSLATE = /^translate\(\s*[-+0-9.eE]+\s*(?:,\s*|\s+)[-+0-9.eE]+\s*\)$/u;
|
|
1408
|
+
var DANGEROUS_SOURCE = /<!DOCTYPE|<!ENTITY|<\?(?!xml)|<(?:a|animate|embed|filter|foreignObject|iframe|image|link|object|script|set|style|use)\b|(?:href|src)\s*=|\bon[a-z]+\s*=|url\s*\(/iu;
|
|
1409
|
+
function canonicalizeVTracerSvg(sourceSvg, width, height, maxPaths) {
|
|
1410
|
+
if (DANGEROUS_SOURCE.test(sourceSvg)) {
|
|
1411
|
+
throw new VectorizeError("unsafe_svg", "VTracer output contains active or referenced SVG content.");
|
|
1412
|
+
}
|
|
1413
|
+
const paths = [];
|
|
1414
|
+
const pathPattern = /<path\b([^>]*)\/?\s*>/gu;
|
|
1415
|
+
for (const match of sourceSvg.matchAll(pathPattern)) {
|
|
1416
|
+
if (paths.length >= maxPaths) {
|
|
1417
|
+
throw new VectorizeError("output_limit", `VTracer output exceeds the ${maxPaths}-path limit.`);
|
|
1418
|
+
}
|
|
1419
|
+
const attributes = match[1];
|
|
1420
|
+
const d = attributes.match(/(?:^|\s)d="([^"]*)"/u)?.[1];
|
|
1421
|
+
const fill = attributes.match(/(?:^|\s)fill="([^"]+)"/u)?.[1];
|
|
1422
|
+
const transform = attributes.match(/(?:^|\s)transform="([^"]+)"/u)?.[1];
|
|
1423
|
+
if (d === "")
|
|
1424
|
+
continue;
|
|
1425
|
+
if (d === undefined || d.includes("&") || !PATH_DATA.test(d)) {
|
|
1426
|
+
throw new VectorizeError("unsafe_svg", "VTracer output contains unsupported path data.");
|
|
1427
|
+
}
|
|
1428
|
+
if (fill === undefined) {
|
|
1429
|
+
throw new VectorizeError("unsafe_svg", "VTracer output contains a path without a fill.");
|
|
1430
|
+
}
|
|
1431
|
+
if (transform !== undefined && !TRANSLATE.test(transform)) {
|
|
1432
|
+
throw new VectorizeError("unsafe_svg", "VTracer output contains an unsupported path transform.");
|
|
1433
|
+
}
|
|
1434
|
+
const normalizedFill = normalizedHexColor(fill);
|
|
1435
|
+
paths.push({
|
|
1436
|
+
d,
|
|
1437
|
+
fill: normalizedFill,
|
|
1438
|
+
rgb: parseHexColor(normalizedFill),
|
|
1439
|
+
...transform === undefined ? {} : { transform }
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
if (paths.length === 0) {
|
|
1443
|
+
throw new VectorizeError("trace_failed", "VTracer output did not contain visible paths.");
|
|
1444
|
+
}
|
|
1445
|
+
return { paths, svg: buildColorSvg(paths, width, height) };
|
|
1446
|
+
}
|
|
1447
|
+
function buildColorSvg(paths, width, height, duotone) {
|
|
1448
|
+
const palette = duotone === undefined ? undefined : [
|
|
1449
|
+
normalizedHexColor(duotone.palette[0]),
|
|
1450
|
+
normalizedHexColor(duotone.palette[1])
|
|
1451
|
+
];
|
|
1452
|
+
const body = paths.map(({ d, fill, rgb, transform }) => {
|
|
1453
|
+
const outputFill = duotone === undefined || palette === undefined ? fill : colorBelongsToPrimary(rgb, duotone.model) ? palette[0] : palette[1];
|
|
1454
|
+
return ` <path d="${d}"${transform === undefined ? "" : ` transform="${transform}"`} fill="${outputFill}"/>`;
|
|
1455
|
+
});
|
|
1456
|
+
const svg = [
|
|
1457
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">`,
|
|
1458
|
+
...body,
|
|
1459
|
+
"</svg>",
|
|
1460
|
+
""
|
|
1461
|
+
].join(`
|
|
1462
|
+
`);
|
|
1463
|
+
assertSafeCanonicalSvg(svg);
|
|
1464
|
+
return svg;
|
|
1465
|
+
}
|
|
1466
|
+
function buildAlphaMaskedSvg(artworkPaths, maskPaths, width, height, duotone) {
|
|
1467
|
+
if (maskPaths.some(({ rgb }) => rgb[0] !== rgb[1] || rgb[1] !== rgb[2])) {
|
|
1468
|
+
throw new VectorizeError("unsafe_svg", "An alpha mask may contain only grayscale fills.");
|
|
1469
|
+
}
|
|
1470
|
+
const palette = duotone === undefined ? undefined : [
|
|
1471
|
+
normalizedHexColor(duotone.palette[0]),
|
|
1472
|
+
normalizedHexColor(duotone.palette[1])
|
|
1473
|
+
];
|
|
1474
|
+
const maskFingerprint = maskPaths.map(({ d, fill, transform }) => `${d}
|
|
1475
|
+
${fill}
|
|
1476
|
+
${transform ?? ""}`).join(`
|
|
1477
|
+
`);
|
|
1478
|
+
const maskId = `alpha-${sha256(maskFingerprint).slice(0, 16)}`;
|
|
1479
|
+
const svg = [
|
|
1480
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">`,
|
|
1481
|
+
" <defs>",
|
|
1482
|
+
` <mask id="${maskId}" maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse" x="0" y="0" width="${width}" height="${height}" mask-type="luminance">`,
|
|
1483
|
+
` <rect x="0" y="0" width="${width}" height="${height}" fill="#000000"/>`,
|
|
1484
|
+
...maskPaths.map(({ d, fill, transform }) => ` <path d="${d}"${transform === undefined ? "" : ` transform="${transform}"`} fill="${fill}"/>`),
|
|
1485
|
+
" </mask>",
|
|
1486
|
+
" </defs>",
|
|
1487
|
+
` <g mask="url(#${maskId})">`,
|
|
1488
|
+
...artworkPaths.map(({ d, fill, rgb, transform }) => {
|
|
1489
|
+
const outputFill = duotone === undefined || palette === undefined ? fill : colorBelongsToPrimary(rgb, duotone.model) ? palette[0] : palette[1];
|
|
1490
|
+
return ` <path d="${d}"${transform === undefined ? "" : ` transform="${transform}"`} fill="${outputFill}"/>`;
|
|
1491
|
+
}),
|
|
1492
|
+
" </g>",
|
|
1493
|
+
"</svg>",
|
|
1494
|
+
""
|
|
1495
|
+
].join(`
|
|
1496
|
+
`);
|
|
1497
|
+
assertSafeCanonicalSvg(svg);
|
|
1498
|
+
return svg;
|
|
1499
|
+
}
|
|
1500
|
+
function countSvgPaths(svg) {
|
|
1501
|
+
return svg.match(/<path\b/gu)?.length ?? 0;
|
|
1502
|
+
}
|
|
1503
|
+
function assertSafeCanonicalSvg(svg) {
|
|
1504
|
+
if (/<!DOCTYPE|<!ENTITY|<\?(?!xml)|<(?:a|animate|embed|filter|foreignObject|iframe|image|link|object|script|set|style|use)\b|(?:href|src)\s*=|\bon[a-z]+\s*=/iu.test(svg)) {
|
|
1505
|
+
throw new VectorizeError("unsafe_svg", "Canonical SVG contains active or external content.");
|
|
1506
|
+
}
|
|
1507
|
+
for (const match of svg.matchAll(/url\(([^)]+)\)/gu)) {
|
|
1508
|
+
if (!/^#[a-z0-9-]+$/u.test(match[1])) {
|
|
1509
|
+
throw new VectorizeError("unsafe_svg", "Canonical SVG contains an external URL.");
|
|
1510
|
+
}
|
|
1511
|
+
if (!svg.includes(`id="${match[1].slice(1)}"`)) {
|
|
1512
|
+
throw new VectorizeError("unsafe_svg", "Canonical SVG references an unknown local ID.");
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/vectorize/supervisor.ts
|
|
1518
|
+
import { fileURLToPath } from "url";
|
|
1519
|
+
import { mkdtemp as mkdtemp2, rm as rm2 } from "fs/promises";
|
|
1520
|
+
import { tmpdir } from "os";
|
|
1521
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
1522
|
+
var vectorizeErrorCodes = new Set([
|
|
1523
|
+
"input_limit",
|
|
1524
|
+
"invalid_input",
|
|
1525
|
+
"output_limit",
|
|
1526
|
+
"quality_limit",
|
|
1527
|
+
"timeout",
|
|
1528
|
+
"tool_download",
|
|
1529
|
+
"tool_integrity",
|
|
1530
|
+
"tool_platform",
|
|
1531
|
+
"tool_version",
|
|
1532
|
+
"trace_failed",
|
|
1533
|
+
"unsafe_svg"
|
|
1534
|
+
]);
|
|
1535
|
+
var WORKER_SHUTDOWN_RESERVE_MS = 250;
|
|
1536
|
+
var WORKER_RESPONSE_RESERVE_MS = 100;
|
|
1537
|
+
async function runVectorizeWorker(input, options) {
|
|
1538
|
+
const startedAt = performance.now();
|
|
1539
|
+
const limits = resolveVectorizeLimits(options.limits);
|
|
1540
|
+
if (process.platform === "win32") {
|
|
1541
|
+
throw new VectorizeError("tool_platform", "Bounded VTracer streaming is unavailable on Windows.", { platform: process.platform });
|
|
1542
|
+
}
|
|
1543
|
+
const workerInput = encodeInput(input, limits.maxInputBytes);
|
|
1544
|
+
const temporaryRoot = await mkdtemp2(join3(tmpdir(), "slopcamera-vectorize-"));
|
|
1545
|
+
let result;
|
|
1546
|
+
try {
|
|
1547
|
+
result = await executeVectorizeWorker(workerInput, options, limits, startedAt, temporaryRoot);
|
|
1548
|
+
} finally {
|
|
1549
|
+
await removeTemporaryRoot(temporaryRoot);
|
|
1550
|
+
}
|
|
1551
|
+
if (performance.now() - startedAt >= limits.maxDurationMs) {
|
|
1552
|
+
throw new VectorizeError("timeout", "Vectorization exceeded the conversion time limit during cleanup.");
|
|
1553
|
+
}
|
|
1554
|
+
return result;
|
|
1555
|
+
}
|
|
1556
|
+
async function executeVectorizeWorker(workerInput, options, limits, startedAt, temporaryRoot) {
|
|
1557
|
+
const preparationRemainingMs = limits.maxDurationMs - (performance.now() - startedAt);
|
|
1558
|
+
if (preparationRemainingMs <= WORKER_SHUTDOWN_RESERVE_MS + WORKER_RESPONSE_RESERVE_MS) {
|
|
1559
|
+
throw new VectorizeError("timeout", "Vectorization has no remaining budget for isolated worker execution.");
|
|
1560
|
+
}
|
|
1561
|
+
const workerDurationMs = Math.floor(preparationRemainingMs - WORKER_SHUTDOWN_RESERVE_MS - WORKER_RESPONSE_RESERVE_MS);
|
|
1562
|
+
const inheritedFileDescriptors = inheritedDescriptors(options.inheritedFileDescriptors);
|
|
1563
|
+
const workerInheritedFileDescriptors = inheritedFileDescriptors.map((_descriptor, index) => index + 3);
|
|
1564
|
+
const request = {
|
|
1565
|
+
input: workerInput,
|
|
1566
|
+
options: cloneOptions(options, workerDurationMs, workerInheritedFileDescriptors),
|
|
1567
|
+
protocol: VECTORIZE_WORKER_PROTOCOL,
|
|
1568
|
+
temporaryRoot
|
|
1569
|
+
};
|
|
1570
|
+
const requestBytes = Buffer.from(JSON.stringify(request));
|
|
1571
|
+
if (requestBytes.byteLength > MAX_VECTORIZE_REQUEST_BYTES) {
|
|
1572
|
+
throw new VectorizeError("input_limit", "The vectorization worker request exceeds its IPC limit.", {
|
|
1573
|
+
bytes: requestBytes.byteLength,
|
|
1574
|
+
maximumBytes: MAX_VECTORIZE_REQUEST_BYTES
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
const remainingMs = limits.maxDurationMs - (performance.now() - startedAt);
|
|
1578
|
+
if (remainingMs <= WORKER_SHUTDOWN_RESERVE_MS) {
|
|
1579
|
+
throw new VectorizeError("timeout", "Vectorization has no remaining budget for isolated worker startup and cleanup.");
|
|
1580
|
+
}
|
|
1581
|
+
const { stdout } = await runBoundedCommand([process.execPath, workerEntryPath()], Math.floor(remainingMs - WORKER_SHUTDOWN_RESERVE_MS), "trace_failed", {
|
|
1582
|
+
...inheritedFileDescriptors.length === 0 ? {} : { inheritedFileDescriptors },
|
|
1583
|
+
maxStdoutBytes: MAX_VECTORIZE_RESPONSE_BYTES,
|
|
1584
|
+
stdin: requestBytes
|
|
1585
|
+
});
|
|
1586
|
+
if (performance.now() - startedAt >= limits.maxDurationMs) {
|
|
1587
|
+
throw new VectorizeError("timeout", "Vectorization exceeded the conversion time limit.");
|
|
1588
|
+
}
|
|
1589
|
+
const response = parseResponse(stdout);
|
|
1590
|
+
if (!response.ok) {
|
|
1591
|
+
throw new VectorizeError(response.error.code, response.error.message, response.error.details);
|
|
1592
|
+
}
|
|
1593
|
+
assertResult(response.result, limits.maxOutputBytes);
|
|
1594
|
+
if (performance.now() - startedAt >= limits.maxDurationMs) {
|
|
1595
|
+
throw new VectorizeError("timeout", "Vectorization exceeded the conversion time limit.");
|
|
1596
|
+
}
|
|
1597
|
+
return response.result;
|
|
1598
|
+
}
|
|
1599
|
+
async function removeTemporaryRoot(temporaryRoot) {
|
|
1600
|
+
try {
|
|
1601
|
+
await rm2(temporaryRoot, { force: true, recursive: true });
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
throw new VectorizeError("trace_failed", "The isolated vectorization directory could not be removed.", { temporaryRoot }, { cause: error });
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
function encodeInput(input, maximumInputBytes) {
|
|
1607
|
+
return typeof input === "string" ? { kind: "path", value: input } : encodeBytes(input, maximumInputBytes);
|
|
1608
|
+
}
|
|
1609
|
+
function encodeBytes(input, maximumInputBytes) {
|
|
1610
|
+
const view = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
|
|
1611
|
+
if (view.byteLength < 1) {
|
|
1612
|
+
throw new VectorizeError("invalid_input", "Raster input is empty.");
|
|
1613
|
+
}
|
|
1614
|
+
if (view.byteLength > maximumInputBytes) {
|
|
1615
|
+
throw new VectorizeError("input_limit", `Raster input exceeds the ${maximumInputBytes}-byte limit.`, { bytes: view.byteLength, maximumBytes: maximumInputBytes });
|
|
1616
|
+
}
|
|
1617
|
+
return {
|
|
1618
|
+
kind: "bytes",
|
|
1619
|
+
value: Buffer.from(view.buffer, view.byteOffset, view.byteLength).toString("base64")
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
function cloneOptions(options, workerDurationMs, inheritedFileDescriptors) {
|
|
1623
|
+
return {
|
|
1624
|
+
...options.alphaCutoff === undefined ? {} : { alphaCutoff: options.alphaCutoff },
|
|
1625
|
+
...options.cacheDirectory === undefined ? {} : { cacheDirectory: options.cacheDirectory },
|
|
1626
|
+
...options.duotone === undefined ? {} : { duotone: [options.duotone[0], options.duotone[1]] },
|
|
1627
|
+
...inheritedFileDescriptors.length === 0 ? {} : { inheritedFileDescriptors },
|
|
1628
|
+
limits: {
|
|
1629
|
+
...options.limits,
|
|
1630
|
+
maxDurationMs: workerDurationMs
|
|
1631
|
+
},
|
|
1632
|
+
...options.outputPath === undefined ? {} : { outputPath: options.outputPath }
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
function inheritedDescriptors(value) {
|
|
1636
|
+
const descriptors = value ?? [];
|
|
1637
|
+
if (descriptors.length > 16 || descriptors.some((descriptor, index) => !Number.isSafeInteger(descriptor) || descriptor < 0 || descriptor > 2147483647 || descriptors.indexOf(descriptor) !== index)) {
|
|
1638
|
+
throw new VectorizeError("invalid_input", "Inherited vectorizer descriptors must be unique bounded integers.");
|
|
1639
|
+
}
|
|
1640
|
+
return Object.freeze([...descriptors]);
|
|
1641
|
+
}
|
|
1642
|
+
function workerEntryPath() {
|
|
1643
|
+
const modulePath = fileURLToPath(import.meta.url);
|
|
1644
|
+
return modulePath.endsWith(".ts") ? join3(dirname2(modulePath), "worker.ts") : join3(dirname2(modulePath), "vectorize", "worker.js");
|
|
1645
|
+
}
|
|
1646
|
+
function parseResponse(stdout) {
|
|
1647
|
+
let parsed;
|
|
1648
|
+
try {
|
|
1649
|
+
parsed = JSON.parse(stdout);
|
|
1650
|
+
} catch (error) {
|
|
1651
|
+
throw new VectorizeError("trace_failed", "The vectorization worker returned malformed output.", {}, { cause: error });
|
|
1652
|
+
}
|
|
1653
|
+
if (!isRecord(parsed) || parsed.protocol !== VECTORIZE_WORKER_PROTOCOL) {
|
|
1654
|
+
throw new VectorizeError("trace_failed", "The vectorization worker returned an incompatible response.");
|
|
1655
|
+
}
|
|
1656
|
+
if (parsed.ok === true && isVectorizeResult(parsed.result)) {
|
|
1657
|
+
return parsed;
|
|
1658
|
+
}
|
|
1659
|
+
if (parsed.ok === false && isRecord(parsed.error) && typeof parsed.error.code === "string" && vectorizeErrorCodes.has(parsed.error.code) && typeof parsed.error.message === "string" && isRecord(parsed.error.details)) {
|
|
1660
|
+
return parsed;
|
|
1661
|
+
}
|
|
1662
|
+
throw new VectorizeError("trace_failed", "The vectorization worker returned an invalid response.");
|
|
1663
|
+
}
|
|
1664
|
+
function assertResult(result, maximumOutputBytes) {
|
|
1665
|
+
const bytes = Buffer.byteLength(result.svg);
|
|
1666
|
+
if (bytes < 1 || bytes > maximumOutputBytes || result.receipt.bytes !== bytes || result.receipt.svgSha256.length !== 64) {
|
|
1667
|
+
throw new VectorizeError("trace_failed", "The vectorization worker response violates its output contract.", { bytes, maximumOutputBytes });
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
function isVectorizeResult(value) {
|
|
1671
|
+
if (!isRecord(value) || value.outputPath !== null && typeof value.outputPath !== "string" || typeof value.svg !== "string" || !isRecord(value.receipt)) {
|
|
1672
|
+
return false;
|
|
1673
|
+
}
|
|
1674
|
+
const profile = value.receipt.profile;
|
|
1675
|
+
return typeof value.receipt.bytes === "number" && typeof value.receipt.svgSha256 === "string" && typeof profile === "string" && vectorizeProfileNames.includes(profile);
|
|
1676
|
+
}
|
|
1677
|
+
function isRecord(value) {
|
|
1678
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// src/vectorize/vectorize.ts
|
|
1682
|
+
var DEFAULT_ALPHA_CUTOFF = 8;
|
|
1683
|
+
var COMPARE_LOW_ALPHA_MASS_RATIO = 0.002;
|
|
1684
|
+
var profiles = [
|
|
1685
|
+
{
|
|
1686
|
+
args: [
|
|
1687
|
+
"--colormode",
|
|
1688
|
+
"color",
|
|
1689
|
+
"--hierarchical",
|
|
1690
|
+
"stacked",
|
|
1691
|
+
"--mode",
|
|
1692
|
+
"spline",
|
|
1693
|
+
"--filter_speckle",
|
|
1694
|
+
"0",
|
|
1695
|
+
"--color_precision",
|
|
1696
|
+
"8",
|
|
1697
|
+
"--gradient_step",
|
|
1698
|
+
"4",
|
|
1699
|
+
"--segment_length",
|
|
1700
|
+
"4.5",
|
|
1701
|
+
"--path_precision",
|
|
1702
|
+
"4"
|
|
1703
|
+
],
|
|
1704
|
+
name: "balanced"
|
|
1705
|
+
},
|
|
1706
|
+
{
|
|
1707
|
+
args: [
|
|
1708
|
+
"--colormode",
|
|
1709
|
+
"color",
|
|
1710
|
+
"--hierarchical",
|
|
1711
|
+
"stacked",
|
|
1712
|
+
"--mode",
|
|
1713
|
+
"spline",
|
|
1714
|
+
"--filter_speckle",
|
|
1715
|
+
"0",
|
|
1716
|
+
"--color_precision",
|
|
1717
|
+
"8",
|
|
1718
|
+
"--gradient_step",
|
|
1719
|
+
"2",
|
|
1720
|
+
"--segment_length",
|
|
1721
|
+
"3.5",
|
|
1722
|
+
"--path_precision",
|
|
1723
|
+
"5"
|
|
1724
|
+
],
|
|
1725
|
+
name: "detailed"
|
|
1726
|
+
},
|
|
1727
|
+
{
|
|
1728
|
+
args: [
|
|
1729
|
+
"--preset",
|
|
1730
|
+
"photo",
|
|
1731
|
+
"--hierarchical",
|
|
1732
|
+
"stacked",
|
|
1733
|
+
"--filter_speckle",
|
|
1734
|
+
"0"
|
|
1735
|
+
],
|
|
1736
|
+
name: "photo"
|
|
1737
|
+
}
|
|
1738
|
+
];
|
|
1739
|
+
var alphaMaskArgs = [
|
|
1740
|
+
"--colormode",
|
|
1741
|
+
"color",
|
|
1742
|
+
"--hierarchical",
|
|
1743
|
+
"cutout",
|
|
1744
|
+
"--mode",
|
|
1745
|
+
"spline",
|
|
1746
|
+
"--filter_speckle",
|
|
1747
|
+
"0",
|
|
1748
|
+
"--color_precision",
|
|
1749
|
+
"8",
|
|
1750
|
+
"--gradient_step",
|
|
1751
|
+
"2",
|
|
1752
|
+
"--segment_length",
|
|
1753
|
+
"3.5",
|
|
1754
|
+
"--path_precision",
|
|
1755
|
+
"5",
|
|
1756
|
+
"--corner_threshold",
|
|
1757
|
+
"30",
|
|
1758
|
+
"--splice_threshold",
|
|
1759
|
+
"20"
|
|
1760
|
+
];
|
|
1761
|
+
function vectorizeImage(input, options = {}) {
|
|
1762
|
+
return runVectorizeWorker(input, options);
|
|
1763
|
+
}
|
|
1764
|
+
async function vectorizeImageInProcess(input, options = {}, temporaryRoot) {
|
|
1765
|
+
const limits = resolveVectorizeLimits(options.limits);
|
|
1766
|
+
const deadline = new VectorizeDeadline(limits.maxDurationMs);
|
|
1767
|
+
const alphaCutoff = options.alphaCutoff ?? DEFAULT_ALPHA_CUTOFF;
|
|
1768
|
+
if (!Number.isInteger(alphaCutoff) || alphaCutoff < 1 || alphaCutoff > 64) {
|
|
1769
|
+
throw new VectorizeError("invalid_input", "alphaCutoff must be an integer from 1 through 64.");
|
|
1770
|
+
}
|
|
1771
|
+
const duotonePalette = options.duotone === undefined ? undefined : [
|
|
1772
|
+
normalizedHexColor(options.duotone[0]),
|
|
1773
|
+
normalizedHexColor(options.duotone[1])
|
|
1774
|
+
];
|
|
1775
|
+
const raster = await loadRaster(input, limits, deadline);
|
|
1776
|
+
if (process.platform === "win32") {
|
|
1777
|
+
throw new VectorizeError("tool_platform", "Bounded VTracer streaming is unavailable on Windows.", { platform: process.platform });
|
|
1778
|
+
}
|
|
1779
|
+
const tool = await ensureVTracer(deadline, temporaryRoot, options.cacheDirectory);
|
|
1780
|
+
const errors = [];
|
|
1781
|
+
const candidates = [];
|
|
1782
|
+
const variations = traceVariations(raster.pixels, alphaCutoff);
|
|
1783
|
+
for (const variation of variations) {
|
|
1784
|
+
deadline.assert(`${variation.name} trace`);
|
|
1785
|
+
const sourcePath = join4(temporaryRoot, `${variation.name}.png`);
|
|
1786
|
+
await writeFile2(sourcePath, await encodeTracePng(variation.pixels, raster.width, raster.height));
|
|
1787
|
+
const balanced = await attemptCandidate(raster, variation, profiles[0], sourcePath, tool, temporaryRoot, limits, deadline, errors);
|
|
1788
|
+
if (balanced !== undefined)
|
|
1789
|
+
candidates.push(balanced);
|
|
1790
|
+
if (balanced !== undefined && passesFastQuality(balanced.quality))
|
|
1791
|
+
continue;
|
|
1792
|
+
const detailed = await attemptCandidate(raster, variation, profiles[1], sourcePath, tool, temporaryRoot, limits, deadline, errors);
|
|
1793
|
+
if (detailed !== undefined)
|
|
1794
|
+
candidates.push(detailed);
|
|
1795
|
+
if ([balanced, detailed].some((candidate) => candidate !== undefined && passesQuality(candidate.quality))) {
|
|
1796
|
+
continue;
|
|
1797
|
+
}
|
|
1798
|
+
const photo = await attemptCandidate(raster, variation, profiles[2], sourcePath, tool, temporaryRoot, limits, deadline, errors);
|
|
1799
|
+
if (photo !== undefined)
|
|
1800
|
+
candidates.push(photo);
|
|
1801
|
+
}
|
|
1802
|
+
const baseForMask = [...candidates].sort(compareFidelity)[0];
|
|
1803
|
+
if (baseForMask !== undefined && hasFractionalAlpha(raster.pixels) && baseForMask.quality.alphaRmse > 0.06) {
|
|
1804
|
+
const masked = await attemptAlphaMask(raster, baseForMask, tool, temporaryRoot, limits, deadline, errors);
|
|
1805
|
+
if (masked !== undefined)
|
|
1806
|
+
candidates.push(masked);
|
|
1807
|
+
}
|
|
1808
|
+
const eligible = candidates.filter((candidate) => candidate.bytes <= limits.maxOutputBytes && candidate.pathCount <= limits.maxPaths && passesQuality(candidate.quality));
|
|
1809
|
+
if (eligible.length === 0) {
|
|
1810
|
+
throw new VectorizeError("quality_limit", "No adaptive vector candidate passed the fidelity and output gates.", {
|
|
1811
|
+
candidates: candidates.map(candidateSummary),
|
|
1812
|
+
errors
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
const selected = selectCandidate(eligible);
|
|
1816
|
+
const duotone = duotonePalette === undefined ? undefined : {
|
|
1817
|
+
model: dominantOklabDuotoneModel(raster.pixels),
|
|
1818
|
+
palette: duotonePalette
|
|
1819
|
+
};
|
|
1820
|
+
const svg = selected.maskPaths === undefined ? buildColorSvg(selected.artworkPaths, raster.width, raster.height, duotone) : buildAlphaMaskedSvg(selected.artworkPaths, selected.maskPaths, raster.width, raster.height, duotone);
|
|
1821
|
+
assertSafeCanonicalSvg(svg);
|
|
1822
|
+
const bytes = Buffer.byteLength(svg);
|
|
1823
|
+
const pathCount = countSvgPaths(svg);
|
|
1824
|
+
if (bytes > limits.maxOutputBytes || pathCount > limits.maxPaths) {
|
|
1825
|
+
throw new VectorizeError("output_limit", `Canonical SVG exceeds ${limits.maxOutputBytes} bytes or ${limits.maxPaths} paths.`, { bytes, pathCount });
|
|
1826
|
+
}
|
|
1827
|
+
deadline.assert("output publication");
|
|
1828
|
+
const outputPath = options.outputPath === undefined ? null : await writeSvgAtomically(options.outputPath, svg);
|
|
1829
|
+
const pixelToolchain = sharpProvenance();
|
|
1830
|
+
return {
|
|
1831
|
+
outputPath,
|
|
1832
|
+
receipt: {
|
|
1833
|
+
alphaCutoff: selected.alphaCutoff,
|
|
1834
|
+
bytes,
|
|
1835
|
+
candidatesEvaluated: candidates.length,
|
|
1836
|
+
format: raster.format,
|
|
1837
|
+
height: raster.height,
|
|
1838
|
+
inputBytes: raster.inputBytes,
|
|
1839
|
+
outputMode: duotone === undefined ? "color" : "duotone",
|
|
1840
|
+
pathCount,
|
|
1841
|
+
profile: selected.profile,
|
|
1842
|
+
provenance: {
|
|
1843
|
+
arch: process.arch,
|
|
1844
|
+
platform: process.platform,
|
|
1845
|
+
sharp: pixelToolchain.sharp,
|
|
1846
|
+
sharpVersions: pixelToolchain.sharpVersions,
|
|
1847
|
+
vips: pixelToolchain.vips,
|
|
1848
|
+
vtracerSha256: tool.sha256,
|
|
1849
|
+
vtracerSource: tool.source,
|
|
1850
|
+
vtracerVersion: tool.version
|
|
1851
|
+
},
|
|
1852
|
+
quality: roundedQuality(selected.quality),
|
|
1853
|
+
receiptVersion: 1,
|
|
1854
|
+
representation: selected.representation,
|
|
1855
|
+
sourceSha256: raster.sourceSha256,
|
|
1856
|
+
svgSha256: sha256(svg),
|
|
1857
|
+
width: raster.width
|
|
1858
|
+
},
|
|
1859
|
+
svg
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
function traceVariations(pixels, alphaCutoff) {
|
|
1863
|
+
const sanitized = sanitizedTraceRgba(pixels, alphaCutoff);
|
|
1864
|
+
const output = [];
|
|
1865
|
+
if (containsVisiblePixel2(sanitized)) {
|
|
1866
|
+
output.push({ alphaCutoff, name: `alpha-${alphaCutoff}`, pixels: sanitized });
|
|
1867
|
+
}
|
|
1868
|
+
if (alphaCutoff > 1 && (output.length === 0 || lowAlphaMassRatio(pixels, alphaCutoff) >= COMPARE_LOW_ALPHA_MASS_RATIO)) {
|
|
1869
|
+
output.push({
|
|
1870
|
+
alphaCutoff: 1,
|
|
1871
|
+
name: "alpha-1",
|
|
1872
|
+
pixels: sanitizedTraceRgba(pixels, 1)
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
if (output.length === 0) {
|
|
1876
|
+
throw new VectorizeError("invalid_input", "Alpha sanitation removed every visible pixel.");
|
|
1877
|
+
}
|
|
1878
|
+
return output;
|
|
1879
|
+
}
|
|
1880
|
+
function containsVisiblePixel2(pixels) {
|
|
1881
|
+
for (let index = 3;index < pixels.length; index += 4) {
|
|
1882
|
+
if (pixels[index] > 0)
|
|
1883
|
+
return true;
|
|
1884
|
+
}
|
|
1885
|
+
return false;
|
|
1886
|
+
}
|
|
1887
|
+
async function attemptCandidate(raster, variation, profile, sourcePath, tool, temporaryRoot, limits, deadline, errors) {
|
|
1888
|
+
try {
|
|
1889
|
+
const raw = await traceRawSvg(tool, sourcePath, profile.args, temporaryRoot, limits.maxOutputBytes, deadline);
|
|
1890
|
+
deadline.assert(`${profile.name} trace`);
|
|
1891
|
+
const canonical = canonicalizeVTracerSvg(raw, raster.width, raster.height, limits.maxPaths);
|
|
1892
|
+
const bytes = Buffer.byteLength(canonical.svg);
|
|
1893
|
+
const pathCount = canonical.paths.length;
|
|
1894
|
+
if (bytes > limits.maxOutputBytes || pathCount > limits.maxPaths) {
|
|
1895
|
+
throw new VectorizeError("output_limit", `${profile.name} exceeds vector output limits.`);
|
|
1896
|
+
}
|
|
1897
|
+
const quality = await scoreSvg(canonical.svg, raster, limits.maxDecodedPixels, deadline);
|
|
1898
|
+
return {
|
|
1899
|
+
alphaCutoff: variation.alphaCutoff,
|
|
1900
|
+
artworkPaths: canonical.paths,
|
|
1901
|
+
bytes,
|
|
1902
|
+
pathCount,
|
|
1903
|
+
profile: profile.name,
|
|
1904
|
+
quality,
|
|
1905
|
+
representation: "color-paths",
|
|
1906
|
+
svg: canonical.svg
|
|
1907
|
+
};
|
|
1908
|
+
} catch (error) {
|
|
1909
|
+
if (error instanceof VectorizeError && error.code === "timeout")
|
|
1910
|
+
throw error;
|
|
1911
|
+
errors.push(`${variation.name}/${profile.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
async function attemptAlphaMask(raster, base, tool, temporaryRoot, limits, deadline, errors) {
|
|
1916
|
+
try {
|
|
1917
|
+
const alphaPixels = alphaPlaneTraceRgba(raster.pixels);
|
|
1918
|
+
const sourcePath = join4(temporaryRoot, "alpha-plane.png");
|
|
1919
|
+
await writeFile2(sourcePath, await encodeTracePng(alphaPixels, raster.width, raster.height));
|
|
1920
|
+
const raw = await traceRawSvg(tool, sourcePath, alphaMaskArgs, temporaryRoot, limits.maxOutputBytes, deadline);
|
|
1921
|
+
const mask = canonicalizeVTracerSvg(raw, raster.width, raster.height, limits.maxPaths);
|
|
1922
|
+
const pathCount = base.artworkPaths.length + mask.paths.length;
|
|
1923
|
+
if (pathCount > limits.maxPaths) {
|
|
1924
|
+
throw new VectorizeError("output_limit", "Alpha-masked output exceeds the path limit.");
|
|
1925
|
+
}
|
|
1926
|
+
const svg = buildAlphaMaskedSvg(base.artworkPaths, mask.paths, raster.width, raster.height);
|
|
1927
|
+
const bytes = Buffer.byteLength(svg);
|
|
1928
|
+
if (bytes > limits.maxOutputBytes) {
|
|
1929
|
+
throw new VectorizeError("output_limit", "Alpha-masked output exceeds the byte limit.");
|
|
1930
|
+
}
|
|
1931
|
+
const quality = await scoreSvg(svg, raster, limits.maxDecodedPixels, deadline);
|
|
1932
|
+
return {
|
|
1933
|
+
alphaCutoff: base.alphaCutoff,
|
|
1934
|
+
artworkPaths: base.artworkPaths,
|
|
1935
|
+
bytes,
|
|
1936
|
+
maskPaths: mask.paths,
|
|
1937
|
+
pathCount,
|
|
1938
|
+
profile: base.profile,
|
|
1939
|
+
quality,
|
|
1940
|
+
representation: "alpha-mask",
|
|
1941
|
+
svg
|
|
1942
|
+
};
|
|
1943
|
+
} catch (error) {
|
|
1944
|
+
if (error instanceof VectorizeError && error.code === "timeout")
|
|
1945
|
+
throw error;
|
|
1946
|
+
errors.push(`alpha-mask: ${error instanceof Error ? error.message : String(error)}`);
|
|
1947
|
+
return;
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
async function scoreSvg(svg, raster, maxDecodedPixels, deadline) {
|
|
1951
|
+
const candidatePixels = await renderSvgRgba(svg, raster.scoreWidth, raster.scoreHeight, maxDecodedPixels);
|
|
1952
|
+
deadline.assert("quality measurement");
|
|
1953
|
+
const support = measureSupport(raster.scorePixels, candidatePixels, raster.scoreWidth, raster.scoreHeight, 1);
|
|
1954
|
+
return {
|
|
1955
|
+
alphaRmse: normalizedAlphaRmse(raster.scorePixels, candidatePixels),
|
|
1956
|
+
colorRmse: normalizedPremultipliedRmse(raster.scorePixels, candidatePixels),
|
|
1957
|
+
outsideAlphaRatio: support.outsideAlphaRatio,
|
|
1958
|
+
sampleHeight: raster.scoreHeight,
|
|
1959
|
+
sampleWidth: raster.scoreWidth,
|
|
1960
|
+
supportRecall: support.supportRecall
|
|
1961
|
+
};
|
|
1962
|
+
}
|
|
1963
|
+
async function traceRawSvg(tool, sourcePath, args, temporaryRoot, maximumBytes, deadline) {
|
|
1964
|
+
const { output } = await runBoundedPathOutputCommand((outputPath) => [
|
|
1965
|
+
tool.path,
|
|
1966
|
+
"--input",
|
|
1967
|
+
sourcePath,
|
|
1968
|
+
"--output",
|
|
1969
|
+
outputPath,
|
|
1970
|
+
...args
|
|
1971
|
+
], deadline.remainingMs(), "trace_failed", {
|
|
1972
|
+
maxOutputBytes: maximumBytes,
|
|
1973
|
+
temporaryRoot
|
|
1974
|
+
});
|
|
1975
|
+
if (output.length === 0) {
|
|
1976
|
+
throw new VectorizeError("trace_failed", "VTracer did not emit an SVG.");
|
|
1977
|
+
}
|
|
1978
|
+
return output;
|
|
1979
|
+
}
|
|
1980
|
+
function passesFastQuality(quality) {
|
|
1981
|
+
return passesQuality(quality) && quality.colorRmse <= 0.12 && quality.alphaRmse <= 0.18 && quality.outsideAlphaRatio <= 0.02 && quality.supportRecall >= 0.97;
|
|
1982
|
+
}
|
|
1983
|
+
function passesQuality(quality) {
|
|
1984
|
+
return quality.colorRmse <= 0.3 && quality.alphaRmse <= 0.3 && quality.outsideAlphaRatio <= 0.15 && quality.supportRecall >= 0.8;
|
|
1985
|
+
}
|
|
1986
|
+
function compareFidelity(left, right) {
|
|
1987
|
+
return left.quality.colorRmse - right.quality.colorRmse || left.quality.alphaRmse - right.quality.alphaRmse || left.bytes - right.bytes || left.pathCount - right.pathCount || left.profile.localeCompare(right.profile);
|
|
1988
|
+
}
|
|
1989
|
+
function selectCandidate(candidates) {
|
|
1990
|
+
const bestRmse = Math.min(...candidates.map(({ quality }) => quality.colorRmse));
|
|
1991
|
+
const fidelityWindow = candidates.filter(({ quality }) => quality.colorRmse <= bestRmse + 0.005);
|
|
1992
|
+
return [...fidelityWindow].sort((left, right) => left.bytes - right.bytes || left.pathCount - right.pathCount || left.quality.alphaRmse - right.quality.alphaRmse || left.profile.localeCompare(right.profile) || left.representation.localeCompare(right.representation))[0];
|
|
1993
|
+
}
|
|
1994
|
+
function roundedQuality(quality) {
|
|
1995
|
+
const rounded = (value) => Number(value.toFixed(8));
|
|
1996
|
+
return {
|
|
1997
|
+
alphaRmse: rounded(quality.alphaRmse),
|
|
1998
|
+
colorRmse: rounded(quality.colorRmse),
|
|
1999
|
+
outsideAlphaRatio: rounded(quality.outsideAlphaRatio),
|
|
2000
|
+
sampleHeight: quality.sampleHeight,
|
|
2001
|
+
sampleWidth: quality.sampleWidth,
|
|
2002
|
+
supportRecall: rounded(quality.supportRecall)
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
function candidateSummary(candidate) {
|
|
2006
|
+
return {
|
|
2007
|
+
alphaCutoff: candidate.alphaCutoff,
|
|
2008
|
+
bytes: candidate.bytes,
|
|
2009
|
+
pathCount: candidate.pathCount,
|
|
2010
|
+
profile: candidate.profile,
|
|
2011
|
+
quality: roundedQuality(candidate.quality),
|
|
2012
|
+
representation: candidate.representation
|
|
2013
|
+
};
|
|
2014
|
+
}
|
|
2015
|
+
async function writeSvgAtomically(path, svg) {
|
|
2016
|
+
const outputPath = resolve3(path);
|
|
2017
|
+
await mkdir2(dirname3(outputPath), { recursive: true });
|
|
2018
|
+
const temporaryPath = `${outputPath}.${randomUUID2()}.tmp`;
|
|
2019
|
+
try {
|
|
2020
|
+
await writeFile2(temporaryPath, svg, { flag: "wx" });
|
|
2021
|
+
await rename2(temporaryPath, outputPath);
|
|
2022
|
+
} catch (error) {
|
|
2023
|
+
await rm3(temporaryPath, { force: true });
|
|
2024
|
+
throw new VectorizeError("output_limit", `Could not atomically write ${outputPath}.`, {}, { cause: error });
|
|
2025
|
+
}
|
|
2026
|
+
return outputPath;
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
export { nonGatewayChildEnvironment, vectorizeProfileNames, VectorizeError, vectorizeHardLimits, vectorizeDefaultLimits, withInheritedCommandFileDescriptors, forwardVectorizeWorkerTermination, VTRACER_VERSION, vtracerReleases, configureVectorizeSharpConcurrency, VECTORIZE_WORKER_PROTOCOL, MAX_VECTORIZE_REQUEST_BYTES, MAX_VECTORIZE_RESPONSE_BYTES, vectorizeImage, vectorizeImageInProcess };
|