@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,2518 @@
|
|
|
1
|
+
// Image metadata: reading what a JPEG, PNG or WebP says about
|
|
2
|
+
// itself (EXIF, XMP, PNG text, ICC presence, Content Credentials), and editing
|
|
3
|
+
// it without touching the pixels where the format allows.
|
|
4
|
+
//
|
|
5
|
+
// A small hand-written reader and writer, no dependency. It runs in the
|
|
6
|
+
// sandbox Worker (the module "mallory:media/metadata", behind imageMetadata(),
|
|
7
|
+
// stripImageMetadata() and fixImageOrientation()), in the metadata Worker the
|
|
8
|
+
// page uses, and under Node, so it has no imports and no DOM. It only ever
|
|
9
|
+
// reads bytes it is handed and never executes, fetches or decodes anything:
|
|
10
|
+
// XMP is matched as text. Compressed PNG text is reported, not inflated, by the
|
|
11
|
+
// synchronous inspect()/edit(); the async layer (inspectAsync, editAsync and the
|
|
12
|
+
// Blob functions) inflates PNG "Raw profile" entries with DecompressionStream,
|
|
13
|
+
// bounded, to read and remove a location inside them.
|
|
14
|
+
//
|
|
15
|
+
// Bounded on purpose (LIMITS): bytes read, segments and chunks walked, tags
|
|
16
|
+
// listed, text kept, errors reported. Every offset in a file is checked
|
|
17
|
+
// against the bytes there are, a pointer that loops or lands on another
|
|
18
|
+
// structure is refused, and a malformed part becomes a short entry in
|
|
19
|
+
// `errors`, never an exception: `inspect(bytes)` and `edit(bytes, …)` return
|
|
20
|
+
// `{ ok: false, reason, message }` rather than throw on any input.
|
|
21
|
+
//
|
|
22
|
+
// What a report says is split in two on purpose. `$personalMetadata` holds
|
|
23
|
+
// everything about the person, place or device (GPS, owner, serial numbers,
|
|
24
|
+
// descriptions, dates, camera make and model, XMP, text chunks); the rest
|
|
25
|
+
// (format, size, orientation, what is present, technical camera settings) is
|
|
26
|
+
// the report's summary. A run log's retention policy treats the first as
|
|
27
|
+
// payload (src/model/retention.js ALWAYS_REDACTED).
|
|
28
|
+
|
|
29
|
+
export const LIMITS = {
|
|
30
|
+
bytes: 64 * 1024 * 1024, // the most bytes of an image read or rewritten
|
|
31
|
+
segments: 512, // JPEG segments, PNG/WebP chunks walked
|
|
32
|
+
chunks: 4096,
|
|
33
|
+
tags: 400, // EXIF tags listed across all IFDs
|
|
34
|
+
ifds: 6,
|
|
35
|
+
textEntries: 64, // PNG text chunks listed
|
|
36
|
+
textChars: 512, // characters kept of any text value
|
|
37
|
+
xmpBytes: 256 * 1024, // XMP read
|
|
38
|
+
xmpProps: 100,
|
|
39
|
+
errors: 16,
|
|
40
|
+
tagBytes: 65536, // one EXIF value larger than this is not read
|
|
41
|
+
exifBytes: 65528, // a JPEG APP1 segment holds at most this much EXIF
|
|
42
|
+
iptcDatasets: 256, // IPTC datasets listed from one block
|
|
43
|
+
rawProfiles: 8, // PNG "Raw profile type …" entries decoded
|
|
44
|
+
rawProfileBytes: 4 * 1024 * 1024, // one raw profile, inflated
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const FORMAT_NAME = { jpeg: "JPEG", png: "PNG", webp: "WebP" };
|
|
48
|
+
const SUPPORTED = "JPEG, PNG and WebP";
|
|
49
|
+
|
|
50
|
+
/** "jpeg", "png", "webp", or null: from the first bytes, never from a name or MIME type. */
|
|
51
|
+
export function detectFormat(b) {
|
|
52
|
+
if (!b || b.length < 12) return b && b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff ? "jpeg" : null;
|
|
53
|
+
if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "jpeg";
|
|
54
|
+
if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47 && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a) return "png";
|
|
55
|
+
if (ascii(b, 0, 4) === "RIFF" && ascii(b, 8, 4) === "WEBP") return "webp";
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ── orientation of the formats the metadata editors don't open ──────────────
|
|
60
|
+
|
|
61
|
+
const OTHER_NAME = { gif: "GIF", tiff: "TIFF", avif: "AVIF", heic: "HEIC" };
|
|
62
|
+
const HEIC_BRANDS = new Set(["heic", "heix", "hevc", "hevx", "heim", "heis", "hevm", "hevs", "mif1", "msf1"]);
|
|
63
|
+
|
|
64
|
+
/** "gif", "tiff", "avif", "heic" or null: a format whose orientation is read but whose metadata is left alone. */
|
|
65
|
+
function detectOther(b) {
|
|
66
|
+
if (b.length >= 6 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38 && (b[4] === 0x37 || b[4] === 0x39) && b[5] === 0x61) return "gif";
|
|
67
|
+
if (b.length >= 8 && ((b[0] === 0x49 && b[1] === 0x49 && b[2] === 0x2a && b[3] === 0) || (b[0] === 0x4d && b[1] === 0x4d && b[2] === 0 && b[3] === 0x2a))) return "tiff";
|
|
68
|
+
if (b.length >= 16 && ascii(b, 4, 4) === "ftyp") {
|
|
69
|
+
const size = Math.min(be32(b, 0), b.length);
|
|
70
|
+
const brands = [ascii(b, 8, 4)];
|
|
71
|
+
for (let at = 16; at + 4 <= size && brands.length < 12; at += 4) brands.push(ascii(b, at, 4));
|
|
72
|
+
if (brands.some((x) => x === "avif" || x === "avis")) return "avif";
|
|
73
|
+
if (brands.some((x) => HEIC_BRANDS.has(x))) return "heic";
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The boxes of an ISO base media file between `from` and `to`: `{ type, data, end }`; a box that runs past `to` ends the list. */
|
|
79
|
+
function isoBoxes(b, from, to) {
|
|
80
|
+
const out = [];
|
|
81
|
+
let at = from;
|
|
82
|
+
while (at + 8 <= to && out.length < 2000) {
|
|
83
|
+
let size = be32(b, at);
|
|
84
|
+
let head = 8;
|
|
85
|
+
if (size === 1) {
|
|
86
|
+
if (at + 16 > to || be32(b, at + 8) !== 0) break;
|
|
87
|
+
size = be32(b, at + 12);
|
|
88
|
+
head = 16;
|
|
89
|
+
} else if (size === 0) size = to - at;
|
|
90
|
+
if (size < head || at + size > to) break;
|
|
91
|
+
out.push({ type: ascii(b, at + 4, 4), data: at + head, end: at + size });
|
|
92
|
+
at += size;
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The 2×2 matrices of the eight EXIF orientations, mapping stored (x, y) to displayed ((x, y) down the page).
|
|
98
|
+
const ORIENT_MATRIX = { 1: [1, 0, 0, 1], 2: [-1, 0, 0, 1], 3: [-1, 0, 0, -1], 4: [1, 0, 0, -1], 5: [0, 1, 1, 0], 6: [0, -1, 1, 0], 7: [0, -1, -1, 0], 8: [0, 1, -1, 0] };
|
|
99
|
+
const mul2 = (m, n) => [m[0] * n[0] + m[1] * n[2], m[0] * n[1] + m[1] * n[3], m[2] * n[0] + m[3] * n[2], m[2] * n[1] + m[3] * n[3]];
|
|
100
|
+
|
|
101
|
+
/** A HEIF-family file's orientation from the rotation (`irot`) and mirror (`imir`) properties of its primary item, and its size. */
|
|
102
|
+
function readHeifOrientation(b) {
|
|
103
|
+
const out = {};
|
|
104
|
+
const top = isoBoxes(b, 0, b.length);
|
|
105
|
+
const meta = top.find((x) => x.type === "meta");
|
|
106
|
+
if (!meta || meta.data + 4 > meta.end) return out;
|
|
107
|
+
const inner = isoBoxes(b, meta.data + 4, meta.end);
|
|
108
|
+
const pitm = inner.find((x) => x.type === "pitm");
|
|
109
|
+
let primary;
|
|
110
|
+
if (pitm && pitm.data + 6 <= pitm.end) primary = b[pitm.data] === 0 ? be16(b, pitm.data + 4) : pitm.data + 8 <= pitm.end ? be32(b, pitm.data + 4) : undefined;
|
|
111
|
+
const iprp = inner.find((x) => x.type === "iprp");
|
|
112
|
+
if (!iprp) return out;
|
|
113
|
+
const parts = isoBoxes(b, iprp.data, iprp.end);
|
|
114
|
+
const ipco = parts.find((x) => x.type === "ipco");
|
|
115
|
+
const ipma = parts.find((x) => x.type === "ipma");
|
|
116
|
+
if (!ipco || !ipma || ipma.data + 8 > ipma.end) return out;
|
|
117
|
+
const props = isoBoxes(b, ipco.data, ipco.end);
|
|
118
|
+
const version = b[ipma.data];
|
|
119
|
+
const wide = b[ipma.data + 3] & 1;
|
|
120
|
+
let n = Math.min(be32(b, ipma.data + 4), 4096);
|
|
121
|
+
let at = ipma.data + 8;
|
|
122
|
+
let chosen;
|
|
123
|
+
while (n-- > 0 && at + (version < 1 ? 3 : 5) <= ipma.end) {
|
|
124
|
+
const id = version < 1 ? be16(b, at) : be32(b, at);
|
|
125
|
+
at += version < 1 ? 2 : 4;
|
|
126
|
+
const count = b[at++];
|
|
127
|
+
const list = [];
|
|
128
|
+
for (let i = 0; i < count && at + (wide ? 2 : 1) <= ipma.end; i++) {
|
|
129
|
+
list.push(wide ? be16(b, at) & 0x7fff : b[at] & 0x7f);
|
|
130
|
+
at += wide ? 2 : 1;
|
|
131
|
+
}
|
|
132
|
+
if (primary === undefined || id === primary) {
|
|
133
|
+
chosen = list;
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (!chosen) return out;
|
|
138
|
+
let m = ORIENT_MATRIX[1];
|
|
139
|
+
let moved = false;
|
|
140
|
+
for (const index of chosen) {
|
|
141
|
+
const p = props[index - 1];
|
|
142
|
+
if (!p) continue;
|
|
143
|
+
if (p.type === "ispe" && p.data + 12 <= p.end && out.width === undefined) {
|
|
144
|
+
out.width = be32(b, p.data + 4);
|
|
145
|
+
out.height = be32(b, p.data + 8);
|
|
146
|
+
} else if (p.type === "irot" && p.data < p.end) {
|
|
147
|
+
m = mul2([[1, 0, 0, 1], [0, 1, -1, 0], [-1, 0, 0, -1], [0, -1, 1, 0]][b[p.data] & 3], m); // counterclockwise quarter turns
|
|
148
|
+
moved = true;
|
|
149
|
+
} else if (p.type === "imir" && p.data < p.end) {
|
|
150
|
+
m = mul2(b[p.data] & 1 ? [1, 0, 0, -1] : [-1, 0, 0, 1], m); // axis 0: left and right swap; axis 1: top and bottom
|
|
151
|
+
moved = true;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (moved) out.orientation = Number(Object.keys(ORIENT_MATRIX).find((k) => ORIENT_MATRIX[k].every((v, i) => v === m[i]) )) || undefined;
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A GIF's size and whether it has more than one frame (blocks walked, bounded). */
|
|
159
|
+
function readGif(b) {
|
|
160
|
+
const out = { width: le16(b, 6), height: le16(b, 8), animated: false };
|
|
161
|
+
if (b.length < 13) return out;
|
|
162
|
+
let at = 13 + (b[10] & 0x80 ? 3 * 2 ** ((b[10] & 7) + 1) : 0);
|
|
163
|
+
let frames = 0;
|
|
164
|
+
for (let step = 0; step < 20000 && at < b.length; step++) {
|
|
165
|
+
const kind = b[at];
|
|
166
|
+
if (kind === 0x3b) break;
|
|
167
|
+
if (kind === 0x2c) {
|
|
168
|
+
frames++;
|
|
169
|
+
if (frames > 1) break;
|
|
170
|
+
if (at + 10 > b.length) break;
|
|
171
|
+
at += 10 + (b[at + 9] & 0x80 ? 3 * 2 ** ((b[at + 9] & 7) + 1) : 0) + 1;
|
|
172
|
+
} else if (kind === 0x21) at += 2;
|
|
173
|
+
else break;
|
|
174
|
+
while (at < b.length && b[at] !== 0) at += b[at] + 1; // data sub-blocks
|
|
175
|
+
at++;
|
|
176
|
+
}
|
|
177
|
+
out.animated = frames > 1;
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* What the first bytes of a TIFF, AVIF, HEIC or GIF say about orientation (the metadata editors don't open these formats,
|
|
183
|
+
* so nothing else about them is read): `{ format, orientation?, orientationText?, width?, height?, animated? }`, or `null`.
|
|
184
|
+
* A TIFF carries the EXIF orientation tag in its first directory; an AVIF or HEIC carries a rotation and a mirror property
|
|
185
|
+
* of its primary image (part of the image itself, applied by whatever draws it); a GIF has none. Never throws.
|
|
186
|
+
*/
|
|
187
|
+
export function orientationOf(bytes) {
|
|
188
|
+
try {
|
|
189
|
+
if (!(bytes instanceof Uint8Array) || bytes.length > LIMITS.bytes) return null;
|
|
190
|
+
const format = detectOther(bytes);
|
|
191
|
+
if (!format) return null;
|
|
192
|
+
const out = { format };
|
|
193
|
+
if (format === "tiff") {
|
|
194
|
+
const walk = walkTiff(bytes, new Errors());
|
|
195
|
+
const e = walk.ok ? findEntry(walk, "ifd0", 0x0112) : undefined;
|
|
196
|
+
const v = e ? valueOf(bytes, e, walk.le) : undefined;
|
|
197
|
+
if (typeof v === "number") out.orientation = v;
|
|
198
|
+
} else if (format === "gif") Object.assign(out, readGif(bytes));
|
|
199
|
+
else Object.assign(out, readHeifOrientation(bytes));
|
|
200
|
+
out.orientationText = out.orientation ? ORIENTATION_TEXT[out.orientation] ?? "not a valid EXIF orientation (1 to 8)" : format === "gif" ? "a GIF has no orientation: it is always drawn as stored" : "no orientation recorded";
|
|
201
|
+
return out;
|
|
202
|
+
} catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ── small helpers ────────────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
const ascii = (b, at, n) => {
|
|
210
|
+
let s = "";
|
|
211
|
+
for (let i = at; i < at + n && i < b.length; i++) s += String.fromCharCode(b[i]);
|
|
212
|
+
return s;
|
|
213
|
+
};
|
|
214
|
+
const be16 = (b, at) => (b[at] << 8) | b[at + 1];
|
|
215
|
+
const be32 = (b, at) => ((b[at] << 24) | (b[at + 1] << 16) | (b[at + 2] << 8) | b[at + 3]) >>> 0;
|
|
216
|
+
const le16 = (b, at) => b[at] | (b[at + 1] << 8);
|
|
217
|
+
const le32 = (b, at) => (b[at] | (b[at + 1] << 8) | (b[at + 2] << 16) | (b[at + 3] << 24)) >>> 0;
|
|
218
|
+
const put32le = (b, at, v) => {
|
|
219
|
+
b[at] = v & 255;
|
|
220
|
+
b[at + 1] = (v >>> 8) & 255;
|
|
221
|
+
b[at + 2] = (v >>> 16) & 255;
|
|
222
|
+
b[at + 3] = (v >>> 24) & 255;
|
|
223
|
+
};
|
|
224
|
+
const put32be = (b, at, v) => {
|
|
225
|
+
b[at] = (v >>> 24) & 255;
|
|
226
|
+
b[at + 1] = (v >>> 16) & 255;
|
|
227
|
+
b[at + 2] = (v >>> 8) & 255;
|
|
228
|
+
b[at + 3] = v & 255;
|
|
229
|
+
};
|
|
230
|
+
const startsWith = (b, at, text) => at + text.length <= b.length && ascii(b, at, text.length) === text;
|
|
231
|
+
const clip = (s, n = LIMITS.textChars) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
|
232
|
+
const concat = (parts) => {
|
|
233
|
+
let n = 0;
|
|
234
|
+
for (const p of parts) n += p.length;
|
|
235
|
+
const out = new Uint8Array(n);
|
|
236
|
+
let at = 0;
|
|
237
|
+
for (const p of parts) (out.set(p, at), (at += p.length));
|
|
238
|
+
return out;
|
|
239
|
+
};
|
|
240
|
+
const latin1 = (b) => {
|
|
241
|
+
let s = "";
|
|
242
|
+
for (let i = 0; i < b.length; i += 0x4000) s += String.fromCharCode(...b.subarray(i, i + 0x4000));
|
|
243
|
+
return s;
|
|
244
|
+
};
|
|
245
|
+
const fromLatin1 = (s) => {
|
|
246
|
+
const out = new Uint8Array(s.length);
|
|
247
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) & 255;
|
|
248
|
+
return out;
|
|
249
|
+
};
|
|
250
|
+
const utf8 = (b) => {
|
|
251
|
+
try {
|
|
252
|
+
return new TextDecoder("utf-8", { fatal: false }).decode(b);
|
|
253
|
+
} catch {
|
|
254
|
+
return latin1(b);
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
const printable = (s) => s.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").trim();
|
|
258
|
+
|
|
259
|
+
class Errors {
|
|
260
|
+
constructor() {
|
|
261
|
+
this.list = [];
|
|
262
|
+
this.more = 0;
|
|
263
|
+
}
|
|
264
|
+
add(message) {
|
|
265
|
+
if (this.list.length < LIMITS.errors) this.list.push(clip(String(message), 200));
|
|
266
|
+
else this.more++;
|
|
267
|
+
}
|
|
268
|
+
out() {
|
|
269
|
+
return this.more ? [...this.list, `${this.more} more problems not listed`] : this.list;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
let crcTable;
|
|
274
|
+
function crc32(bytes) {
|
|
275
|
+
if (!crcTable) {
|
|
276
|
+
crcTable = new Uint32Array(256);
|
|
277
|
+
for (let n = 0; n < 256; n++) {
|
|
278
|
+
let c = n;
|
|
279
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
280
|
+
crcTable[n] = c >>> 0;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
let crc = 0xffffffff;
|
|
284
|
+
for (let i = 0; i < bytes.length; i++) crc = crcTable[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
|
285
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ── EXIF / TIFF ──────────────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
const TYPE_SIZE = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8, 13: 4 };
|
|
291
|
+
const T_ASCII = 2;
|
|
292
|
+
const T_SHORT = 3;
|
|
293
|
+
const T_LONG = 4;
|
|
294
|
+
const T_RATIONAL = 5;
|
|
295
|
+
|
|
296
|
+
// name, and whether the field is a technical one (kept in the summary). Anything
|
|
297
|
+
// not listed here is personal: it is about the person, the place or the device.
|
|
298
|
+
const IFD0_TAGS = {
|
|
299
|
+
0x0100: ["ImageWidth", true], 0x0101: ["ImageHeight", true], 0x0102: ["BitsPerSample", true], 0x0106: ["PhotometricInterpretation", true],
|
|
300
|
+
0x010e: ["ImageDescription", false], 0x010f: ["Make", false], 0x0110: ["Model", false], 0x0112: ["Orientation", true],
|
|
301
|
+
0x011a: ["XResolution", true], 0x011b: ["YResolution", true], 0x0128: ["ResolutionUnit", true], 0x0131: ["Software", false],
|
|
302
|
+
0x0132: ["DateTime", false], 0x013b: ["Artist", false], 0x0213: ["YCbCrPositioning", true], 0x8298: ["Copyright", false],
|
|
303
|
+
0x8769: ["ExifIFDPointer", true], 0x8825: ["GPSInfoIFDPointer", false], 0x0201: ["JPEGInterchangeFormat", true], 0x0202: ["JPEGInterchangeFormatLength", true],
|
|
304
|
+
0x0103: ["Compression", true],
|
|
305
|
+
};
|
|
306
|
+
const EXIF_TAGS = {
|
|
307
|
+
0x829a: ["ExposureTime", true], 0x829d: ["FNumber", true], 0x8822: ["ExposureProgram", true], 0x8827: ["ISOSpeedRatings", true],
|
|
308
|
+
0x9000: ["ExifVersion", true], 0x9003: ["DateTimeOriginal", false], 0x9004: ["DateTimeDigitized", false], 0x9201: ["ShutterSpeedValue", true],
|
|
309
|
+
0x9202: ["ApertureValue", true], 0x9204: ["ExposureBiasValue", true], 0x9207: ["MeteringMode", true], 0x9209: ["Flash", true],
|
|
310
|
+
0x920a: ["FocalLength", true], 0x927c: ["MakerNote", false], 0x9286: ["UserComment", false], 0x9290: ["SubSecTime", false],
|
|
311
|
+
0xa001: ["ColorSpace", true], 0xa002: ["PixelXDimension", true], 0xa003: ["PixelYDimension", true], 0xa005: ["InteroperabilityIFDPointer", true],
|
|
312
|
+
0xa217: ["SensingMethod", true], 0xa401: ["CustomRendered", true], 0xa402: ["ExposureMode", true], 0xa403: ["WhiteBalance", true],
|
|
313
|
+
0xa404: ["DigitalZoomRatio", true], 0xa405: ["FocalLengthIn35mmFilm", true], 0xa406: ["SceneCaptureType", true],
|
|
314
|
+
0xa420: ["ImageUniqueID", false], 0xa430: ["CameraOwnerName", false], 0xa431: ["BodySerialNumber", false], 0xa432: ["LensSpecification", true],
|
|
315
|
+
0xa433: ["LensMake", false], 0xa434: ["LensModel", false], 0xa435: ["LensSerialNumber", false],
|
|
316
|
+
};
|
|
317
|
+
const GPS_TAGS = {
|
|
318
|
+
0: "GPSVersionID", 1: "GPSLatitudeRef", 2: "GPSLatitude", 3: "GPSLongitudeRef", 4: "GPSLongitude", 5: "GPSAltitudeRef", 6: "GPSAltitude",
|
|
319
|
+
7: "GPSTimeStamp", 8: "GPSSatellites", 9: "GPSStatus", 10: "GPSMeasureMode", 11: "GPSDOP", 12: "GPSSpeedRef", 13: "GPSSpeed", 14: "GPSTrackRef",
|
|
320
|
+
15: "GPSTrack", 16: "GPSImgDirectionRef", 17: "GPSImgDirection", 18: "GPSMapDatum", 19: "GPSDestLatitudeRef", 20: "GPSDestLatitude",
|
|
321
|
+
21: "GPSDestLongitudeRef", 22: "GPSDestLongitude", 23: "GPSDestBearingRef", 24: "GPSDestBearing", 25: "GPSDestDistanceRef", 26: "GPSDestDistance",
|
|
322
|
+
27: "GPSProcessingMethod", 28: "GPSAreaInformation", 29: "GPSDateStamp", 30: "GPSDifferential", 31: "GPSHPositioningError",
|
|
323
|
+
};
|
|
324
|
+
const ORIENTATION_TEXT = { 1: "upright", 2: "mirrored horizontally", 3: "rotated 180°", 4: "mirrored vertically", 5: "transposed (mirrored, then rotated 90° clockwise)", 6: "rotated 90° clockwise to display", 7: "transversed (mirrored, then rotated 90° counterclockwise)", 8: "rotated 90° counterclockwise to display" };
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The structure of a TIFF block (the EXIF payload): its byte order and each IFD
|
|
328
|
+
* with its entries and where their values are. Reads only; every offset is
|
|
329
|
+
* checked against `t`. Pointers that loop, or reach an IFD already walked, are
|
|
330
|
+
* refused. A problem becomes an entry in `errors` and ends that IFD.
|
|
331
|
+
*/
|
|
332
|
+
function walkTiff(t, errors) {
|
|
333
|
+
const out = { le: true, ifds: [], end: 8, ok: false };
|
|
334
|
+
if (t.length < 8) return (errors.add("EXIF: too short to hold a TIFF header"), out);
|
|
335
|
+
if (t[0] === 0x49 && t[1] === 0x49) out.le = true;
|
|
336
|
+
else if (t[0] === 0x4d && t[1] === 0x4d) out.le = false;
|
|
337
|
+
else return (errors.add("EXIF: not a TIFF header (byte order mark missing)"), out);
|
|
338
|
+
const le = out.le;
|
|
339
|
+
const r16 = (at) => (le ? le16(t, at) : be16(t, at));
|
|
340
|
+
const r32 = (at) => (le ? le32(t, at) : be32(t, at));
|
|
341
|
+
if (r16(2) !== 42) return (errors.add("EXIF: bad TIFF magic number"), out);
|
|
342
|
+
const first = r32(4);
|
|
343
|
+
const queue = [{ name: "ifd0", at: first }];
|
|
344
|
+
const seen = new Set();
|
|
345
|
+
let tags = 0;
|
|
346
|
+
while (queue.length) {
|
|
347
|
+
const { name, at } = queue.shift();
|
|
348
|
+
if (out.ifds.length >= LIMITS.ifds) {
|
|
349
|
+
errors.add("EXIF: more IFDs than are read");
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
if (at < 8 || at + 2 > t.length) {
|
|
353
|
+
errors.add(`EXIF: ${name} offset ${at} is outside the ${t.length} bytes there are`);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (seen.has(at)) {
|
|
357
|
+
errors.add(`EXIF: ${name} points at an IFD already read (a loop)`);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
seen.add(at);
|
|
361
|
+
const count = r16(at);
|
|
362
|
+
const end = at + 2 + count * 12 + 4;
|
|
363
|
+
if (end > t.length) {
|
|
364
|
+
errors.add(`EXIF: ${name} lists ${count} entries but runs past the end`);
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
const ifd = { name, at, count, end, entries: [], next: r32(at + 2 + count * 12) };
|
|
368
|
+
out.end = Math.max(out.end, end);
|
|
369
|
+
for (let i = 0; i < count; i++) {
|
|
370
|
+
if (tags++ >= LIMITS.tags) {
|
|
371
|
+
errors.add(`EXIF: more than ${LIMITS.tags} tags; the rest are not read`);
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
const pos = at + 2 + i * 12;
|
|
375
|
+
const tag = r16(pos);
|
|
376
|
+
const type = r16(pos + 2);
|
|
377
|
+
const n = r32(pos + 4);
|
|
378
|
+
const size = TYPE_SIZE[type];
|
|
379
|
+
const entry = { ifd: name, tag, type, count: n, pos, valuePos: -1, size: 0 };
|
|
380
|
+
if (size === undefined) entry.problem = `unknown value type ${type}`;
|
|
381
|
+
else {
|
|
382
|
+
entry.size = size * n;
|
|
383
|
+
if (entry.size > LIMITS.tagBytes) entry.problem = `value of ${entry.size} bytes is larger than the ${LIMITS.tagBytes} read`;
|
|
384
|
+
else if (entry.size <= 4) entry.valuePos = pos + 8;
|
|
385
|
+
else {
|
|
386
|
+
const off = r32(pos + 8);
|
|
387
|
+
if (off < 8 || off + entry.size > t.length) entry.problem = `value at offset ${off} runs past the end`;
|
|
388
|
+
else (entry.valuePos = off, (out.end = Math.max(out.end, off + entry.size)));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
ifd.entries.push(entry);
|
|
392
|
+
}
|
|
393
|
+
out.ifds.push(ifd);
|
|
394
|
+
for (const e of ifd.entries) {
|
|
395
|
+
if (e.problem || e.type !== T_LONG || e.count !== 1) continue;
|
|
396
|
+
const target = r32(e.valuePos);
|
|
397
|
+
if (name === "ifd0" && e.tag === 0x8769) queue.push({ name: "exif", at: target });
|
|
398
|
+
else if (name === "ifd0" && e.tag === 0x8825) queue.push({ name: "gps", at: target });
|
|
399
|
+
else if (name === "exif" && e.tag === 0xa005) queue.push({ name: "interop", at: target });
|
|
400
|
+
}
|
|
401
|
+
if (name === "ifd0" && ifd.next) queue.push({ name: "ifd1", at: ifd.next });
|
|
402
|
+
}
|
|
403
|
+
out.ok = out.ifds.length > 0;
|
|
404
|
+
return out;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** One entry's value as JSON: a string, a number, an array of up to 16, or a short hex string. */
|
|
408
|
+
function valueOf(t, e, le) {
|
|
409
|
+
const r16 = (at) => (le ? le16(t, at) : be16(t, at));
|
|
410
|
+
const r32 = (at) => (le ? le32(t, at) : be32(t, at));
|
|
411
|
+
const s32 = (at) => r32(at) | 0;
|
|
412
|
+
const p = e.valuePos;
|
|
413
|
+
const n = Math.min(e.count, 16);
|
|
414
|
+
switch (e.type) {
|
|
415
|
+
case T_ASCII: {
|
|
416
|
+
let s = latin1(t.subarray(p, p + Math.min(e.size, LIMITS.textChars * 2)));
|
|
417
|
+
const nul = s.indexOf("\0");
|
|
418
|
+
if (nul >= 0) s = s.slice(0, nul);
|
|
419
|
+
return clip(printable(s));
|
|
420
|
+
}
|
|
421
|
+
case 1:
|
|
422
|
+
case 7: {
|
|
423
|
+
if (e.count > 16) return `${e.count} bytes`;
|
|
424
|
+
let hex = "";
|
|
425
|
+
for (let i = 0; i < e.count; i++) hex += t[p + i].toString(16).padStart(2, "0");
|
|
426
|
+
return hex;
|
|
427
|
+
}
|
|
428
|
+
case 6: {
|
|
429
|
+
const v = [...Array(n).keys()].map((i) => (t[p + i] << 24) >> 24);
|
|
430
|
+
return v.length === 1 ? v[0] : v;
|
|
431
|
+
}
|
|
432
|
+
case T_SHORT:
|
|
433
|
+
case 8: {
|
|
434
|
+
const v = [...Array(n).keys()].map((i) => (e.type === 8 ? (r16(p + i * 2) << 16) >> 16 : r16(p + i * 2)));
|
|
435
|
+
return v.length === 1 ? v[0] : v;
|
|
436
|
+
}
|
|
437
|
+
case T_LONG:
|
|
438
|
+
case 9:
|
|
439
|
+
case 13: {
|
|
440
|
+
const v = [...Array(n).keys()].map((i) => (e.type === 9 ? s32(p + i * 4) : r32(p + i * 4)));
|
|
441
|
+
return v.length === 1 ? v[0] : v;
|
|
442
|
+
}
|
|
443
|
+
case T_RATIONAL:
|
|
444
|
+
case 10: {
|
|
445
|
+
const v = [...Array(n).keys()].map((i) => {
|
|
446
|
+
const num = e.type === 10 ? s32(p + i * 8) : r32(p + i * 8);
|
|
447
|
+
const den = e.type === 10 ? s32(p + i * 8 + 4) : r32(p + i * 8 + 4);
|
|
448
|
+
return den === 0 ? null : Math.round((num / den) * 1e6) / 1e6;
|
|
449
|
+
});
|
|
450
|
+
return v.length === 1 ? v[0] : v;
|
|
451
|
+
}
|
|
452
|
+
case 11:
|
|
453
|
+
case 12: {
|
|
454
|
+
const v = [...Array(n).keys()].map((i) => {
|
|
455
|
+
const dv = new DataView(t.buffer, t.byteOffset + p + i * (e.type === 11 ? 4 : 8), e.type === 11 ? 4 : 8);
|
|
456
|
+
return e.type === 11 ? dv.getFloat32(0, le) : dv.getFloat64(0, le);
|
|
457
|
+
});
|
|
458
|
+
return v.length === 1 ? v[0] : v;
|
|
459
|
+
}
|
|
460
|
+
default:
|
|
461
|
+
return undefined;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const tagName = (ifd, tag) => {
|
|
466
|
+
if (ifd === "gps") return [GPS_TAGS[tag] ?? `GPS_0x${tag.toString(16)}`, false];
|
|
467
|
+
const table = ifd === "exif" ? EXIF_TAGS : IFD0_TAGS;
|
|
468
|
+
const found = table[tag] ?? (ifd === "ifd1" ? IFD0_TAGS[tag] : undefined);
|
|
469
|
+
return found ? [found[0], found[1]] : [`Tag_0x${tag.toString(16).padStart(4, "0")}`, false];
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
/** Decimal degrees from `[d, m, s]` and "N"/"S"/"E"/"W". */
|
|
473
|
+
function degrees(dms, ref) {
|
|
474
|
+
if (!Array.isArray(dms) || dms.length < 3 || dms.some((x) => typeof x !== "number" || !Number.isFinite(x))) return undefined;
|
|
475
|
+
const v = dms[0] + dms[1] / 60 + dms[2] / 3600;
|
|
476
|
+
const sign = ref === "S" || ref === "W" ? -1 : 1;
|
|
477
|
+
return Math.round(v * sign * 1e6) / 1e6;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// ── MakerNote ────────────────────────────────────────────────────────────────
|
|
481
|
+
// A camera's own block of settings, serial numbers and identifiers (EXIF tag 0x927c). Most makers write it as a small
|
|
482
|
+
// TIFF-style directory (a count, then 12-byte entries of tag, type, count and a value or an offset) after a short
|
|
483
|
+
// header that says whose it is and where its offsets start from. This reads that directory and nothing else: it lists
|
|
484
|
+
// the fields (the text ones, the short numeric ones), names the few it is sure of, and finds the text values that spell
|
|
485
|
+
// a place so removing the location can blank them. A vendor's binary fields are not interpreted, and a note that does
|
|
486
|
+
// not read as a directory stays "present and not decoded".
|
|
487
|
+
|
|
488
|
+
const MAKERNOTE_LIMITS = {
|
|
489
|
+
entries: 200, // fields listed from one note
|
|
490
|
+
textBytes: 1024, // one text field read
|
|
491
|
+
valueBytes: 65536, // a field larger than this is not read
|
|
492
|
+
fields: 64, // fields in the report
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
// The few fields whose meaning is certain, by maker: name and whether it identifies a device or a shot.
|
|
496
|
+
const MAKERNOTE_KNOWN = {
|
|
497
|
+
Apple: { 0x0001: ["MakerNoteVersion"], 0x000b: ["BurstUUID", true], 0x0011: ["ContentIdentifier", true], 0x0015: ["ImageUniqueID", true] },
|
|
498
|
+
Canon: { 0x0006: ["CanonImageType"], 0x0007: ["CanonFirmwareVersion"], 0x0009: ["OwnerName", true], 0x000c: ["SerialNumber", true], 0x0095: ["LensModel"], 0x0096: ["InternalSerialNumber", true] },
|
|
499
|
+
Nikon: { 0x0001: ["MakerNoteVersion"], 0x0002: ["ISO"], 0x001d: ["SerialNumber", true], 0x00a0: ["SerialNumber", true] },
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
const tiffReader = (t, le) => ({
|
|
503
|
+
r16: (at) => (le ? t[at] | (t[at + 1] << 8) : (t[at] << 8) | t[at + 1]),
|
|
504
|
+
r32: (at) => (le ? (t[at] | (t[at + 1] << 8) | (t[at + 2] << 16) | (t[at + 3] << 24)) >>> 0 : ((t[at] << 24) | (t[at + 1] << 16) | (t[at + 2] << 8) | t[at + 3]) >>> 0),
|
|
505
|
+
});
|
|
506
|
+
const makerOrder = (t, at) => (t[at] === 0x49 && t[at + 1] === 0x49 ? true : t[at] === 0x4d && t[at + 1] === 0x4d ? false : undefined);
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Where a note's directory is: `{ maker, ifd, base, le }` (`ifd`: the directory's byte in `t`; `base`: the byte its
|
|
510
|
+
* offsets count from; `le`: its byte order), or `undefined` when no known header matches. `headerless` notes (Canon and
|
|
511
|
+
* others, a directory straight away with offsets from the start of the TIFF block) are tried last by the caller.
|
|
512
|
+
*/
|
|
513
|
+
function makerLayout(t, at, size, tiffLe) {
|
|
514
|
+
const end = at + size;
|
|
515
|
+
const has = (text) => at + text.length <= end && ascii(t, at, text.length) === text;
|
|
516
|
+
if (has("Apple iOS\0") && size >= 16) {
|
|
517
|
+
const le = makerOrder(t, at + 12);
|
|
518
|
+
if (le !== undefined) return { maker: "Apple", ifd: at + 14, base: at, le };
|
|
519
|
+
}
|
|
520
|
+
if (has("Nikon\0") && size >= 18) {
|
|
521
|
+
const le = makerOrder(t, at + 10);
|
|
522
|
+
if (le !== undefined && tiffReader(t, le).r16(at + 12) === 42) return { maker: "Nikon", ifd: at + 10 + tiffReader(t, le).r32(at + 14), base: at + 10, le };
|
|
523
|
+
}
|
|
524
|
+
if (has("OLYMPUS\0") && size >= 16) {
|
|
525
|
+
const le = makerOrder(t, at + 8);
|
|
526
|
+
if (le !== undefined) return { maker: "Olympus", ifd: at + 12, base: at, le };
|
|
527
|
+
}
|
|
528
|
+
if (has("FUJIFILM") && size >= 12) return { maker: "Fujifilm", ifd: at + tiffReader(t, true).r32(at + 8), base: at, le: true };
|
|
529
|
+
if (has("SONY DSC \0\0\0") && size >= 14) return { maker: "Sony", ifd: at + 12, base: 0, le: tiffLe };
|
|
530
|
+
if (has("Panasonic\0\0\0") && size >= 14) return { maker: "Panasonic", ifd: at + 12, base: 0, le: tiffLe };
|
|
531
|
+
return undefined;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Read the MakerNote of `note` (`{ valuePos, size }` in `t`, the TIFF block; `le`: the block's byte order).
|
|
536
|
+
* `make` is IFD0's Make, which names a headerless note's maker. `isPlace(text)` says whether a text value spells a location.
|
|
537
|
+
* @returns {{ ok: false, why: string } | { ok: true, maker: string, layout: string, count: number, fields: object[], places: number[][], truncated?: boolean }}
|
|
538
|
+
* `fields`: `{ tag, type, count, name?, identifier?, value? }` (the report); `places`: the `[from, to)` byte ranges of
|
|
539
|
+
* text values that name a place (the editor blanks them).
|
|
540
|
+
*/
|
|
541
|
+
function readMakerNote(t, note, le, { make = "", isPlace = () => false } = {}) {
|
|
542
|
+
const at = note.valuePos;
|
|
543
|
+
const end = at + note.size;
|
|
544
|
+
if (!(at >= 0) || end > t.length || note.size < 14) return { ok: false, why: "too short to hold a field list" };
|
|
545
|
+
let lay = makerLayout(t, at, note.size, le);
|
|
546
|
+
let layout = lay ? "header" : "no header";
|
|
547
|
+
if (!lay) {
|
|
548
|
+
const maker = /canon/i.test(make) ? "Canon" : /nikon/i.test(make) ? "Nikon" : /sony/i.test(make) ? "Sony" : /pentax|ricoh/i.test(make) ? "Pentax" : /panasonic|leica/i.test(make) ? "Panasonic" : /olympus|om digital/i.test(make) ? "Olympus" : /fuji/i.test(make) ? "Fujifilm" : /samsung/i.test(make) ? "Samsung" : "unknown";
|
|
549
|
+
lay = { maker, ifd: at, base: 0, le };
|
|
550
|
+
}
|
|
551
|
+
const { r16, r32 } = tiffReader(t, lay.le);
|
|
552
|
+
if (lay.ifd < at || lay.ifd + 2 > end) return { ok: false, why: "its field list starts outside the note" };
|
|
553
|
+
const count = r16(lay.ifd);
|
|
554
|
+
if (count < 1 || count > 4000) return { ok: false, why: `its field list claims ${count} fields` };
|
|
555
|
+
if (lay.ifd + 2 + count * 12 > end) return { ok: false, why: "its field list runs past the end of the note" };
|
|
556
|
+
const known = MAKERNOTE_KNOWN[lay.maker] ?? {};
|
|
557
|
+
const fields = [];
|
|
558
|
+
const places = [];
|
|
559
|
+
let prev = -1;
|
|
560
|
+
let ordered = true;
|
|
561
|
+
let valid = 0;
|
|
562
|
+
const limit = Math.min(count, MAKERNOTE_LIMITS.entries);
|
|
563
|
+
for (let i = 0; i < limit; i++) {
|
|
564
|
+
const pos = lay.ifd + 2 + i * 12;
|
|
565
|
+
const tag = r16(pos);
|
|
566
|
+
const type = r16(pos + 2);
|
|
567
|
+
const n = r32(pos + 4);
|
|
568
|
+
if (tag <= prev) ordered = false;
|
|
569
|
+
prev = tag;
|
|
570
|
+
const unit = TYPE_SIZE[type];
|
|
571
|
+
if (unit === undefined) continue;
|
|
572
|
+
const size = unit * n;
|
|
573
|
+
let valuePos = -1;
|
|
574
|
+
if (size <= 4) valuePos = pos + 8;
|
|
575
|
+
else {
|
|
576
|
+
const off = lay.base + r32(pos + 8);
|
|
577
|
+
if (off >= at && off + size <= end) valuePos = off;
|
|
578
|
+
else if (lay.base === 0 && off >= 8 && off + size <= t.length) valuePos = off; // a value the note keeps outside itself: read, never blanked
|
|
579
|
+
}
|
|
580
|
+
if (valuePos < 0) continue;
|
|
581
|
+
valid++;
|
|
582
|
+
const field = { tag: `0x${tag.toString(16).padStart(4, "0")}`, type, count: n };
|
|
583
|
+
const name = known[tag];
|
|
584
|
+
if (name) {
|
|
585
|
+
field.name = name[0];
|
|
586
|
+
if (name[1]) field.identifier = true;
|
|
587
|
+
}
|
|
588
|
+
if (size <= MAKERNOTE_LIMITS.valueBytes) {
|
|
589
|
+
if (type === 2) {
|
|
590
|
+
let s = ascii(t, valuePos, Math.min(size, MAKERNOTE_LIMITS.textBytes));
|
|
591
|
+
const nul = s.indexOf("\0");
|
|
592
|
+
if (nul >= 0) s = s.slice(0, nul);
|
|
593
|
+
s = s.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").trim();
|
|
594
|
+
if (s) {
|
|
595
|
+
field.value = s.length > 120 ? `${s.slice(0, 120)}…` : s;
|
|
596
|
+
if (isPlace(s) && valuePos >= at && valuePos + size <= end) places.push([valuePos, valuePos + (nul >= 0 ? Math.min(nul, size) : size)]);
|
|
597
|
+
else if (isPlace(s)) field.place = true;
|
|
598
|
+
}
|
|
599
|
+
} else if ((type === 3 || type === 4 || type === 1 || type === 6 || type === 8 || type === 9) && n >= 1 && n <= 4) {
|
|
600
|
+
const v = [];
|
|
601
|
+
for (let k = 0; k < n; k++) {
|
|
602
|
+
if (type === 3 || type === 8) v.push(type === 8 ? (r16(valuePos + k * 2) << 16) >> 16 : r16(valuePos + k * 2));
|
|
603
|
+
else if (type === 4 || type === 9) v.push(type === 9 ? r32(valuePos + k * 4) | 0 : r32(valuePos + k * 4));
|
|
604
|
+
else v.push(type === 6 ? (t[valuePos + k] << 24) >> 24 : t[valuePos + k]);
|
|
605
|
+
}
|
|
606
|
+
field.value = v.length === 1 ? v[0] : v;
|
|
607
|
+
} else field.value = `${size} bytes`;
|
|
608
|
+
}
|
|
609
|
+
if (fields.length < MAKERNOTE_LIMITS.fields) fields.push(field);
|
|
610
|
+
}
|
|
611
|
+
// A note with no header has to look like a field list: ascending tags and most fields inside the bytes.
|
|
612
|
+
if (layout === "no header" && (!ordered || valid < Math.ceil(limit * 0.8))) return { ok: false, why: "it has no header and does not read as a field list" };
|
|
613
|
+
if (valid === 0) return { ok: false, why: "none of its fields could be read" };
|
|
614
|
+
return { ok: true, maker: lay.maker, layout, count, fields, places, ...(count > limit || valid > fields.length ? { truncated: true } : {}) };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** The EXIF block's report: `{ technical, personal, orientation, location, hasMakerNote, problems }`. */
|
|
618
|
+
function readExif(tiff, errors) {
|
|
619
|
+
const walk = walkTiff(tiff, errors);
|
|
620
|
+
const out = { technical: [], personal: [], hasMakerNote: false, hasGps: false, thumbnail: false };
|
|
621
|
+
if (!walk.ok) return out;
|
|
622
|
+
const gps = {};
|
|
623
|
+
let make = "";
|
|
624
|
+
for (const ifd of walk.ifds) {
|
|
625
|
+
if (ifd.name === "ifd1") out.thumbnail = true;
|
|
626
|
+
for (const e of ifd.entries) {
|
|
627
|
+
const [name, technical] = tagName(ifd.name, e.tag);
|
|
628
|
+
if (/Pointer$/.test(name)) continue;
|
|
629
|
+
if (e.problem) {
|
|
630
|
+
errors.add(`EXIF ${ifd.name} ${name}: ${e.problem}`);
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
if (e.tag === 0x927c && ifd.name === "exif") {
|
|
634
|
+
out.hasMakerNote = true;
|
|
635
|
+
const note = readMakerNote(tiff, e, walk.le, { make, isPlace: namesLocationText });
|
|
636
|
+
if (note.ok) {
|
|
637
|
+
out.makerNote = note;
|
|
638
|
+
out.personal.push({ ifd: ifd.name, tag: name, value: `${e.size} bytes of vendor data (${note.fields.length} fields listed under makerNote)` });
|
|
639
|
+
} else out.personal.push({ ifd: ifd.name, tag: name, value: `${e.size} bytes of vendor data (not decoded: ${note.why})` });
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
const value = valueOf(tiff, e, walk.le);
|
|
643
|
+
if (value === undefined) continue;
|
|
644
|
+
if (ifd.name === "ifd0" && e.tag === 0x010f && typeof value === "string") make = value;
|
|
645
|
+
if (ifd.name === "gps") (out.hasGps = true), (gps[name] = value);
|
|
646
|
+
if (ifd.name === "ifd0" && e.tag === 0x0112 && typeof value === "number") out.orientation = value;
|
|
647
|
+
(technical && ifd.name !== "gps" ? out.technical : out.personal).push({ ifd: ifd.name, tag: name, value });
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
if (out.hasGps) {
|
|
651
|
+
const lat = degrees(gps.GPSLatitude, gps.GPSLatitudeRef);
|
|
652
|
+
const lon = degrees(gps.GPSLongitude, gps.GPSLongitudeRef);
|
|
653
|
+
if (lat !== undefined && lon !== undefined && Math.abs(lat) <= 90 && Math.abs(lon) <= 180) {
|
|
654
|
+
out.location = { latitude: lat, longitude: lon };
|
|
655
|
+
if (typeof gps.GPSAltitude === "number") out.location.altitude = gps.GPSAltitude * (gps.GPSAltitudeRef === 1 || gps.GPSAltitudeRef === "01" ? -1 : 1);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return out;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** The first IFD0 entry with this tag, with the walk. */
|
|
662
|
+
function findEntry(walk, ifdName, tag) {
|
|
663
|
+
return walk.ifds.find((i) => i.name === ifdName)?.entries.find((e) => e.tag === tag && !e.problem);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Remove the GPS IFD from a TIFF block, in place: its entries and out-of-line
|
|
668
|
+
* values are zeroed, and the pointer to it leaves IFD0 (the entries after it
|
|
669
|
+
* move up, the block keeps its length). Refuses, and changes nothing, when the
|
|
670
|
+
* GPS IFD overlaps another structure.
|
|
671
|
+
* @returns {{ removed: boolean, why?: string }}
|
|
672
|
+
*/
|
|
673
|
+
function removeGpsIfd(t, errors) {
|
|
674
|
+
const walk = walkTiff(t, errors);
|
|
675
|
+
if (!walk.ok) return { removed: false, why: "the EXIF block can't be read" };
|
|
676
|
+
const ptr = findEntry(walk, "ifd0", 0x8825);
|
|
677
|
+
const gps = walk.ifds.find((i) => i.name === "gps");
|
|
678
|
+
if (!ptr) return { removed: false, why: undefined };
|
|
679
|
+
if (!gps) return { removed: false, why: "the GPS pointer is invalid" };
|
|
680
|
+
const regions = [[gps.at, gps.end]];
|
|
681
|
+
for (const e of gps.entries) if (!e.problem && e.size > 4) regions.push([e.valuePos, e.valuePos + e.size]);
|
|
682
|
+
for (const other of walk.ifds) {
|
|
683
|
+
if (other === gps) continue;
|
|
684
|
+
const spans = [[other.at, other.end], ...other.entries.filter((e) => !e.problem && e.size > 4).map((e) => [e.valuePos, e.valuePos + e.size])];
|
|
685
|
+
for (const [a, b] of spans) for (const [c, d] of regions) if (a < d && c < b) return { removed: false, why: "the GPS data overlaps other EXIF data, so it was left unchanged" };
|
|
686
|
+
}
|
|
687
|
+
for (const [a, b] of regions) t.fill(0, a, b);
|
|
688
|
+
const ifd0 = walk.ifds.find((i) => i.name === "ifd0");
|
|
689
|
+
const le = walk.le;
|
|
690
|
+
const index = ifd0.entries.indexOf(ptr);
|
|
691
|
+
const tail = ifd0.at + 2 + (index + 1) * 12;
|
|
692
|
+
t.copyWithin(ptr.pos, tail, ifd0.end); // later entries, then the next-IFD pointer, move up one entry
|
|
693
|
+
t.fill(0, ifd0.end - 12, ifd0.end);
|
|
694
|
+
const count = ifd0.count - 1;
|
|
695
|
+
if (le) (t[ifd0.at] = count & 255), (t[ifd0.at + 1] = count >> 8);
|
|
696
|
+
else (t[ifd0.at] = count >> 8), (t[ifd0.at + 1] = count & 255);
|
|
697
|
+
return { removed: true };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Blank the text values of a decoded MakerNote that spell a place (a coordinate pair, a geo: URI, degrees-minutes-seconds),
|
|
702
|
+
* in place, to spaces: same length, every other field untouched. Returns how many values it blanked.
|
|
703
|
+
*/
|
|
704
|
+
function blankMakerNotePlaces(t) {
|
|
705
|
+
const walk = walkTiff(t, new Errors());
|
|
706
|
+
if (!walk.ok) return 0;
|
|
707
|
+
const note = findEntry(walk, "exif", 0x927c);
|
|
708
|
+
if (!note) return 0;
|
|
709
|
+
const make = findEntry(walk, "ifd0", 0x010f);
|
|
710
|
+
const r = readMakerNote(t, note, walk.le, { make: make && make.type === T_ASCII ? valueOf(t, make, walk.le) : "", isPlace: namesLocationText });
|
|
711
|
+
if (!r.ok) return 0;
|
|
712
|
+
for (const [from, to] of r.places) t.fill(0x20, from, to);
|
|
713
|
+
return r.places.length;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** Remove the GPS IFD and the places a MakerNote spells, in place (see removeGpsIfd and blankMakerNotePlaces). */
|
|
717
|
+
function removeGpsFromTiff(t, errors) {
|
|
718
|
+
const r = removeGpsIfd(t, errors);
|
|
719
|
+
const makerNote = blankMakerNotePlaces(t);
|
|
720
|
+
return makerNote ? { ...r, makerNote } : r;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** Set IFD0's Orientation to `value` in place, when it has one (a SHORT, count 1). */
|
|
724
|
+
function setOrientationInTiff(t, value, errors) {
|
|
725
|
+
const walk = walkTiff(t, errors);
|
|
726
|
+
if (!walk.ok) return false;
|
|
727
|
+
const e = findEntry(walk, "ifd0", 0x0112);
|
|
728
|
+
if (!e || e.type !== T_SHORT || e.count !== 1) return false;
|
|
729
|
+
if (walk.le) (t[e.valuePos] = value & 255), (t[e.valuePos + 1] = 0);
|
|
730
|
+
else (t[e.valuePos] = 0), (t[e.valuePos + 1] = value & 255);
|
|
731
|
+
return true;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** Set the Exif pixel dimensions (when the block has them as a single SHORT or LONG), in place. */
|
|
735
|
+
function setDimensionsInTiff(t, w, h, errors) {
|
|
736
|
+
const walk = walkTiff(t, errors);
|
|
737
|
+
if (!walk.ok) return;
|
|
738
|
+
for (const [tag, v] of [[0xa002, w], [0xa003, h]]) {
|
|
739
|
+
const e = findEntry(walk, "exif", tag);
|
|
740
|
+
if (!e || e.count !== 1) continue;
|
|
741
|
+
if (e.type === T_SHORT && v <= 0xffff) walk.le ? ((t[e.valuePos] = v & 255), (t[e.valuePos + 1] = v >> 8)) : ((t[e.valuePos] = v >> 8), (t[e.valuePos + 1] = v & 255));
|
|
742
|
+
else if (e.type === T_LONG) walk.le ? put32le(t, e.valuePos, v) : put32be(t, e.valuePos, v);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Drop the embedded thumbnail (IFD1 and its picture) and trim the block to what
|
|
748
|
+
* is still referenced. A thumbnail is a second, smaller copy of the picture,
|
|
749
|
+
* stale once the pixels change.
|
|
750
|
+
*/
|
|
751
|
+
function compactTiff(t, { dropThumbnail }, errors) {
|
|
752
|
+
const walk = walkTiff(t, errors);
|
|
753
|
+
if (!walk.ok) return t;
|
|
754
|
+
if (dropThumbnail) {
|
|
755
|
+
const ifd0 = walk.ifds.find((i) => i.name === "ifd0");
|
|
756
|
+
const ifd1 = walk.ifds.find((i) => i.name === "ifd1");
|
|
757
|
+
if (ifd0 && ifd1) {
|
|
758
|
+
const off = findEntry(walk, "ifd1", 0x0201);
|
|
759
|
+
const len = findEntry(walk, "ifd1", 0x0202);
|
|
760
|
+
const r32 = (at) => (walk.le ? le32(t, at) : be32(t, at));
|
|
761
|
+
if (off && len && off.count === 1 && len.count === 1) {
|
|
762
|
+
const a = r32(off.valuePos);
|
|
763
|
+
const n = r32(len.valuePos);
|
|
764
|
+
if (a >= 8 && a + n <= t.length) t.fill(0, a, a + n);
|
|
765
|
+
}
|
|
766
|
+
for (const e of ifd1.entries) if (!e.problem && e.size > 4) t.fill(0, e.valuePos, e.valuePos + e.size);
|
|
767
|
+
t.fill(0, ifd1.at, ifd1.end);
|
|
768
|
+
t.fill(0, ifd0.end - 4, ifd0.end); // IFD0's next-IFD pointer
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
// Trim: the furthest byte anything still alive uses.
|
|
772
|
+
const again = walkTiff(t, new Errors());
|
|
773
|
+
let end = again.end;
|
|
774
|
+
const keepThumb = !dropThumbnail && again.ifds.some((i) => i.name === "ifd1");
|
|
775
|
+
if (keepThumb) {
|
|
776
|
+
const off = findEntry(again, "ifd1", 0x0201);
|
|
777
|
+
const len = findEntry(again, "ifd1", 0x0202);
|
|
778
|
+
const r32 = (at) => (again.le ? le32(t, at) : be32(t, at));
|
|
779
|
+
if (off && len) end = Math.max(end, Math.min(t.length, r32(off.valuePos) + r32(len.valuePos)));
|
|
780
|
+
else end = t.length;
|
|
781
|
+
}
|
|
782
|
+
return t.slice(0, Math.max(8, Math.min(t.length, end)));
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// ── XMP ──────────────────────────────────────────────────────────────────────
|
|
786
|
+
|
|
787
|
+
const XMP_NS = "exif|tiff|dc|xmp|photoshop|xmpRights|aux|Iptc4xmpCore|Iptc4xmpExt|xmpMM|MicrosoftPhoto|mwg-rs|crs|lr|plus";
|
|
788
|
+
|
|
789
|
+
function readXmp(bytes, errors) {
|
|
790
|
+
const clipped = bytes.length > LIMITS.xmpBytes ? bytes.subarray(0, LIMITS.xmpBytes) : bytes;
|
|
791
|
+
const text = utf8(clipped);
|
|
792
|
+
const props = [];
|
|
793
|
+
const seen = new Set();
|
|
794
|
+
const add = (name, value) => {
|
|
795
|
+
const v = clip(printable(value.replace(/"/g, '"').replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/'/g, "'")), 200);
|
|
796
|
+
const key = `${name}=${v}`;
|
|
797
|
+
if (!seen.has(key) && props.length < LIMITS.xmpProps) (seen.add(key), props.push({ name, value: v }));
|
|
798
|
+
};
|
|
799
|
+
for (const m of text.matchAll(new RegExp(`\\b((?:${XMP_NS}):[A-Za-z0-9]+)\\s*=\\s*"([^"]{0,300})"`, "g"))) add(m[1], m[2]);
|
|
800
|
+
for (const m of text.matchAll(new RegExp(`<((?:${XMP_NS}):[A-Za-z0-9]+)>([^<]{1,300})</\\1>`, "g"))) add(m[1], m[2]);
|
|
801
|
+
const gps = /\bexif:GPS[A-Za-z]+/.test(text);
|
|
802
|
+
const orient = /\btiff:Orientation\s*(?:=\s*"(\d)"|>\s*(\d)\s*<)/.exec(text);
|
|
803
|
+
if (bytes.length > LIMITS.xmpBytes) errors.add(`XMP: ${bytes.length} bytes; only the first ${LIMITS.xmpBytes} are read`);
|
|
804
|
+
return { props, gps, orientation: orient ? Number(orient[1] ?? orient[2]) : undefined, truncated: bytes.length > LIMITS.xmpBytes };
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Blank GPS properties out of XMP text (as bytes), same length: each attribute
|
|
809
|
+
* or element becomes spaces, so offsets and the packet's padding stay valid.
|
|
810
|
+
* @returns {{ bytes: Uint8Array, count: number }}
|
|
811
|
+
*/
|
|
812
|
+
function blankXmpGps(bytes) {
|
|
813
|
+
let count = 0;
|
|
814
|
+
let s = latin1(bytes);
|
|
815
|
+
const blank = (m) => (count++, " ".repeat(m.length));
|
|
816
|
+
s = s.replace(/\s?exif:GPS[A-Za-z]+\s*=\s*"[^"]*"/g, blank);
|
|
817
|
+
s = s.replace(/\s?exif:GPS[A-Za-z]+\s*=\s*'[^']*'/g, blank);
|
|
818
|
+
s = s.replace(/<exif:(GPS[A-Za-z]+)(?:\s[^>]*)?>[\s\S]*?<\/exif:\1>/g, blank);
|
|
819
|
+
// Named places say where a picture was taken as plainly as coordinates do.
|
|
820
|
+
s = s.replace(new RegExp(`\\s?(?:${XMP_PLACES})\\s*=\\s*"[^"]*"`, "g"), blank);
|
|
821
|
+
s = s.replace(new RegExp(`\\s?(?:${XMP_PLACES})\\s*=\\s*'[^']*'`, "g"), blank);
|
|
822
|
+
s = s.replace(new RegExp(`<(${XMP_PLACE_STRUCTS}|${XMP_PLACES})(?:\\s[^>]*)?>[\\s\\S]*?<\\/\\1>`, "g"), blank);
|
|
823
|
+
return { bytes: fromLatin1(s), count };
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// The XMP properties that name a place (IPTC Core and Extension, Photoshop), as alternation text for a RegExp.
|
|
827
|
+
const XMP_PLACES = "photoshop:(?:City|State|Country)|Iptc4xmpCore:(?:Location|CountryCode)|Iptc4xmpExt:(?:City|ProvinceState|CountryName|CountryCode|Sublocation|WorldRegion|LocationName)";
|
|
828
|
+
const XMP_PLACE_STRUCTS = "Iptc4xmpExt:(?:LocationShown|LocationCreated)";
|
|
829
|
+
|
|
830
|
+
/** Set tiff:Orientation to 1 in XMP text, same length, when the existing value is one digit. */
|
|
831
|
+
function setXmpOrientation(bytes, value) {
|
|
832
|
+
const s = latin1(bytes);
|
|
833
|
+
let done = false;
|
|
834
|
+
const r = s.replace(/(\btiff:Orientation\s*=\s*")(\d)(")/, (m, a, d, c) => ((done = true), `${a}${value}${c}`)).replace(/(<tiff:Orientation>\s*)(\d)(\s*<)/, (m, a, d, c) => ((done = true), `${a}${value}${c}`));
|
|
835
|
+
return done ? fromLatin1(r) : bytes;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// ── JPEG ─────────────────────────────────────────────────────────────────────
|
|
839
|
+
|
|
840
|
+
const EXIF_HEAD = "Exif\0\0";
|
|
841
|
+
const XMP_HEAD = "http://ns.adobe.com/xap/1.0/\0";
|
|
842
|
+
const XMP_EXT_HEAD = "http://ns.adobe.com/xmp/extension/\0";
|
|
843
|
+
const ICC_HEAD = "ICC_PROFILE\0";
|
|
844
|
+
const PS_HEAD = "Photoshop 3.0\0";
|
|
845
|
+
|
|
846
|
+
/** JPEG segments before the image data: `{ marker, start, end, data (offset of the payload), size }`. */
|
|
847
|
+
function parseJpeg(b, errors) {
|
|
848
|
+
const out = { segments: [], sos: -1, eoi: -1, width: undefined, height: undefined };
|
|
849
|
+
let at = 2;
|
|
850
|
+
while (at < b.length) {
|
|
851
|
+
if (b[at] !== 0xff) {
|
|
852
|
+
errors.add(`JPEG: expected a marker at byte ${at}`);
|
|
853
|
+
return out;
|
|
854
|
+
}
|
|
855
|
+
while (at < b.length && b[at] === 0xff) at++; // fill bytes
|
|
856
|
+
const marker = b[at++];
|
|
857
|
+
if (marker === undefined) break;
|
|
858
|
+
if (marker === 0xd9) {
|
|
859
|
+
out.eoi = at;
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue; // no length
|
|
863
|
+
if (at + 2 > b.length) {
|
|
864
|
+
errors.add("JPEG: ends inside a segment header");
|
|
865
|
+
return out;
|
|
866
|
+
}
|
|
867
|
+
const size = be16(b, at);
|
|
868
|
+
if (size < 2 || at + size > b.length) {
|
|
869
|
+
errors.add(`JPEG: segment 0x${marker.toString(16)} claims ${size} bytes but ${Math.max(0, b.length - at)} remain`);
|
|
870
|
+
return out;
|
|
871
|
+
}
|
|
872
|
+
const seg = { marker, start: at - 2, end: at + size, data: at + 2, size: size - 2 };
|
|
873
|
+
if (out.segments.length >= LIMITS.segments) {
|
|
874
|
+
errors.add(`JPEG: more than ${LIMITS.segments} segments; the rest are not read`);
|
|
875
|
+
return out;
|
|
876
|
+
}
|
|
877
|
+
out.segments.push(seg);
|
|
878
|
+
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc && size >= 8 && out.height === undefined) {
|
|
879
|
+
out.height = be16(b, at + 3);
|
|
880
|
+
out.width = be16(b, at + 5);
|
|
881
|
+
}
|
|
882
|
+
at += size;
|
|
883
|
+
if (marker === 0xda) {
|
|
884
|
+
out.sos = seg.start;
|
|
885
|
+
// the entropy-coded data runs to the next marker that isn't a restart or a stuffed 0xFF
|
|
886
|
+
while (at < b.length - 1) {
|
|
887
|
+
if (b[at] === 0xff && b[at + 1] !== 0 && !(b[at + 1] >= 0xd0 && b[at + 1] <= 0xd7) && b[at + 1] !== 0xff) break;
|
|
888
|
+
at++;
|
|
889
|
+
}
|
|
890
|
+
if (b[at] === 0xff && b[at + 1] === 0xd9) out.eoi = at + 2;
|
|
891
|
+
else if (at >= b.length - 1) errors.add("JPEG: no end-of-image marker (truncated)");
|
|
892
|
+
else out.afterScan = at; // another scan (progressive): the rest is image data we don't walk
|
|
893
|
+
return out;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
return out;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// ── IPTC (a JPEG's APP13 Photoshop block) ────────────────────────────────────
|
|
900
|
+
|
|
901
|
+
const IPTC_FIELDS = { 5: "Object name", 25: "Keywords", 26: "Content location code", 27: "Content location name", 55: "Date created", 80: "Byline", 90: "City", 92: "Sub-location", 95: "Province/State", 100: "Country code", 101: "Country", 105: "Headline", 110: "Credit", 115: "Source", 116: "Copyright", 120: "Caption" };
|
|
902
|
+
const IPTC_PLACES = new Set([26, 27, 90, 92, 95, 100, 101]); // the datasets that say where
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* The datasets of an IPTC-IIM stream `b[from, stop)`: the record-2 ones as `[{ dataset, at, size }]`, `at` being the
|
|
906
|
+
* value's offset in `b`, plus `charset` (the bytes of 1:90, if there is one) and `stopped` (why the walk ended before the
|
|
907
|
+
* end of the stream, when it did: what follows is not read). Standard and extended-length datasets (the size field's
|
|
908
|
+
* high bit set: its low bits say how many bytes of length follow, 1 to 4) are both followed; every length is checked
|
|
909
|
+
* against the stream, and one that claims more than is there ends the walk with a problem noted.
|
|
910
|
+
*/
|
|
911
|
+
function walkIim(b, from, stop, errors) {
|
|
912
|
+
const out = [];
|
|
913
|
+
let q = from;
|
|
914
|
+
let count = 0;
|
|
915
|
+
const end = (why, problem) => {
|
|
916
|
+
out.stopped = why;
|
|
917
|
+
if (problem) errors.add(problem);
|
|
918
|
+
return out;
|
|
919
|
+
};
|
|
920
|
+
while (q + 5 <= stop && b[q] === 0x1c) {
|
|
921
|
+
if (++count > LIMITS.iptcDatasets) return end(`more than ${LIMITS.iptcDatasets} datasets`);
|
|
922
|
+
const rec = b[q + 1];
|
|
923
|
+
const ds = b[q + 2];
|
|
924
|
+
let sz = be16(b, q + 3);
|
|
925
|
+
let head = 5;
|
|
926
|
+
if (sz & 0x8000) {
|
|
927
|
+
const n = sz & 0x7fff;
|
|
928
|
+
if (n < 1 || n > 4 || q + 5 + n > stop) return end("a dataset has an unusable extended length", `IPTC: a dataset has an extended length of ${n} bytes, which is not valid here`);
|
|
929
|
+
sz = 0;
|
|
930
|
+
for (let i = 0; i < n; i++) sz = sz * 256 + b[q + 5 + i];
|
|
931
|
+
head += n;
|
|
932
|
+
}
|
|
933
|
+
if (q + head + sz > stop) return end("a dataset runs past the end of its block", "IPTC: a dataset runs past the end of its block");
|
|
934
|
+
if (rec === 2) out.push({ dataset: ds, at: q + head, size: sz });
|
|
935
|
+
else if (rec === 1 && ds === 90) out.charset = b.subarray(q + head, q + head + Math.min(sz, 16));
|
|
936
|
+
q += head + sz;
|
|
937
|
+
}
|
|
938
|
+
if (q < stop && b.subarray(q, stop).some((v) => v !== 0)) return end("bytes follow the last dataset that aren't a dataset");
|
|
939
|
+
return out;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* The record-2 datasets of the Photoshop resources in `b[from, stop)` (the 8BIM blocks; the IPTC one has id 0x0404):
|
|
944
|
+
* walkIim's result for each IPTC resource, joined. A resource that claims more than is there ends the walk.
|
|
945
|
+
*/
|
|
946
|
+
function readPhotoshop(b, from, stop, errors) {
|
|
947
|
+
const out = [];
|
|
948
|
+
let at = from;
|
|
949
|
+
while (at + 12 <= stop && startsWith(b, at, "8BIM")) {
|
|
950
|
+
const id = be16(b, at + 4);
|
|
951
|
+
const nameLen = b[at + 6];
|
|
952
|
+
const p = at + 6 + 1 + nameLen + ((1 + nameLen) & 1);
|
|
953
|
+
if (p + 4 > stop) return (errors.add("IPTC: a Photoshop resource is cut short"), (out.stopped = out.stopped ?? "a Photoshop resource is cut short"), out);
|
|
954
|
+
const size = be32(b, p);
|
|
955
|
+
const end = p + 4 + size;
|
|
956
|
+
if (end > stop) return (errors.add("IPTC: a Photoshop resource claims more bytes than the block holds"), (out.stopped = out.stopped ?? "a Photoshop resource claims more bytes than the block holds"), out);
|
|
957
|
+
if (id === 0x0404) {
|
|
958
|
+
const r = walkIim(b, p + 4, end, errors);
|
|
959
|
+
out.push(...r);
|
|
960
|
+
if (r.charset) out.charset = r.charset;
|
|
961
|
+
if (r.stopped) out.stopped = out.stopped ?? r.stopped;
|
|
962
|
+
}
|
|
963
|
+
at = end + (size & 1);
|
|
964
|
+
}
|
|
965
|
+
return out;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** The IPTC datasets of a JPEG's APP13 segment `seg` (see walkIim and readPhotoshop). */
|
|
969
|
+
const readIptc = (b, seg, errors) => readPhotoshop(b, seg.data + PS_HEAD.length, seg.data + seg.size, errors);
|
|
970
|
+
|
|
971
|
+
/**
|
|
972
|
+
* What an IPTC dataset list says: `{ entries: [{ field, value }], place }` (`place`: a place dataset has a value, whatever
|
|
973
|
+
* its character set) and a note for `unsupported` when the character set (1:90) is one that isn't decoded. UTF-8 is
|
|
974
|
+
* declared by ESC % G; with no 1:90 a value is UTF-8 if it is valid UTF-8 and Latin-1 otherwise.
|
|
975
|
+
*/
|
|
976
|
+
function iptcReport(b, list, unsupported) {
|
|
977
|
+
const cs = list.charset ? latin1(list.charset) : "";
|
|
978
|
+
const declaredUtf8 = cs === "\x1b%G";
|
|
979
|
+
const other = cs && !declaredUtf8;
|
|
980
|
+
if (other && !unsupported.some((u) => u.startsWith("IPTC character set"))) unsupported.push(`IPTC character set (1:90 is ${JSON.stringify(printable(cs) || "escape codes")}) is not decoded: values are shown as Latin-1 and may read wrongly; place names in it are still found and blanked`);
|
|
981
|
+
const entries = [];
|
|
982
|
+
let place = false;
|
|
983
|
+
for (const d of list) {
|
|
984
|
+
const raw = b.subarray(d.at, d.at + d.size);
|
|
985
|
+
if (IPTC_PLACES.has(d.dataset) && raw.some((v) => v !== 0 && v !== 0x20)) place = true;
|
|
986
|
+
if (entries.length >= LIMITS.textEntries) continue;
|
|
987
|
+
const shown = raw.subarray(0, Math.min(raw.length, LIMITS.textChars * 2));
|
|
988
|
+
let value;
|
|
989
|
+
if (declaredUtf8) value = utf8(shown);
|
|
990
|
+
else if (other) value = latin1(shown);
|
|
991
|
+
else {
|
|
992
|
+
try {
|
|
993
|
+
value = new TextDecoder("utf-8", { fatal: true }).decode(shown);
|
|
994
|
+
} catch {
|
|
995
|
+
value = latin1(shown);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
value = clip(printable(value));
|
|
999
|
+
if (value) entries.push({ field: IPTC_FIELDS[d.dataset] ?? `2:${d.dataset}`, value });
|
|
1000
|
+
}
|
|
1001
|
+
return { entries, place };
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/** Blank the place datasets of `list` in `target` (a copy of the bytes `list` was read from, offset by `base`), in place. */
|
|
1005
|
+
function blankIptcPlaces(target, list, base = 0) {
|
|
1006
|
+
let n = 0;
|
|
1007
|
+
for (const d of list) if (IPTC_PLACES.has(d.dataset)) (target.fill(0x20, d.at - base, d.at - base + d.size), n++);
|
|
1008
|
+
return n;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function jpegKind(b, seg) {
|
|
1012
|
+
const m = seg.marker;
|
|
1013
|
+
if (m === 0xfe) return "comment";
|
|
1014
|
+
if (m < 0xe0 || m > 0xef) return "image";
|
|
1015
|
+
const d = seg.data;
|
|
1016
|
+
if (m === 0xe1) {
|
|
1017
|
+
if (startsWith(b, d, EXIF_HEAD)) return "exif";
|
|
1018
|
+
if (startsWith(b, d, XMP_HEAD)) return "xmp";
|
|
1019
|
+
if (startsWith(b, d, XMP_EXT_HEAD)) return "xmp-extension";
|
|
1020
|
+
return "app";
|
|
1021
|
+
}
|
|
1022
|
+
if (m === 0xe0 && (startsWith(b, d, "JFIF\0") || startsWith(b, d, "JFXX\0"))) return "jfif";
|
|
1023
|
+
if (m === 0xe2 && startsWith(b, d, ICC_HEAD)) return "icc";
|
|
1024
|
+
if (m === 0xed && startsWith(b, d, PS_HEAD)) return "iptc";
|
|
1025
|
+
if (m === 0xeb && (ascii(b, d, 2) === "JP" || /jumb|c2pa/.test(ascii(b, d, 16)))) return "c2pa";
|
|
1026
|
+
if (m === 0xee && startsWith(b, d, "Adobe")) return "adobe";
|
|
1027
|
+
return "app";
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// ── PNG ──────────────────────────────────────────────────────────────────────
|
|
1031
|
+
|
|
1032
|
+
function parsePng(b, errors) {
|
|
1033
|
+
const out = { chunks: [], width: undefined, height: undefined, iend: false };
|
|
1034
|
+
let at = 8;
|
|
1035
|
+
while (at + 8 <= b.length) {
|
|
1036
|
+
if (out.chunks.length >= LIMITS.chunks) {
|
|
1037
|
+
errors.add(`PNG: more than ${LIMITS.chunks} chunks; the rest are not read`);
|
|
1038
|
+
return out;
|
|
1039
|
+
}
|
|
1040
|
+
const len = be32(b, at);
|
|
1041
|
+
const type = ascii(b, at + 4, 4);
|
|
1042
|
+
const end = at + 12 + len;
|
|
1043
|
+
if (len > 0x7fffffff || end > b.length) {
|
|
1044
|
+
errors.add(`PNG: chunk ${type} claims ${len} bytes but ${Math.max(0, b.length - at - 8)} remain`);
|
|
1045
|
+
return out;
|
|
1046
|
+
}
|
|
1047
|
+
if (!/^[A-Za-z]{4}$/.test(type)) {
|
|
1048
|
+
errors.add(`PNG: bad chunk type at byte ${at + 4}`);
|
|
1049
|
+
return out;
|
|
1050
|
+
}
|
|
1051
|
+
out.chunks.push({ type, start: at, data: at + 8, size: len, end });
|
|
1052
|
+
if (type === "IHDR" && len >= 8) (out.width = be32(b, at + 8)), (out.height = be32(b, at + 12));
|
|
1053
|
+
at = end;
|
|
1054
|
+
if (type === "IEND") {
|
|
1055
|
+
out.iend = true;
|
|
1056
|
+
out.trailing = b.length - end;
|
|
1057
|
+
return out;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (!out.iend) errors.add("PNG: no IEND chunk (truncated)");
|
|
1061
|
+
return out;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/** A PNG text chunk's `{ keyword, text?, compressed? }`, or undefined. */
|
|
1065
|
+
function pngText(b, c) {
|
|
1066
|
+
const d = b.subarray(c.data, c.data + c.size);
|
|
1067
|
+
const nul = d.indexOf(0);
|
|
1068
|
+
if (nul < 1 || nul > 79) return undefined;
|
|
1069
|
+
const keyword = latin1(d.subarray(0, nul));
|
|
1070
|
+
if (c.type === "tEXt") return { keyword, text: clip(printable(latin1(d.subarray(nul + 1)))) };
|
|
1071
|
+
if (c.type === "zTXt") return { keyword, compressed: true };
|
|
1072
|
+
if (c.type === "iTXt") {
|
|
1073
|
+
const flag = d[nul + 1];
|
|
1074
|
+
let p = nul + 3; // flag, method
|
|
1075
|
+
const l1 = d.indexOf(0, p);
|
|
1076
|
+
if (l1 < 0) return undefined;
|
|
1077
|
+
const l2 = d.indexOf(0, l1 + 1);
|
|
1078
|
+
if (l2 < 0) return undefined;
|
|
1079
|
+
p = l2 + 1;
|
|
1080
|
+
if (flag === 1) return { keyword, compressed: true };
|
|
1081
|
+
return { keyword, text: d.subarray(p), international: true };
|
|
1082
|
+
}
|
|
1083
|
+
return undefined;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// A text entry "names a location" when its keyword says so (GPS, latitude, location, …) or its text holds a
|
|
1087
|
+
// coordinate pair, a geo: URI or degrees-minutes-seconds with a hemisphere. Compressed entries are judged by
|
|
1088
|
+
// keyword alone (they are not inflated). Prose that merely mentions a place can't be told from any other prose.
|
|
1089
|
+
const LOCATION_KEY = /gps|latitude|longitude|geotag|geolocation|(^|[^a-z])(location|coordinates?)([^a-z]|$)/i;
|
|
1090
|
+
const LOCATION_TEXT = /(^|[^\d.])-?\d{1,3}\.\d{3,}\s*[,;/]\s*-?\d{1,3}\.\d{3,}(?![\d])|geo:-?\d|\d{1,3}\s*°\s*\d{1,2}\s*['′]\s*[\d.]+\s*["″]?\s*[NSEW]/i;
|
|
1091
|
+
const namesLocationText = (text) => LOCATION_TEXT.test(text);
|
|
1092
|
+
function namesLocation(t) {
|
|
1093
|
+
if (LOCATION_KEY.test(t.keyword)) return true;
|
|
1094
|
+
if (t.compressed) return false;
|
|
1095
|
+
return LOCATION_TEXT.test(typeof t.text === "string" ? t.text : utf8(t.text));
|
|
1096
|
+
}
|
|
1097
|
+
const RAW_PROFILE = /^Raw profile type /i;
|
|
1098
|
+
|
|
1099
|
+
// ── PNG raw profiles ─────────────────────────────────────────────────────────
|
|
1100
|
+
// ImageMagick and ExifTool keep EXIF, IPTC and XMP in a PNG as a text entry "Raw profile type <name>" whose text is
|
|
1101
|
+
// "\n<name>\n<length>\n<hex>" (usually zTXt, so compressed). Reading one needs inflate, which is async
|
|
1102
|
+
// (DecompressionStream), so this part serves inspectAsync/editAsync; the synchronous functions only name the entry.
|
|
1103
|
+
|
|
1104
|
+
/** Where a PNG text chunk's text starts: `{ prefix, compressed, payload }` (what comes before it, whether it is deflated, the text bytes). */
|
|
1105
|
+
function textLayout(b, c) {
|
|
1106
|
+
const d = b.subarray(c.data, c.data + c.size);
|
|
1107
|
+
const nul = d.indexOf(0);
|
|
1108
|
+
if (nul < 1) return undefined;
|
|
1109
|
+
if (c.type === "tEXt") return { prefix: d.subarray(0, nul + 1), compressed: false, payload: d.subarray(nul + 1) };
|
|
1110
|
+
if (c.type === "zTXt") return d[nul + 1] === 0 ? { prefix: d.subarray(0, nul + 2), compressed: true, payload: d.subarray(nul + 2) } : undefined;
|
|
1111
|
+
if (c.type === "iTXt") {
|
|
1112
|
+
const l1 = d.indexOf(0, nul + 3);
|
|
1113
|
+
const l2 = l1 < 0 ? -1 : d.indexOf(0, l1 + 1);
|
|
1114
|
+
if (l2 < 0 || d[nul + 2] !== 0) return undefined; // only compression method 0
|
|
1115
|
+
return { prefix: d.subarray(0, l2 + 1), compressed: d[nul + 1] === 1, payload: d.subarray(l2 + 1), international: true };
|
|
1116
|
+
}
|
|
1117
|
+
return undefined;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
async function pipeBytes(bytes, stream, max) {
|
|
1121
|
+
const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader();
|
|
1122
|
+
const parts = [];
|
|
1123
|
+
let n = 0;
|
|
1124
|
+
for (;;) {
|
|
1125
|
+
const { done, value } = await reader.read();
|
|
1126
|
+
if (done) break;
|
|
1127
|
+
n += value.length;
|
|
1128
|
+
if (n > max) {
|
|
1129
|
+
await reader.cancel().catch(() => {});
|
|
1130
|
+
return { why: `it inflates to more than ${max} bytes` };
|
|
1131
|
+
}
|
|
1132
|
+
parts.push(value);
|
|
1133
|
+
}
|
|
1134
|
+
return { bytes: concat(parts) };
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/** zlib-inflate `bytes`, refusing output over `max`: `{ bytes }` or `{ why }`. */
|
|
1138
|
+
async function inflate(bytes, max) {
|
|
1139
|
+
if (typeof DecompressionStream !== "function" || typeof Blob !== "function") return { why: "this runtime has no DecompressionStream" };
|
|
1140
|
+
try {
|
|
1141
|
+
return await pipeBytes(bytes, new DecompressionStream("deflate"), max);
|
|
1142
|
+
} catch {
|
|
1143
|
+
return { why: "its compressed data is damaged" };
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/** zlib-deflate `bytes`, or null when this runtime can't. */
|
|
1148
|
+
async function deflate(bytes) {
|
|
1149
|
+
if (typeof CompressionStream !== "function" || typeof Blob !== "function") return null;
|
|
1150
|
+
try {
|
|
1151
|
+
return (await pipeBytes(bytes, new CompressionStream("deflate"), Infinity)).bytes ?? null;
|
|
1152
|
+
} catch {
|
|
1153
|
+
return null;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/** The bytes a raw-profile text holds: `{ name, bytes }` or `{ why }`. The declared length must match exactly. */
|
|
1158
|
+
function parseRawProfile(text) {
|
|
1159
|
+
const m = /^\s*([^\n]*)\n\s*(\d+)\s*\n([\s\S]*)$/.exec(text);
|
|
1160
|
+
if (!m) return { why: "it isn't in the raw-profile layout (name, length, hex)" };
|
|
1161
|
+
const hex = m[3].replace(/\s+/g, "");
|
|
1162
|
+
if (!/^[0-9a-fA-F]*$/.test(hex)) return { why: "its hex text has characters that aren't hex" };
|
|
1163
|
+
if (hex.length & 1) return { why: "its hex text has an odd number of digits" };
|
|
1164
|
+
const length = Number(m[2]);
|
|
1165
|
+
if (hex.length / 2 !== length) return { why: `it says it holds ${length} bytes but its hex holds ${hex.length / 2}` };
|
|
1166
|
+
const bytes = new Uint8Array(length);
|
|
1167
|
+
for (let i = 0; i < length; i++) bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
|
|
1168
|
+
return { name: m[1].trim(), bytes };
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/** The raw-profile layout for `bytes`, as lines of 72 hex digits, like the writers that make them. */
|
|
1172
|
+
function rawProfileText(name, bytes) {
|
|
1173
|
+
let hex = "";
|
|
1174
|
+
for (let i = 0; i < bytes.length; i++) hex += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
|
|
1175
|
+
const lines = hex.match(/.{1,72}/g) ?? [];
|
|
1176
|
+
return `\n${name}\n${String(bytes.length).padStart(8)}\n${lines.join("\n")}\n`;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/** What a decoded profile is, from its content (not its name): `{ kind: "exif" | "xmp" | "iim" | "photoshop" | "icc", at }` or null. */
|
|
1180
|
+
function sniffProfile(p, name) {
|
|
1181
|
+
if (startsWith(p, 0, EXIF_HEAD)) return { kind: "exif", at: 6 };
|
|
1182
|
+
if ((p[0] === 0x49 && p[1] === 0x49 && p[2] === 0x2a && p[3] === 0) || (p[0] === 0x4d && p[1] === 0x4d && p[2] === 0 && p[3] === 0x2a)) return { kind: "exif", at: 0 };
|
|
1183
|
+
if (startsWith(p, 0, XMP_HEAD)) return { kind: "xmp", at: XMP_HEAD.length };
|
|
1184
|
+
if (p[0] === 0x1c) return { kind: "iim", at: 0 };
|
|
1185
|
+
if (startsWith(p, 0, PS_HEAD)) return { kind: "photoshop", at: PS_HEAD.length };
|
|
1186
|
+
if (startsWith(p, 0, "8BIM")) return { kind: "photoshop", at: 0 };
|
|
1187
|
+
if (p.length > 40 && ascii(p, 36, 4) === "acsp") return { kind: "icc", at: 0 };
|
|
1188
|
+
if (/^xmp$/i.test(name) || /<\?xpacket|<x:xmpmeta|<rdf:RDF/.test(latin1(p.subarray(0, 4096)))) return { kind: "xmp", at: 0 };
|
|
1189
|
+
return null;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/**
|
|
1193
|
+
* Decode every raw-profile text chunk of a PNG (up to LIMITS.rawProfiles): a Map from the chunk's start offset to
|
|
1194
|
+
* `{ ok: true, name, kind, at, inner }` (the profile's bytes) or `{ ok: false, why }`. Chunks beyond the limit are
|
|
1195
|
+
* absent, so a reader counts them as not decoded.
|
|
1196
|
+
*/
|
|
1197
|
+
async function decodeRawProfiles(b) {
|
|
1198
|
+
const out = new Map();
|
|
1199
|
+
const p = parsePng(b, new Errors());
|
|
1200
|
+
let n = 0;
|
|
1201
|
+
for (const c of p.chunks) {
|
|
1202
|
+
if (c.type !== "tEXt" && c.type !== "zTXt" && c.type !== "iTXt") continue;
|
|
1203
|
+
const t = pngText(b, c);
|
|
1204
|
+
if (!t || !RAW_PROFILE.test(t.keyword)) continue;
|
|
1205
|
+
if (n++ >= LIMITS.rawProfiles) break;
|
|
1206
|
+
const layout = textLayout(b, c);
|
|
1207
|
+
if (!layout) {
|
|
1208
|
+
out.set(c.start, { ok: false, why: "the text chunk is malformed" });
|
|
1209
|
+
continue;
|
|
1210
|
+
}
|
|
1211
|
+
let payload = layout.payload;
|
|
1212
|
+
if (layout.compressed) {
|
|
1213
|
+
const r = await inflate(payload, LIMITS.rawProfileBytes);
|
|
1214
|
+
if (!r.bytes) {
|
|
1215
|
+
out.set(c.start, { ok: false, why: r.why });
|
|
1216
|
+
continue;
|
|
1217
|
+
}
|
|
1218
|
+
payload = r.bytes;
|
|
1219
|
+
} else if (payload.length > LIMITS.rawProfileBytes * 2 + 64) {
|
|
1220
|
+
out.set(c.start, { ok: false, why: `it is larger than ${LIMITS.rawProfileBytes} bytes` });
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
const parsed = parseRawProfile(latin1(payload));
|
|
1224
|
+
if (!parsed.bytes) {
|
|
1225
|
+
out.set(c.start, { ok: false, why: parsed.why });
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
const kind = sniffProfile(parsed.bytes, parsed.name);
|
|
1229
|
+
if (!kind) {
|
|
1230
|
+
out.set(c.start, { ok: false, why: "its contents aren't EXIF, IPTC, XMP or a color profile" });
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
out.set(c.start, { ok: true, name: parsed.name, layout, chunk: c, ...kind, inner: parsed.bytes });
|
|
1234
|
+
}
|
|
1235
|
+
return out;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/** What a decoded profile says: `{ location?, place, hasGps, xmpGps, fields: [...], hasMakerNote, stopped?, notes: [] }`. */
|
|
1239
|
+
function readInner(a, errors, unsupported) {
|
|
1240
|
+
const out = { hasGps: false, xmpGps: false, place: false, fields: [], hasMakerNote: false };
|
|
1241
|
+
const { kind, at, inner } = a;
|
|
1242
|
+
if (kind === "exif") {
|
|
1243
|
+
const r = readExif(inner.subarray(at), errors);
|
|
1244
|
+
out.location = r.location;
|
|
1245
|
+
out.hasGps = r.hasGps;
|
|
1246
|
+
out.hasMakerNote = r.hasMakerNote && !r.makerNote;
|
|
1247
|
+
out.makerNoteLocation = Boolean(r.makerNote?.places.length || r.makerNote?.fields.some((f) => f.place));
|
|
1248
|
+
for (const e of [...r.personal, ...r.technical]) out.fields.push({ profile: "exif", tag: e.tag, value: e.value });
|
|
1249
|
+
} else if (kind === "xmp") {
|
|
1250
|
+
const r = readXmp(inner.subarray(at), errors);
|
|
1251
|
+
out.xmpGps = r.gps;
|
|
1252
|
+
for (const e of r.props) out.fields.push({ profile: "xmp", name: e.name, value: e.value });
|
|
1253
|
+
} else if (kind === "iim" || kind === "photoshop") {
|
|
1254
|
+
const list = kind === "iim" ? walkIim(inner, 0, inner.length, errors) : readPhotoshop(inner, at, inner.length, errors);
|
|
1255
|
+
const r = iptcReport(inner, list, unsupported);
|
|
1256
|
+
out.place = r.place;
|
|
1257
|
+
out.list = list;
|
|
1258
|
+
out.stopped = list.stopped;
|
|
1259
|
+
for (const e of r.entries) out.fields.push({ profile: "iptc", ...e });
|
|
1260
|
+
}
|
|
1261
|
+
out.located = Boolean(out.location || out.hasGps || out.xmpGps || out.place || out.makerNoteLocation);
|
|
1262
|
+
return out;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/**
|
|
1266
|
+
* Blank the location out of a decoded profile's bytes `a.inner`, in place: the EXIF GPS block, XMP GPS and place
|
|
1267
|
+
* properties, IPTC place datasets. Returns `{ changed, why? }`.
|
|
1268
|
+
*/
|
|
1269
|
+
function scrubInner(a, errors) {
|
|
1270
|
+
const before = a.inner.slice();
|
|
1271
|
+
let why;
|
|
1272
|
+
const { kind, at, inner } = a;
|
|
1273
|
+
if (kind === "exif") why = removeGpsFromTiff(inner.subarray(at), errors).why;
|
|
1274
|
+
else if (kind === "xmp") inner.set(blankXmpGps(inner.subarray(at)).bytes, at);
|
|
1275
|
+
else if (kind === "iim" || kind === "photoshop") {
|
|
1276
|
+
const list = kind === "iim" ? walkIim(inner, 0, inner.length, errors) : readPhotoshop(inner, at, inner.length, errors);
|
|
1277
|
+
blankIptcPlaces(inner, list);
|
|
1278
|
+
}
|
|
1279
|
+
return { changed: before.some((v, i) => v !== inner[i]), why };
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/** The chunk `a.chunk` rewritten to hold `a.inner`: the same type, keyword and compression where the runtime can compress, an uncompressed entry where not. */
|
|
1283
|
+
async function rawProfileChunk(a) {
|
|
1284
|
+
const text = fromLatin1(rawProfileText(a.name, a.inner));
|
|
1285
|
+
const { layout, chunk } = a;
|
|
1286
|
+
let prefix = layout.prefix;
|
|
1287
|
+
let type = chunk.type;
|
|
1288
|
+
let payload = text;
|
|
1289
|
+
if (layout.compressed) {
|
|
1290
|
+
const z = await deflate(text);
|
|
1291
|
+
if (z) payload = z;
|
|
1292
|
+
else if (type === "zTXt") (type = "tEXt"), (prefix = prefix.subarray(0, prefix.length - 1)); // drop the method byte
|
|
1293
|
+
else (prefix = prefix.slice()), (prefix[prefix.indexOf(0) + 1] = 0);
|
|
1294
|
+
}
|
|
1295
|
+
return pngChunk(type, concat([prefix, payload]));
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
const PNG_KEEP = new Set(["IHDR", "PLTE", "IDAT", "IEND", "tRNS", "cHRM", "gAMA", "sBIT", "sRGB", "cICP", "mDCV", "cLLI", "bKGD", "hIST", "pHYs", "sPLT", "acTL", "fcTL", "fdAT", "oFFs", "pCAL", "sCAL", "sTER"]);
|
|
1299
|
+
|
|
1300
|
+
// ── WebP ─────────────────────────────────────────────────────────────────────
|
|
1301
|
+
|
|
1302
|
+
function parseWebp(b, errors) {
|
|
1303
|
+
const out = { chunks: [], width: undefined, height: undefined, flags: 0, vp8x: false };
|
|
1304
|
+
const riff = le32(b, 4);
|
|
1305
|
+
if (riff + 8 > b.length) errors.add(`WebP: the RIFF size says ${riff + 8} bytes but the file has ${b.length}`);
|
|
1306
|
+
const limit = Math.min(b.length, riff + 8);
|
|
1307
|
+
let at = 12;
|
|
1308
|
+
while (at + 8 <= limit) {
|
|
1309
|
+
if (out.chunks.length >= LIMITS.chunks) {
|
|
1310
|
+
errors.add(`WebP: more than ${LIMITS.chunks} chunks; the rest are not read`);
|
|
1311
|
+
return out;
|
|
1312
|
+
}
|
|
1313
|
+
const fourcc = ascii(b, at, 4);
|
|
1314
|
+
const size = le32(b, at + 4);
|
|
1315
|
+
const end = at + 8 + size + (size & 1);
|
|
1316
|
+
if (at + 8 + size > limit) {
|
|
1317
|
+
errors.add(`WebP: chunk ${JSON.stringify(fourcc)} claims ${size} bytes but ${Math.max(0, limit - at - 8)} remain`);
|
|
1318
|
+
return out;
|
|
1319
|
+
}
|
|
1320
|
+
out.chunks.push({ type: fourcc, start: at, data: at + 8, size, end: Math.min(end, b.length) });
|
|
1321
|
+
if (fourcc === "VP8X" && size >= 10) {
|
|
1322
|
+
out.vp8x = true;
|
|
1323
|
+
out.flags = b[at + 8];
|
|
1324
|
+
out.width = 1 + (b[at + 12] | (b[at + 13] << 8) | (b[at + 14] << 16));
|
|
1325
|
+
out.height = 1 + (b[at + 15] | (b[at + 16] << 8) | (b[at + 17] << 16));
|
|
1326
|
+
} else if (fourcc === "VP8L" && size >= 5 && b[at + 8] === 0x2f && out.width === undefined) {
|
|
1327
|
+
out.width = 1 + (b[at + 9] | ((b[at + 10] & 0x3f) << 8));
|
|
1328
|
+
out.height = 1 + ((b[at + 10] >> 6) | (b[at + 11] << 2) | ((b[at + 12] & 0x0f) << 10));
|
|
1329
|
+
out.alpha = Boolean(b[at + 12] & 0x10);
|
|
1330
|
+
} else if (fourcc === "VP8 " && size >= 10 && b[at + 11] === 0x9d && b[at + 12] === 0x01 && b[at + 13] === 0x2a && out.width === undefined) {
|
|
1331
|
+
out.width = le16(b, at + 14) & 0x3fff;
|
|
1332
|
+
out.height = le16(b, at + 16) & 0x3fff;
|
|
1333
|
+
}
|
|
1334
|
+
at = end;
|
|
1335
|
+
}
|
|
1336
|
+
return out;
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
const exifPayload = (b, c) => {
|
|
1340
|
+
// WebP's EXIF chunk is the TIFF block, though some writers prefix "Exif\0\0".
|
|
1341
|
+
const from = startsWith(b, c.data, EXIF_HEAD) ? c.data + 6 : c.data;
|
|
1342
|
+
return b.subarray(from, c.data + c.size);
|
|
1343
|
+
};
|
|
1344
|
+
|
|
1345
|
+
// ── inspect ──────────────────────────────────────────────────────────────────
|
|
1346
|
+
|
|
1347
|
+
const refuse = (reason, message) => ({ ok: false, reason, message });
|
|
1348
|
+
|
|
1349
|
+
/**
|
|
1350
|
+
* What an image's bytes say about it. Never throws.
|
|
1351
|
+
* @returns {object} `{ ok: true, format, bytes, width?, height?, orientation?, orientationText?, has: {...}, technical: [...],
|
|
1352
|
+
* $personalMetadata: { location?, exif: [...], xmp: [...], text: [...] }, unsupported: [...], warnings: [...], errors: [...] }`
|
|
1353
|
+
* or `{ ok: false, reason: "empty" | "unsupported" | "too-large" | "malformed", message }`.
|
|
1354
|
+
*/
|
|
1355
|
+
export function inspect(bytes) {
|
|
1356
|
+
try {
|
|
1357
|
+
return inspectBytes(bytes);
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
return refuse("malformed", `this image's metadata couldn't be read safely (${clip(String(error?.message ?? error), 120)})`);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
function inspectBytes(b, raw) {
|
|
1364
|
+
if (!(b instanceof Uint8Array)) return refuse("unsupported", "expected the image's bytes");
|
|
1365
|
+
if (b.length === 0) return refuse("empty", "the image has no bytes");
|
|
1366
|
+
if (b.length > LIMITS.bytes) return refuse("too-large", `the image is ${b.length} bytes; metadata is read from images up to ${LIMITS.bytes}`);
|
|
1367
|
+
const format = detectFormat(b);
|
|
1368
|
+
if (!format) {
|
|
1369
|
+
const other = orientationOf(b);
|
|
1370
|
+
if (other) return { ...refuse("unsupported", `metadata is read from ${SUPPORTED}; these bytes are ${/^[AEIOU]/.test(OTHER_NAME[other.format]) ? "an" : "a"} ${OTHER_NAME[other.format]} (${other.orientation ? `orientation ${other.orientation}: ${other.orientationText}` : other.orientationText}); the file is left as it is`), ...other };
|
|
1371
|
+
return refuse("unsupported", `metadata is read from ${SUPPORTED}; these bytes are another format (they are left as they are)`);
|
|
1372
|
+
}
|
|
1373
|
+
const errors = new Errors();
|
|
1374
|
+
const warnings = [];
|
|
1375
|
+
const unsupported = [];
|
|
1376
|
+
const personal = { exif: [], xmp: [], text: [], iptc: [] };
|
|
1377
|
+
const has = { exif: false, xmp: false, icc: false, iptc: false, text: false, contentCredentials: false, location: false, thumbnail: false, animated: false };
|
|
1378
|
+
let technical = [];
|
|
1379
|
+
let width;
|
|
1380
|
+
let height;
|
|
1381
|
+
let orientation;
|
|
1382
|
+
let exifBlocks = 0;
|
|
1383
|
+
const useExif = (tiff) => {
|
|
1384
|
+
exifBlocks++;
|
|
1385
|
+
if (exifBlocks > 1) return warnings.push("more than one EXIF block; only the first is read");
|
|
1386
|
+
has.exif = true;
|
|
1387
|
+
const r = readExif(tiff, errors);
|
|
1388
|
+
technical = r.technical;
|
|
1389
|
+
personal.exif = r.personal;
|
|
1390
|
+
orientation = r.orientation;
|
|
1391
|
+
if (r.location) (personal.location = r.location), (has.location = true);
|
|
1392
|
+
else if (r.hasGps) has.location = "fields without coordinates";
|
|
1393
|
+
if (r.makerNote) {
|
|
1394
|
+
has.makerNote = true;
|
|
1395
|
+
personal.makerNote = { maker: r.makerNote.maker, layout: r.makerNote.layout, entries: r.makerNote.count, fields: r.makerNote.fields };
|
|
1396
|
+
if (r.makerNote.places.length || r.makerNote.fields.some((f) => f.place)) {
|
|
1397
|
+
has.makerNoteLocation = true;
|
|
1398
|
+
if (!has.location) has.location = "in MakerNote";
|
|
1399
|
+
}
|
|
1400
|
+
unsupported.push("MakerNote (vendor data) decoded as a field list: its text and short numeric fields are listed under makerNote and a place spelled in its text is found; its binary fields are not interpreted, so a location stored as numbers there would not be found");
|
|
1401
|
+
} else if (r.hasMakerNote) unsupported.push("MakerNote (vendor data): present and not decoded; some cameras keep a location or serial number there");
|
|
1402
|
+
has.thumbnail = r.thumbnail;
|
|
1403
|
+
};
|
|
1404
|
+
const useXmp = (xmpBytes) => {
|
|
1405
|
+
if (has.xmp) return warnings.push("more than one XMP packet; only the first is read");
|
|
1406
|
+
has.xmp = true;
|
|
1407
|
+
const r = readXmp(xmpBytes, errors);
|
|
1408
|
+
personal.xmp = r.props;
|
|
1409
|
+
if (r.gps) {
|
|
1410
|
+
has.xmpGps = true;
|
|
1411
|
+
if (!has.location) has.location = "in XMP";
|
|
1412
|
+
}
|
|
1413
|
+
if (orientation === undefined && r.orientation) orientation = r.orientation;
|
|
1414
|
+
};
|
|
1415
|
+
|
|
1416
|
+
if (format === "jpeg") {
|
|
1417
|
+
const j = parseJpeg(b, errors);
|
|
1418
|
+
width = j.width;
|
|
1419
|
+
height = j.height;
|
|
1420
|
+
let iccParts = 0;
|
|
1421
|
+
let iccBytes = 0;
|
|
1422
|
+
let iptcNote = false;
|
|
1423
|
+
for (const seg of j.segments) {
|
|
1424
|
+
const kind = jpegKind(b, seg);
|
|
1425
|
+
if (kind === "exif") useExif(b.subarray(seg.data + 6, seg.data + seg.size));
|
|
1426
|
+
else if (kind === "xmp") useXmp(b.subarray(seg.data + XMP_HEAD.length, seg.data + seg.size));
|
|
1427
|
+
else if (kind === "xmp-extension") unsupported.push("extended XMP (a second packet for large XMP): present and not read");
|
|
1428
|
+
else if (kind === "icc") (iccParts++, (iccBytes += seg.size - ICC_HEAD.length - 2));
|
|
1429
|
+
else if (kind === "iptc") {
|
|
1430
|
+
has.iptc = true;
|
|
1431
|
+
if (!iptcNote) (iptcNote = true), unsupported.push("IPTC/Photoshop block: every record-2 dataset (long ones too) is listed, with the place names and common fields (byline, caption, credit, copyright) named; other Photoshop resources are not decoded");
|
|
1432
|
+
const list = readIptc(b, seg, errors);
|
|
1433
|
+
const r = iptcReport(b, list, unsupported);
|
|
1434
|
+
if (r.place) has.iptcLocation = true;
|
|
1435
|
+
for (const e of r.entries) if (personal.iptc.length < LIMITS.textEntries) personal.iptc.push(e);
|
|
1436
|
+
if (list.stopped) unsupported.push(`IPTC: ${list.stopped}; the datasets after it are not read, so a place name there would not be found`);
|
|
1437
|
+
}
|
|
1438
|
+
else if (kind === "c2pa") has.contentCredentials = true;
|
|
1439
|
+
else if (kind === "comment") personal.text.push({ keyword: "JPEG comment", text: clip(printable(latin1(b.subarray(seg.data, seg.data + Math.min(seg.size, LIMITS.textChars * 2))))) });
|
|
1440
|
+
}
|
|
1441
|
+
if (iccParts) has.icc = { bytes: Math.max(0, iccBytes), parts: iccParts };
|
|
1442
|
+
if (has.iptcLocation && !has.location) has.location = "in IPTC";
|
|
1443
|
+
if (j.eoi > 0 && j.eoi < b.length) unsupported.push(`${b.length - j.eoi} bytes follow the end of the image: not read (a camera's preview or video can sit there)`);
|
|
1444
|
+
} else if (format === "png") {
|
|
1445
|
+
const p = parsePng(b, errors);
|
|
1446
|
+
width = p.width;
|
|
1447
|
+
height = p.height;
|
|
1448
|
+
for (const c of p.chunks) {
|
|
1449
|
+
if (c.type === "eXIf") useExif(b.subarray(c.data, c.data + c.size));
|
|
1450
|
+
else if (c.type === "iCCP") {
|
|
1451
|
+
const d = b.subarray(c.data, c.data + Math.min(c.size, 80));
|
|
1452
|
+
const nul = d.indexOf(0);
|
|
1453
|
+
has.icc = { name: clip(printable(latin1(nul < 0 ? d : d.subarray(0, nul))), 80) };
|
|
1454
|
+
}
|
|
1455
|
+
else if (c.type === "caBX") has.contentCredentials = true;
|
|
1456
|
+
else if (c.type === "acTL") has.animated = true;
|
|
1457
|
+
else if (c.type === "tEXt" || c.type === "zTXt" || c.type === "iTXt") {
|
|
1458
|
+
const t = pngText(b, c);
|
|
1459
|
+
if (!t) {
|
|
1460
|
+
errors.add(`PNG: ${c.type} chunk at byte ${c.start} is malformed`);
|
|
1461
|
+
continue;
|
|
1462
|
+
}
|
|
1463
|
+
has.text = true;
|
|
1464
|
+
if (RAW_PROFILE.test(t.keyword)) {
|
|
1465
|
+
has.rawProfile = true;
|
|
1466
|
+
const a = raw?.get(c.start);
|
|
1467
|
+
const name = clip(printable(t.keyword), 40);
|
|
1468
|
+
if (a?.ok) {
|
|
1469
|
+
const r = readInner(a, errors, unsupported);
|
|
1470
|
+
const list = (personal.rawProfile ??= []);
|
|
1471
|
+
for (const f of r.fields) if (list.length < LIMITS.tags) list.push(f);
|
|
1472
|
+
if (r.location && !personal.location) personal.location = r.location;
|
|
1473
|
+
if (r.located) has.rawProfileLocation = true;
|
|
1474
|
+
if (r.hasMakerNote && !unsupported.some((u) => /MakerNote/.test(u))) unsupported.push("MakerNote (vendor data): present and not decoded; some cameras keep a location or serial number there");
|
|
1475
|
+
if (r.stopped) unsupported.push(`IPTC: ${r.stopped} (in the PNG "${name}" entry); the datasets after it are not read, so a place name there would not be found`);
|
|
1476
|
+
if (personal.text.length < LIMITS.textEntries) personal.text.push({ keyword: clip(printable(t.keyword), 80), note: `decoded as ${a.kind === "iim" || a.kind === "photoshop" ? "IPTC" : a.kind.toUpperCase()}: its fields are under rawProfile` });
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1479
|
+
has.rawProfileUndecoded = (has.rawProfileUndecoded ?? 0) + 1;
|
|
1480
|
+
if (has.rawProfileUndecoded <= 8) unsupported.push(`PNG "${name}" entry (a hex-encoded copy of EXIF, IPTC or XMP, as ImageMagick and ExifTool write it): present and not decoded${a ? ` (${a.why})` : raw ? ` (only the first ${LIMITS.rawProfiles} are decoded)` : ""}; it may hold a location`);
|
|
1481
|
+
else if (has.rawProfileUndecoded === 9) unsupported.push("more PNG raw-profile entries, also not decoded");
|
|
1482
|
+
}
|
|
1483
|
+
if (t.keyword === "XML:com.adobe.xmp" && c.type === "iTXt" && t.text) useXmp(t.text);
|
|
1484
|
+
else if (namesLocation(t) && (has.textLocation = true) && personal.text.length < LIMITS.textEntries) personal.text.push({ keyword: clip(printable(t.keyword), 80), ...(t.compressed ? { note: "compressed: not decoded" } : { text: clip(printable(t.international ? utf8(t.text) : t.text)) }) });
|
|
1485
|
+
else if (personal.text.length < LIMITS.textEntries) personal.text.push({ keyword: clip(printable(t.keyword), 80), ...(t.compressed ? { note: "compressed: not decoded" } : { text: clip(printable(t.international ? utf8(t.text) : t.text)) }) });
|
|
1486
|
+
} else if (c.type === "tIME") {
|
|
1487
|
+
has.text = true;
|
|
1488
|
+
if (c.size === 7) personal.text.push({ keyword: "last modified (tIME)", text: `${be16(b, c.data)}-${String(b[c.data + 2]).padStart(2, "0")}-${String(b[c.data + 3]).padStart(2, "0")}` });
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
if (p.trailing) unsupported.push(`${p.trailing} bytes follow the PNG's end: not read`);
|
|
1492
|
+
if (has.textLocation && !has.location) has.location = "in text";
|
|
1493
|
+
if (has.rawProfileLocation && !has.location) has.location = "in PNG raw profile";
|
|
1494
|
+
} else {
|
|
1495
|
+
const w = parseWebp(b, errors);
|
|
1496
|
+
width = w.width;
|
|
1497
|
+
height = w.height;
|
|
1498
|
+
has.animated = w.chunks.some((c) => c.type === "ANIM");
|
|
1499
|
+
for (const c of w.chunks) {
|
|
1500
|
+
if (c.type === "EXIF") useExif(exifPayload(b, c));
|
|
1501
|
+
else if (c.type === "XMP ") useXmp(b.subarray(c.data, c.data + c.size));
|
|
1502
|
+
else if (c.type === "ICCP") has.icc = { bytes: c.size };
|
|
1503
|
+
else if (c.type === "C2PA") has.contentCredentials = true;
|
|
1504
|
+
}
|
|
1505
|
+
if (b.length > le32(b, 4) + 8) unsupported.push(`${b.length - le32(b, 4) - 8} bytes follow the WebP's RIFF end: not read`);
|
|
1506
|
+
}
|
|
1507
|
+
if (has.contentCredentials) warnings.push("Content Credentials (C2PA) are present: any edit of the file's bytes makes their signature fail to verify, and removing all metadata removes them");
|
|
1508
|
+
if (personal.text.length >= LIMITS.textEntries) warnings.push(`only the first ${LIMITS.textEntries} text entries are listed`);
|
|
1509
|
+
const out = {
|
|
1510
|
+
ok: true,
|
|
1511
|
+
format,
|
|
1512
|
+
bytes: b.length,
|
|
1513
|
+
...(width ? { width } : {}),
|
|
1514
|
+
...(height ? { height } : {}),
|
|
1515
|
+
...(orientation ? { orientation, orientationText: ORIENTATION_TEXT[orientation] ?? "not a valid EXIF orientation (1 to 8)" } : {}),
|
|
1516
|
+
has,
|
|
1517
|
+
technical,
|
|
1518
|
+
$personalMetadata: personal,
|
|
1519
|
+
unsupported,
|
|
1520
|
+
warnings,
|
|
1521
|
+
errors: errors.out(),
|
|
1522
|
+
};
|
|
1523
|
+
return out;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
/**
|
|
1527
|
+
* inspect() that also decodes a PNG's "Raw profile type …" entries (inflating them with DecompressionStream, at most
|
|
1528
|
+
* LIMITS.rawProfiles of at most LIMITS.rawProfileBytes each), so a location inside one is found: `has.rawProfileLocation`,
|
|
1529
|
+
* the fields under `$personalMetadata.rawProfile`. An entry that can't be decoded stays named under `unsupported`, with why,
|
|
1530
|
+
* and is counted in `has.rawProfileUndecoded`. Never throws.
|
|
1531
|
+
*/
|
|
1532
|
+
export async function inspectAsync(bytes) {
|
|
1533
|
+
try {
|
|
1534
|
+
const raw = bytes instanceof Uint8Array && bytes.length > 0 && bytes.length <= LIMITS.bytes && detectFormat(bytes) === "png" ? await decodeRawProfiles(bytes) : undefined;
|
|
1535
|
+
return inspectBytes(bytes, raw);
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
return refuse("malformed", `this image's metadata couldn't be read safely (${clip(String(error?.message ?? error), 120)})`);
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/** The report as a short plain-text list, without personal values: for lists, logs and agents. */
|
|
1542
|
+
export function summarize(report) {
|
|
1543
|
+
if (!report?.ok) return report?.message ?? "no report";
|
|
1544
|
+
const bits = [`${FORMAT_NAME[report.format]} ${report.width && report.height ? `${report.width}×${report.height}` : ""}`.trim()];
|
|
1545
|
+
if (report.orientation) bits.push(`orientation ${report.orientation}${report.orientation === 1 ? "" : ` (${report.orientationText})`}`);
|
|
1546
|
+
const present = ["exif", "xmp", "icc", "iptc", "text", "contentCredentials"].filter((k) => report.has[k]).map((k) => (k === "contentCredentials" ? "Content Credentials" : k.toUpperCase()));
|
|
1547
|
+
bits.push(present.length ? `has ${present.join(", ")}` : "no metadata found");
|
|
1548
|
+
if (report.has.location) bits.push("contains location");
|
|
1549
|
+
if (report.errors.length) bits.push(`${report.errors.length} problem${report.errors.length === 1 ? "" : "s"} reading it`);
|
|
1550
|
+
return bits.join("; ");
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
// ── edit ─────────────────────────────────────────────────────────────────────
|
|
1554
|
+
|
|
1555
|
+
/**
|
|
1556
|
+
* Remove metadata from an image's bytes without touching its pixels: the
|
|
1557
|
+
* compressed image data is copied byte for byte, never decoded or re-encoded.
|
|
1558
|
+
*
|
|
1559
|
+
* - `{ gps: true }` removes the location: the EXIF GPS block (zeroed, not just
|
|
1560
|
+
* unlinked) and the `exif:GPS*` properties of XMP (blanked to spaces). Every
|
|
1561
|
+
* other field stays, and the file keeps its length.
|
|
1562
|
+
* - `{ all: true }` removes EXIF, XMP, IPTC, comments, PNG text and time, the
|
|
1563
|
+
* other application data, and Content Credentials. The color profile stays
|
|
1564
|
+
* unless `icc: "strip"`.
|
|
1565
|
+
*
|
|
1566
|
+
* Returns `{ ok: true, bytes, changed, removed: [...], kept: [...], unsupported: [...], warnings: [...] }` (`bytes` is the input
|
|
1567
|
+
* itself when nothing changed), or `{ ok: false, reason, message }`. Never throws.
|
|
1568
|
+
*/
|
|
1569
|
+
export function edit(bytes, options = {}) {
|
|
1570
|
+
try {
|
|
1571
|
+
return editBytes(bytes, options);
|
|
1572
|
+
} catch (error) {
|
|
1573
|
+
return refuse("malformed", `this image couldn't be edited safely (${clip(String(error?.message ?? error), 120)}); it is unchanged`);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/**
|
|
1578
|
+
* edit() that also reads and removes a location inside a PNG's raw profiles (see inspectAsync): the profile's own GPS,
|
|
1579
|
+
* XMP places or IPTC places are blanked in place, and the entry is written back as the same kind of chunk. An entry that
|
|
1580
|
+
* can't be decoded is left as it is and the result warns that a location in it is not removed. With `all`, text entries
|
|
1581
|
+
* are dropped whole as before. Never throws.
|
|
1582
|
+
*/
|
|
1583
|
+
export async function editAsync(bytes, options = {}) {
|
|
1584
|
+
try {
|
|
1585
|
+
return await editBytesAsync(bytes, options);
|
|
1586
|
+
} catch (error) {
|
|
1587
|
+
return refuse("malformed", `this image couldn't be edited safely (${clip(String(error?.message ?? error), 120)}); it is unchanged`);
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
function editBytes(b, options = {}) {
|
|
1592
|
+
const stage = editStage1(b, options);
|
|
1593
|
+
return stage.ok === false ? stage : editStage2(stage, inspectBytes(stage.out.bytes));
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
/** edit() for bytes, inflating a PNG's raw profiles first so a location in one is read, removed and checked (see editAsync). */
|
|
1597
|
+
async function editBytesAsync(b, options = {}) {
|
|
1598
|
+
let rawBefore;
|
|
1599
|
+
if (b instanceof Uint8Array && b.length <= LIMITS.bytes && detectFormat(b) === "png") {
|
|
1600
|
+
rawBefore = await decodeRawProfiles(b);
|
|
1601
|
+
if (options.gps && !options.all) {
|
|
1602
|
+
for (const a of rawBefore.values()) {
|
|
1603
|
+
if (!a.ok) continue;
|
|
1604
|
+
const errs = new Errors();
|
|
1605
|
+
const copy = { ...a, inner: a.inner.slice() };
|
|
1606
|
+
const r = scrubInner(copy, errs);
|
|
1607
|
+
if (r.changed) a.replacement = await rawProfileChunk(copy);
|
|
1608
|
+
else if (r.why) a.why = r.why; // the EXIF's GPS data was refused, as for a file's own EXIF
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
const stage = editStage1(b, options, rawBefore);
|
|
1613
|
+
if (stage.ok === false) return stage;
|
|
1614
|
+
const rawAfter = rawBefore ? await decodeRawProfiles(stage.out.bytes) : undefined;
|
|
1615
|
+
return editStage2(stage, inspectBytes(stage.out.bytes, rawAfter));
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
function editStage1(b, { gps = false, all = false, icc = "keep", set } = {}, raw) {
|
|
1619
|
+
if (!gps && !all && (set === undefined || set === null)) return refuse("unsupported", "nothing to remove: ask for the location (gps) or all metadata, or give the fields to set");
|
|
1620
|
+
if (all && set !== undefined && set !== null) return refuse("unsupported", "set can't be combined with all: removing all metadata leaves no EXIF to edit");
|
|
1621
|
+
const fields = set === undefined || set === null ? undefined : validateSet(set);
|
|
1622
|
+
if (fields?.problem) return refuse("unsupported", fields.problem);
|
|
1623
|
+
const before = inspectBytes(b, raw);
|
|
1624
|
+
if (!before.ok) return before;
|
|
1625
|
+
const errors = new Errors();
|
|
1626
|
+
const removed = [];
|
|
1627
|
+
const warnings = [...before.warnings];
|
|
1628
|
+
const unsupported = [...before.unsupported];
|
|
1629
|
+
let out = { bytes: b };
|
|
1630
|
+
const note = (label) => removed.includes(label) || removed.push(label);
|
|
1631
|
+
if (gps || all) {
|
|
1632
|
+
if (before.format === "jpeg") out = editJpeg(b, { gps, all, icc }, { note, warnings, errors });
|
|
1633
|
+
else if (before.format === "png") out = editPng(b, { gps, all, icc }, { note, warnings, errors, raw });
|
|
1634
|
+
else out = editWebp(b, { gps, all, icc }, { note, warnings, errors });
|
|
1635
|
+
if (out.ok === false) return out;
|
|
1636
|
+
}
|
|
1637
|
+
let setNames;
|
|
1638
|
+
if (fields) {
|
|
1639
|
+
const r = applySet(out.bytes, before.format, fields.list, errors);
|
|
1640
|
+
if (r.ok === false) return r;
|
|
1641
|
+
out = { bytes: r.bytes };
|
|
1642
|
+
setNames = fields.list.map((f) => f.key);
|
|
1643
|
+
if (r.changed) for (const f of fields.list) for (const name of XMP_OF[f.key] ?? []) if (before.$personalMetadata.xmp.some((x) => x.name === name)) warnings.push(`the XMP also holds ${f.key} (${name}); XMP is not edited, so it still says what it did`);
|
|
1644
|
+
}
|
|
1645
|
+
return { b, gps, all, icc, before, errors, removed, warnings, unsupported, out, note, set: setNames };
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
function editStage2({ b, gps, all, icc, before, errors, removed, warnings, unsupported, out, note, set }, after) {
|
|
1649
|
+
const changed = out.bytes !== b && (out.bytes.length !== b.length || out.bytes.some((v, i) => v !== b[i]));
|
|
1650
|
+
const iptcUnread = after.ok && after.unsupported.some((u) => /^IPTC: .*not read/.test(u));
|
|
1651
|
+
if (gps && !all && after.ok && after.has.location) {
|
|
1652
|
+
const where = [after.has.xmpGps && "XMP", after.has.makerNoteLocation && "a MakerNote", after.has.iptcLocation && "IPTC", after.has.textLocation && "text entries", after.has.rawProfileLocation && "a PNG raw profile"].filter(Boolean);
|
|
1653
|
+
warnings.push(`the location is still in the file${where.length ? ` (${where.join(", ")})` : ""}: it could not be removed safely`);
|
|
1654
|
+
}
|
|
1655
|
+
if (gps && before.has.location && !["in IPTC", "in text", "in PNG raw profile", "in MakerNote"].includes(before.has.location) && after.ok && !after.has.location) note("location (GPS)");
|
|
1656
|
+
if (gps && before.has.xmpGps && after.ok && !after.has.xmpGps) note("location in XMP");
|
|
1657
|
+
if (gps && before.has.iptcLocation && after.ok && !after.has.iptcLocation) note("location in IPTC");
|
|
1658
|
+
if (gps && before.has.textLocation && after.ok && !after.has.textLocation) note("text entries naming a location");
|
|
1659
|
+
if (gps && before.has.rawProfileLocation && after.ok && !after.has.rawProfileLocation) note("location in PNG raw profile");
|
|
1660
|
+
if (gps && before.has.makerNoteLocation && after.ok && !after.has.makerNoteLocation) note("location in MakerNote");
|
|
1661
|
+
if (gps && !all && after.ok && after.has.rawProfileUndecoded) warnings.push(`${after.has.rawProfileUndecoded === 1 ? "a PNG \"Raw profile\" text entry is" : `${after.has.rawProfileUndecoded} PNG "Raw profile" text entries are`} present and was not decoded: a location inside ${after.has.rawProfileUndecoded === 1 ? "it is" : "them is"} not removed`);
|
|
1662
|
+
if (gps && !all && iptcUnread) warnings.push("part of an IPTC block was not read, so a place name in the part after the problem is not removed");
|
|
1663
|
+
if (gps && !all && !before.has.location) warnings.push(`no location was found in this file${after.ok && (after.has.rawProfileUndecoded || iptcUnread) ? ", in the parts that could be read" : ""}`);
|
|
1664
|
+
const kept = [];
|
|
1665
|
+
if (!all) {
|
|
1666
|
+
if (after.ok && after.has.exif) kept.push("the other EXIF fields");
|
|
1667
|
+
if (after.ok && after.has.xmp) kept.push("the other XMP properties");
|
|
1668
|
+
if (after.ok && after.has.iptc) kept.push("IPTC");
|
|
1669
|
+
if (after.ok && after.has.text) kept.push("text entries");
|
|
1670
|
+
if (after.ok && after.has.contentCredentials) kept.push("Content Credentials (their signature no longer verifies)");
|
|
1671
|
+
}
|
|
1672
|
+
if (after.ok && after.has.icc && icc === "keep") kept.push("the color profile");
|
|
1673
|
+
if (all && after.ok && after.has.exif) warnings.push("some EXIF could not be removed");
|
|
1674
|
+
if (changed && before.has.contentCredentials && !all) warnings.push("Content Credentials were kept but the edit changed the bytes they sign, so they no longer verify");
|
|
1675
|
+
for (const e of errors.out()) warnings.push(e);
|
|
1676
|
+
return { ok: true, bytes: out.bytes, changed, removed, kept, ...(set ? { set } : {}), unsupported: all ? unsupported.filter((u) => !/IPTC|MakerNote|extended XMP|follow/.test(u)) : unsupported, warnings, pixels: "unchanged" };
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
// ── metadata-only field edits ────────────────────────────────────────────────
|
|
1680
|
+
// edit(bytes, { set: { artist, copyright, description, software, make, model, orientation } }) rewrites those EXIF fields and
|
|
1681
|
+
// nothing else: the EXIF block is rebuilt around a new IFD0 (every other entry, value and IFD stays where it is, the old
|
|
1682
|
+
// values of the fields it replaced are zeroed), then put back where the old one was. The compressed image is copied byte
|
|
1683
|
+
// for byte. XMP is not edited; the result names an XMP property that still says the old thing.
|
|
1684
|
+
|
|
1685
|
+
const SET_FIELDS = { artist: 0x013b, copyright: 0x8298, description: 0x010e, software: 0x0131, make: 0x010f, model: 0x0110, orientation: 0x0112 };
|
|
1686
|
+
const XMP_OF = { artist: ["dc:creator", "tiff:Artist"], copyright: ["dc:rights", "tiff:Copyright"], description: ["dc:description", "tiff:ImageDescription"], software: ["xmp:CreatorTool", "tiff:Software"], make: ["tiff:Make"], model: ["tiff:Model"], orientation: ["tiff:Orientation"] };
|
|
1687
|
+
|
|
1688
|
+
/** `{ list: [{ key, tag, remove?, text?, number? }] }` for a `set` object, or `{ problem }`. */
|
|
1689
|
+
function validateSet(set) {
|
|
1690
|
+
const keys = set && typeof set === "object" && !Array.isArray(set) ? Object.keys(set).filter((k) => set[k] !== undefined) : [];
|
|
1691
|
+
if (!keys.length) return { problem: "nothing to set: give at least one field (artist, copyright, description, software, make, model, orientation)" };
|
|
1692
|
+
const list = [];
|
|
1693
|
+
for (const key of keys) {
|
|
1694
|
+
if (!Object.hasOwn(SET_FIELDS, key)) return { problem: `set has no field "${clip(key, 40)}": it edits artist, copyright, description, software, make, model, orientation` };
|
|
1695
|
+
const v = set[key];
|
|
1696
|
+
const tag = SET_FIELDS[key];
|
|
1697
|
+
if (v === null || v === "") list.push({ key, tag, remove: true });
|
|
1698
|
+
else if (key === "orientation") {
|
|
1699
|
+
if (!Number.isInteger(v) || v < 1 || v > 8) return { problem: "orientation must be a whole number from 1 to 8 (or null to remove it)" };
|
|
1700
|
+
list.push({ key, tag, number: v });
|
|
1701
|
+
} else if (typeof v !== "string") return { problem: `${key} must be text (or null to remove it)` };
|
|
1702
|
+
else if (/[\u0000-\u001f\u007f]/.test(v)) return { problem: `${key} can't hold control characters` };
|
|
1703
|
+
else {
|
|
1704
|
+
const bytes = new TextEncoder().encode(v);
|
|
1705
|
+
if (bytes.length > 255) return { problem: `${key} is at most 255 bytes (this is ${bytes.length})` };
|
|
1706
|
+
list.push({ key, tag, text: bytes });
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
return { list };
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
/** The EXIF payload of `b` and what holds it: `{ tiff, kind, ... }` or undefined. */
|
|
1713
|
+
function findExif(b, format, errors) {
|
|
1714
|
+
if (format === "jpeg") {
|
|
1715
|
+
for (const seg of parseJpeg(b, errors).segments) if (jpegKind(b, seg) === "exif") return { kind: "jpeg", seg, tiff: b.slice(seg.data + 6, seg.data + seg.size) };
|
|
1716
|
+
} else if (format === "png") {
|
|
1717
|
+
for (const c of parsePng(b, errors).chunks) if (c.type === "eXIf") return { kind: "png", chunk: c, tiff: b.slice(c.data, c.data + c.size) };
|
|
1718
|
+
} else {
|
|
1719
|
+
const w = parseWebp(b, errors);
|
|
1720
|
+
for (const c of w.chunks) if (c.type === "EXIF") return { kind: "webp", chunks: w.chunks, chunk: c, prefixed: startsWith(b, c.data, EXIF_HEAD), tiff: exifPayload(b, c).slice() };
|
|
1721
|
+
}
|
|
1722
|
+
return undefined;
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
/** The text of one TIFF entry value's bytes, for comparing a field with what it would be. */
|
|
1726
|
+
const sameBytes = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
|
|
1727
|
+
|
|
1728
|
+
function entryBytes(f, le) {
|
|
1729
|
+
if (f.number !== undefined) return { type: T_SHORT, count: 1, bytes: Uint8Array.from(le ? [f.number, 0] : [0, f.number]) };
|
|
1730
|
+
const bytes = new Uint8Array(f.text.length + 1);
|
|
1731
|
+
bytes.set(f.text);
|
|
1732
|
+
return { type: T_ASCII, count: bytes.length, bytes };
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
/** A new TIFF block (little-endian) holding only these fields. */
|
|
1736
|
+
function buildTiff(fields) {
|
|
1737
|
+
const entries = fields.filter((f) => !f.remove).sort((a, b) => a.tag - b.tag);
|
|
1738
|
+
const head = 8 + 2 + entries.length * 12 + 4;
|
|
1739
|
+
const table = new Uint8Array(head);
|
|
1740
|
+
table.set([0x49, 0x49, 42, 0, 8, 0, 0, 0, entries.length & 255, entries.length >> 8]);
|
|
1741
|
+
const data = [];
|
|
1742
|
+
let used = 0;
|
|
1743
|
+
entries.forEach((f, i) => {
|
|
1744
|
+
const v = entryBytes(f, true);
|
|
1745
|
+
const at = 10 + i * 12;
|
|
1746
|
+
table[at] = f.tag & 255;
|
|
1747
|
+
table[at + 1] = f.tag >> 8;
|
|
1748
|
+
table[at + 2] = v.type;
|
|
1749
|
+
put32le(table, at + 4, v.count);
|
|
1750
|
+
if (v.bytes.length <= 4) table.set(v.bytes, at + 8);
|
|
1751
|
+
else {
|
|
1752
|
+
put32le(table, at + 8, head + used);
|
|
1753
|
+
data.push(v.bytes);
|
|
1754
|
+
used += v.bytes.length + (v.bytes.length & 1);
|
|
1755
|
+
if (v.bytes.length & 1) data.push(new Uint8Array(1));
|
|
1756
|
+
}
|
|
1757
|
+
});
|
|
1758
|
+
return concat([table, ...data]);
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
/**
|
|
1762
|
+
* `t` (an EXIF TIFF block, copied by the caller) with these fields set, removed or added in IFD0: a new IFD0 and its values
|
|
1763
|
+
* are appended and the header points at it; the old IFD0 and the old values of the fields it replaced are zeroed unless
|
|
1764
|
+
* something else shares those bytes. `{ ok, bytes, changed }` or `{ ok: false, why }`.
|
|
1765
|
+
*/
|
|
1766
|
+
function setFieldsInTiff(t, fields, errors) {
|
|
1767
|
+
const walk = walkTiff(t, errors);
|
|
1768
|
+
const ifd0 = walk.ok ? walk.ifds.find((i) => i.name === "ifd0") : undefined;
|
|
1769
|
+
if (!ifd0) return { ok: false, why: "the block can't be read" };
|
|
1770
|
+
const le = walk.le;
|
|
1771
|
+
const w16 = (n) => (le ? [n & 255, n >> 8] : [n >> 8, n & 255]);
|
|
1772
|
+
const w32 = (n) => (le ? [n & 255, (n >> 8) & 255, (n >> 16) & 255, (n >>> 24) & 255] : [(n >>> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255]);
|
|
1773
|
+
const entries = ifd0.entries.map((e) => ({ tag: e.tag, e, raw: t.slice(e.pos, e.pos + 12) }));
|
|
1774
|
+
const zero = [];
|
|
1775
|
+
let changed = false;
|
|
1776
|
+
for (const f of fields) {
|
|
1777
|
+
const at = entries.findIndex((x) => x.tag === f.tag);
|
|
1778
|
+
const old = at < 0 ? undefined : entries[at];
|
|
1779
|
+
if (f.remove) {
|
|
1780
|
+
if (old) (entries.splice(at, 1), (changed = true), old.e.size > 4 && !old.e.problem && zero.push([old.e.valuePos, old.e.valuePos + old.e.size]));
|
|
1781
|
+
continue;
|
|
1782
|
+
}
|
|
1783
|
+
const v = entryBytes(f, le);
|
|
1784
|
+
if (old && !old.e.problem && old.e.type === v.type && old.e.count === v.count && sameBytes(t.subarray(old.e.valuePos, old.e.valuePos + old.e.size), v.bytes)) continue;
|
|
1785
|
+
const fresh = { tag: f.tag, value: v, raw: null };
|
|
1786
|
+
if (old) (entries.splice(at, 1, fresh), old.e.size > 4 && !old.e.problem && zero.push([old.e.valuePos, old.e.valuePos + old.e.size]));
|
|
1787
|
+
else entries.push(fresh);
|
|
1788
|
+
changed = true;
|
|
1789
|
+
}
|
|
1790
|
+
if (!changed) return { ok: true, bytes: t, changed: false };
|
|
1791
|
+
entries.sort((a, b) => a.tag - b.tag);
|
|
1792
|
+
const base = t.length + (t.length & 1);
|
|
1793
|
+
const ifdSize = 2 + entries.length * 12 + 4;
|
|
1794
|
+
const table = new Uint8Array(ifdSize);
|
|
1795
|
+
table.set(w16(entries.length), 0);
|
|
1796
|
+
const data = [];
|
|
1797
|
+
let used = 0;
|
|
1798
|
+
entries.forEach((x, i) => {
|
|
1799
|
+
const at = 2 + i * 12;
|
|
1800
|
+
if (x.raw) return table.set(x.raw, at);
|
|
1801
|
+
const v = x.value;
|
|
1802
|
+
table.set([...w16(x.tag), ...w16(v.type), ...w32(v.count)], at);
|
|
1803
|
+
if (v.bytes.length <= 4) table.set(v.bytes, at + 8);
|
|
1804
|
+
else {
|
|
1805
|
+
table.set(w32(base + ifdSize + used), at + 8);
|
|
1806
|
+
data.push(v.bytes);
|
|
1807
|
+
used += v.bytes.length + (v.bytes.length & 1);
|
|
1808
|
+
if (v.bytes.length & 1) data.push(new Uint8Array(1));
|
|
1809
|
+
}
|
|
1810
|
+
});
|
|
1811
|
+
table.set(w32(ifd0.next), ifdSize - 4);
|
|
1812
|
+
// the bytes nothing else uses: zero them so a replaced or removed value is gone, not just unlinked
|
|
1813
|
+
const kept = new Set(entries.filter((x) => x.raw).map((x) => x.e));
|
|
1814
|
+
const others = [];
|
|
1815
|
+
for (const ifd of walk.ifds) {
|
|
1816
|
+
if (ifd !== ifd0) others.push([ifd.at, ifd.end]);
|
|
1817
|
+
for (const e of ifd.entries) if (!e.problem && e.size > 4 && (ifd !== ifd0 || kept.has(e))) others.push([e.valuePos, e.valuePos + e.size]);
|
|
1818
|
+
}
|
|
1819
|
+
const thumbOff = findEntry(walk, "ifd1", 0x0201);
|
|
1820
|
+
const thumbLen = findEntry(walk, "ifd1", 0x0202);
|
|
1821
|
+
if (thumbOff && thumbLen) {
|
|
1822
|
+
const r32 = (at) => (le ? le32(t, at) : be32(t, at));
|
|
1823
|
+
others.push([r32(thumbOff.valuePos), r32(thumbOff.valuePos) + r32(thumbLen.valuePos)]);
|
|
1824
|
+
}
|
|
1825
|
+
const free = (a, z) => !others.some(([c, d]) => a < d && c < z);
|
|
1826
|
+
const out = new Uint8Array(base + ifdSize + used);
|
|
1827
|
+
out.set(t, 0);
|
|
1828
|
+
for (const [a, z] of [[ifd0.at, ifd0.end], ...zero]) if (a >= 8 && z <= t.length && free(a, z)) out.fill(0, a, z);
|
|
1829
|
+
out.set(table, base);
|
|
1830
|
+
let at = base + ifdSize;
|
|
1831
|
+
for (const d of data) (out.set(d, at), (at += d.length));
|
|
1832
|
+
out.set(w32(base), 4);
|
|
1833
|
+
return { ok: true, bytes: out, changed: true };
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
/** `b` with the fields set in its EXIF (made if it has none). `{ bytes, changed }` or a refusal; the pixels are never touched. */
|
|
1837
|
+
function applySet(b, format, fields, errors) {
|
|
1838
|
+
const found = findExif(b, format, errors);
|
|
1839
|
+
let tiffOut;
|
|
1840
|
+
if (found) {
|
|
1841
|
+
const r = setFieldsInTiff(found.tiff, fields, errors);
|
|
1842
|
+
if (!r.ok) return refuse("malformed", `its EXIF block can't be edited safely (${r.why}); the image is unchanged`);
|
|
1843
|
+
if (!r.changed) return { bytes: b, changed: false };
|
|
1844
|
+
tiffOut = r.bytes;
|
|
1845
|
+
} else {
|
|
1846
|
+
if (fields.every((f) => f.remove)) return { bytes: b, changed: false };
|
|
1847
|
+
tiffOut = buildTiff(fields);
|
|
1848
|
+
}
|
|
1849
|
+
if (format === "jpeg" && tiffOut.length > LIMITS.exifBytes) return refuse("unsupported", `the EXIF block would be ${tiffOut.length} bytes, more than a JPEG holds (${LIMITS.exifBytes}); the image is unchanged`);
|
|
1850
|
+
if (!found) {
|
|
1851
|
+
const out = embed(b, { exif: tiffOut });
|
|
1852
|
+
return { bytes: out, changed: out !== b };
|
|
1853
|
+
}
|
|
1854
|
+
if (found.kind === "jpeg") return { bytes: concat([b.subarray(0, found.seg.start), app1(EXIF_HEAD, tiffOut), b.subarray(found.seg.end)]), changed: true };
|
|
1855
|
+
if (found.kind === "png") return { bytes: concat([b.subarray(0, found.chunk.start), pngChunk("eXIf", tiffOut), b.subarray(found.chunk.end)]), changed: true };
|
|
1856
|
+
const chunks = found.chunks.map((c) => (c === found.chunk ? { ...c, bytes: found.prefixed ? concat([fromLatin1(EXIF_HEAD), tiffOut]) : tiffOut } : c));
|
|
1857
|
+
return { bytes: buildWebp(b, chunks), changed: true };
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
function editJpeg(b, { gps, all, icc }, { note, warnings, errors }) {
|
|
1861
|
+
const j = parseJpeg(b, errors);
|
|
1862
|
+
if (j.sos < 0) return refuse("malformed", "this JPEG has no image data to keep; it is unchanged");
|
|
1863
|
+
const parts = [b.subarray(0, 2)];
|
|
1864
|
+
for (const seg of j.segments) {
|
|
1865
|
+
if (seg.start >= j.sos) break;
|
|
1866
|
+
const kind = jpegKind(b, seg);
|
|
1867
|
+
const whole = b.subarray(seg.start, seg.end);
|
|
1868
|
+
if (all) {
|
|
1869
|
+
const drop = { exif: "EXIF", xmp: "XMP", "xmp-extension": "XMP", iptc: "IPTC", comment: "comments", c2pa: "Content Credentials", app: "other application data" }[kind] ?? (kind === "icc" && icc === "strip" ? "color profile" : undefined);
|
|
1870
|
+
if (drop) note(drop);
|
|
1871
|
+
else parts.push(whole);
|
|
1872
|
+
continue;
|
|
1873
|
+
}
|
|
1874
|
+
if (gps && kind === "exif") {
|
|
1875
|
+
const copy = b.slice(seg.start, seg.end);
|
|
1876
|
+
const r = removeGpsFromTiff(copy.subarray(seg.data - seg.start + 6), errors);
|
|
1877
|
+
if (r.why) warnings.push(`EXIF: ${r.why}`);
|
|
1878
|
+
parts.push(copy);
|
|
1879
|
+
} else if (gps && kind === "xmp") {
|
|
1880
|
+
const copy = b.slice(seg.start, seg.end);
|
|
1881
|
+
const r = blankXmpGps(copy.subarray(seg.data - seg.start + XMP_HEAD.length));
|
|
1882
|
+
copy.set(r.bytes, seg.data - seg.start + XMP_HEAD.length);
|
|
1883
|
+
parts.push(copy);
|
|
1884
|
+
} else if (gps && kind === "iptc") {
|
|
1885
|
+
// the place datasets are blanked to spaces in place: same length, every other dataset untouched
|
|
1886
|
+
const copy = b.slice(seg.start, seg.end);
|
|
1887
|
+
blankIptcPlaces(copy, readIptc(b, seg, errors), seg.start);
|
|
1888
|
+
parts.push(copy);
|
|
1889
|
+
} else parts.push(whole);
|
|
1890
|
+
}
|
|
1891
|
+
const tail = all && j.eoi > 0 ? b.subarray(j.sos, j.eoi) : b.subarray(j.sos);
|
|
1892
|
+
if (all && j.eoi > 0 && j.eoi < b.length) note("data after the image end");
|
|
1893
|
+
parts.push(tail);
|
|
1894
|
+
return { bytes: concat(parts) };
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
function pngChunk(type, data) {
|
|
1898
|
+
const out = new Uint8Array(12 + data.length);
|
|
1899
|
+
put32be(out, 0, data.length);
|
|
1900
|
+
out.set(fromLatin1(type), 4);
|
|
1901
|
+
out.set(data, 8);
|
|
1902
|
+
put32be(out, 8 + data.length, crc32(out.subarray(4, 8 + data.length)));
|
|
1903
|
+
return out;
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
function editPng(b, { gps, all, icc }, { note, warnings, errors, raw }) {
|
|
1907
|
+
const p = parsePng(b, errors);
|
|
1908
|
+
if (!p.iend) return refuse("malformed", "this PNG is cut short or damaged; it is unchanged");
|
|
1909
|
+
const parts = [b.subarray(0, 8)];
|
|
1910
|
+
for (const c of p.chunks) {
|
|
1911
|
+
const whole = b.subarray(c.start, c.end);
|
|
1912
|
+
if (all) {
|
|
1913
|
+
if (c.type === "eXIf") note("EXIF");
|
|
1914
|
+
else if (c.type === "tEXt" || c.type === "zTXt" || c.type === "iTXt") note("text entries (including XMP)");
|
|
1915
|
+
else if (c.type === "tIME") note("modification time");
|
|
1916
|
+
else if (c.type === "caBX") note("Content Credentials");
|
|
1917
|
+
else if (c.type === "iCCP" && icc === "strip") note("color profile");
|
|
1918
|
+
else if (c.type !== "iCCP" && (c.type.charCodeAt(0) & 0x20) && !PNG_KEEP.has(c.type)) note("other ancillary chunks");
|
|
1919
|
+
else parts.push(whole);
|
|
1920
|
+
continue;
|
|
1921
|
+
}
|
|
1922
|
+
if (gps && c.type === "eXIf") {
|
|
1923
|
+
const data = b.slice(c.data, c.data + c.size);
|
|
1924
|
+
const r = removeGpsFromTiff(data, errors);
|
|
1925
|
+
if (r.why) warnings.push(`EXIF: ${r.why}`);
|
|
1926
|
+
parts.push(pngChunk("eXIf", data));
|
|
1927
|
+
} else if (gps && c.type === "iTXt" && pngText(b, c)?.keyword === "XML:com.adobe.xmp") {
|
|
1928
|
+
const data = b.slice(c.data, c.data + c.size);
|
|
1929
|
+
const r = blankXmpGps(data);
|
|
1930
|
+
parts.push(pngChunk("iTXt", r.bytes));
|
|
1931
|
+
} else if (gps && raw?.get(c.start)?.replacement) {
|
|
1932
|
+
parts.push(raw.get(c.start).replacement); // a raw profile with its location blanked, in the same kind of chunk
|
|
1933
|
+
} else if (gps && raw?.get(c.start)?.why) {
|
|
1934
|
+
warnings.push(`EXIF in a PNG raw profile: ${raw.get(c.start).why}`);
|
|
1935
|
+
parts.push(whole);
|
|
1936
|
+
} else if (gps && (c.type === "tEXt" || c.type === "zTXt" || c.type === "iTXt") && pngText(b, c) && namesLocation(pngText(b, c))) {
|
|
1937
|
+
note("text entries naming a location"); // dropped whole: a text value can't be blanked without changing what the chunk says
|
|
1938
|
+
} else parts.push(whole);
|
|
1939
|
+
}
|
|
1940
|
+
return { bytes: concat(parts) };
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
/** A WebP from chunks, with the RIFF size and VP8X flags set to match. */
|
|
1944
|
+
function buildWebp(b, chunks, flagsOff = 0, flagsOn = 0) {
|
|
1945
|
+
const body = [];
|
|
1946
|
+
for (const c of chunks) {
|
|
1947
|
+
const data = c.bytes ?? b.subarray(c.data, c.data + c.size);
|
|
1948
|
+
const head = new Uint8Array(8);
|
|
1949
|
+
head.set(fromLatin1(c.type), 0);
|
|
1950
|
+
put32le(head, 4, data.length);
|
|
1951
|
+
body.push(head, data);
|
|
1952
|
+
if (data.length & 1) body.push(new Uint8Array(1));
|
|
1953
|
+
}
|
|
1954
|
+
const inner = concat(body);
|
|
1955
|
+
const out = new Uint8Array(12 + inner.length);
|
|
1956
|
+
out.set(fromLatin1("RIFF"), 0);
|
|
1957
|
+
put32le(out, 4, 4 + inner.length);
|
|
1958
|
+
out.set(fromLatin1("WEBP"), 8);
|
|
1959
|
+
out.set(inner, 12);
|
|
1960
|
+
const first = chunks[0];
|
|
1961
|
+
if (first?.type === "VP8X") out[20] = (out[20] & ~flagsOff) | flagsOn;
|
|
1962
|
+
return out;
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
function editWebp(b, { gps, all, icc }, { note, warnings, errors }) {
|
|
1966
|
+
const w = parseWebp(b, errors);
|
|
1967
|
+
if (!w.chunks.length) return refuse("malformed", "this WebP has no chunks; it is unchanged");
|
|
1968
|
+
let flagsOff = 0;
|
|
1969
|
+
const chunks = [];
|
|
1970
|
+
for (const c of w.chunks) {
|
|
1971
|
+
if (all) {
|
|
1972
|
+
if (c.type === "EXIF") (note("EXIF"), (flagsOff |= 0x08));
|
|
1973
|
+
else if (c.type === "XMP ") (note("XMP"), (flagsOff |= 0x04));
|
|
1974
|
+
else if (c.type === "C2PA") note("Content Credentials");
|
|
1975
|
+
else if (c.type === "ICCP" && icc === "strip") (note("color profile"), (flagsOff |= 0x20));
|
|
1976
|
+
else chunks.push(c);
|
|
1977
|
+
continue;
|
|
1978
|
+
}
|
|
1979
|
+
if (gps && c.type === "EXIF") {
|
|
1980
|
+
const data = b.slice(c.data, c.data + c.size);
|
|
1981
|
+
const from = startsWith(data, 0, EXIF_HEAD) ? 6 : 0;
|
|
1982
|
+
const r = removeGpsFromTiff(data.subarray(from), errors);
|
|
1983
|
+
if (r.why) warnings.push(`EXIF: ${r.why}`);
|
|
1984
|
+
chunks.push({ ...c, bytes: data });
|
|
1985
|
+
} else if (gps && c.type === "XMP ") {
|
|
1986
|
+
chunks.push({ ...c, bytes: blankXmpGps(b.subarray(c.data, c.data + c.size)).bytes });
|
|
1987
|
+
} else chunks.push(c);
|
|
1988
|
+
}
|
|
1989
|
+
if (!all && !gps) return { bytes: b };
|
|
1990
|
+
return { bytes: buildWebp(b, chunks, flagsOff) };
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
// ── routing by metadata ──────────────────────────────────────────────────────
|
|
1994
|
+
|
|
1995
|
+
// A routing rule's `matches` pattern runs on the linear-time matcher (src/model/safe-regex.js). This module imports nothing (it is a sandbox module), so the sandbox's
|
|
1996
|
+
// prelude (src/runtime/worker/00-prelude.js) hands the matcher in; the Node tests do the same.
|
|
1997
|
+
let safeRegex = null;
|
|
1998
|
+
/** The matcher module (src/model/safe-regex.js's exports) that routeByMetadata's `matches` conditions use. */
|
|
1999
|
+
export function bindSafeRegex(lib) {
|
|
2000
|
+
safeRegex = lib;
|
|
2001
|
+
}
|
|
2002
|
+
const ROUTE_LIMITS = { rules: 64, regex: 100, name: 64 };
|
|
2003
|
+
const ROUTE_TEXT_FIELDS = { make: "Make", model: "Model", software: "Software", artist: "Artist", copyright: "Copyright", description: "ImageDescription" };
|
|
2004
|
+
const ROUTE_HAS = new Set(["exif", "xmp", "icc", "iptc", "text", "contentCredentials", "makerNote", "thumbnail"]);
|
|
2005
|
+
const ROUTE_CONDITIONS = new Set(["format", "orientation", "upright", "location", "has", "animated", "taken", "width", "height", ...Object.keys(ROUTE_TEXT_FIELDS)]);
|
|
2006
|
+
const DATE_RULE = /^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2})(?::(\d{2}))?)?$/;
|
|
2007
|
+
|
|
2008
|
+
const asList = (v) => (Array.isArray(v) ? v : [v]);
|
|
2009
|
+
|
|
2010
|
+
/** A date rule ("2026-10-01", "2026-10-01T09:30") as the sortable text "2026-10-01T09:30:00", or undefined. */
|
|
2011
|
+
const ruleDate = (v) => {
|
|
2012
|
+
const m = typeof v === "string" ? DATE_RULE.exec(v) : null;
|
|
2013
|
+
return m ? `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}` : undefined;
|
|
2014
|
+
};
|
|
2015
|
+
|
|
2016
|
+
/** One rule's `when` as a function of a report; throws a TypeError naming the rule and the condition. */
|
|
2017
|
+
function compileWhen(when, i) {
|
|
2018
|
+
const bad = (message) => new TypeError(`routeByMetadata rule ${i}: ${message}`);
|
|
2019
|
+
if (when === undefined || when === null) return () => true;
|
|
2020
|
+
if (typeof when !== "object" || Array.isArray(when)) throw bad("when must be an object of conditions");
|
|
2021
|
+
const tests = [];
|
|
2022
|
+
for (const [key, want] of Object.entries(when)) {
|
|
2023
|
+
if (want === undefined) continue;
|
|
2024
|
+
if (!ROUTE_CONDITIONS.has(key)) throw bad(`unknown condition "${clip(key, 40)}" (known: ${[...ROUTE_CONDITIONS].join(", ")})`);
|
|
2025
|
+
if (key === "format") tests.push((r) => asList(want).includes(r.format));
|
|
2026
|
+
else if (key === "orientation") tests.push((r) => r.orientation !== undefined && asList(want).includes(r.orientation));
|
|
2027
|
+
else if (key === "upright") tests.push((r) => ((r.orientation ?? 1) === 1) === Boolean(want));
|
|
2028
|
+
else if (key === "location") tests.push((r) => Boolean(r.has?.location) === Boolean(want));
|
|
2029
|
+
else if (key === "animated") tests.push((r) => Boolean(r.has?.animated ?? r.animated) === Boolean(want));
|
|
2030
|
+
else if (key === "has") {
|
|
2031
|
+
for (const name of asList(want)) if (!ROUTE_HAS.has(name)) throw bad(`has: unknown part "${clip(String(name), 40)}" (known: ${[...ROUTE_HAS].join(", ")})`);
|
|
2032
|
+
tests.push((r) => asList(want).every((name) => Boolean(r.has?.[name])));
|
|
2033
|
+
} else if (key === "width" || key === "height") {
|
|
2034
|
+
if (!want || typeof want !== "object") throw bad(`${key} must be { min?, max? }`);
|
|
2035
|
+
tests.push((r) => typeof r[key] === "number" && (want.min === undefined || r[key] >= want.min) && (want.max === undefined || r[key] <= want.max));
|
|
2036
|
+
} else if (key === "taken") {
|
|
2037
|
+
const after = want?.after === undefined ? undefined : ruleDate(want.after);
|
|
2038
|
+
const before = want?.before === undefined ? undefined : ruleDate(want.before);
|
|
2039
|
+
if (!want || typeof want !== "object" || (want.after !== undefined && !after) || (want.before !== undefined && !before)) throw bad("taken must be { after?, before? } with dates like 2026-10-01 or 2026-10-01T09:30");
|
|
2040
|
+
tests.push((r) => {
|
|
2041
|
+
const exif = r.$personalMetadata?.exif ?? [];
|
|
2042
|
+
const raw = (exif.find((e) => e.tag === "DateTimeOriginal") ?? exif.find((e) => e.tag === "DateTime"))?.value;
|
|
2043
|
+
const m = typeof raw === "string" ? /^(\d{4}):(\d{2}):(\d{2}) (\d{2}:\d{2}:\d{2})/.exec(raw) : null;
|
|
2044
|
+
if (!m) return false;
|
|
2045
|
+
const at = `${m[1]}-${m[2]}-${m[3]}T${m[4]}`;
|
|
2046
|
+
return (after === undefined || at >= after) && (before === undefined || at < before);
|
|
2047
|
+
});
|
|
2048
|
+
} else {
|
|
2049
|
+
const tag = ROUTE_TEXT_FIELDS[key];
|
|
2050
|
+
let match;
|
|
2051
|
+
if (typeof want === "string") match = (v) => v.trim().toLowerCase() === want.trim().toLowerCase();
|
|
2052
|
+
else if (want && typeof want.contains === "string") match = (v) => v.toLowerCase().includes(want.contains.toLowerCase());
|
|
2053
|
+
else if (want && typeof want.matches === "string") {
|
|
2054
|
+
if (want.matches.length > ROUTE_LIMITS.regex) throw bad(`${key}: a pattern is at most ${ROUTE_LIMITS.regex} characters`);
|
|
2055
|
+
// The pattern is a rule author's text: it runs on the linear-time matcher (src/model/safe-regex.js), never on RegExp. One outside the supported subset is
|
|
2056
|
+
// refused here with the matcher's reason. A field it can't be tested on (over the length limit, or too costly) does not satisfy the condition: the rule
|
|
2057
|
+
// doesn't fire for that image, and it can't be mistaken for a match.
|
|
2058
|
+
if (!safeRegex) throw bad(`${key}: "matches" can't be checked: no safe pattern matcher is installed`);
|
|
2059
|
+
const re = safeRegex.compileSafeRegex(want.matches, { ignoreCase: true });
|
|
2060
|
+
if (!re.ok) throw bad(`${key}: "matches" is not a regular expression this rule can run safely (${re.error})`);
|
|
2061
|
+
match = (v) => re.check(v) === "match";
|
|
2062
|
+
} else throw bad(`${key} must be text, { contains } or { matches }`);
|
|
2063
|
+
tests.push((r) => {
|
|
2064
|
+
const v = r.$personalMetadata?.exif?.find((e) => e.tag === tag)?.value;
|
|
2065
|
+
return typeof v === "string" && match(v);
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
return (r) => tests.every((t) => t(r));
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
/**
|
|
2073
|
+
* Which route an image takes, by what it says about itself: the first rule whose conditions all hold names the route.
|
|
2074
|
+
* `report` is an inspect()/imageMetadata() result (a refusal that names a format, like a GIF's, routes by what it carries);
|
|
2075
|
+
* `rules` is `[{ route: "name", when: { format, orientation, upright, location, has, animated, make, model, software, artist,
|
|
2076
|
+
* copyright, description, taken: { after, before }, width: { min, max }, height } }]`. Text conditions compare a field
|
|
2077
|
+
* (equal ignoring case, or `{ contains }`, or `{ matches: "regex" }`). The answer is `{ route, rule }` (`rule`: the rule's
|
|
2078
|
+
* index, -1 for none) and holds no metadata value, so what a pane does with it can leave the sandbox. A report that couldn't
|
|
2079
|
+
* be read routes to `unreadable`, no match to `otherwise`. Throws a TypeError naming the rule for a malformed rule list.
|
|
2080
|
+
*/
|
|
2081
|
+
export function routeByMetadata(report, rules, { otherwise = "unmatched", unreadable = "unreadable" } = {}) {
|
|
2082
|
+
if (!Array.isArray(rules)) throw new TypeError("routeByMetadata(report, rules): rules must be an array of { route, when }");
|
|
2083
|
+
if (rules.length > ROUTE_LIMITS.rules) throw new TypeError(`routeByMetadata: at most ${ROUTE_LIMITS.rules} rules`);
|
|
2084
|
+
const compiled = rules.map((rule, i) => {
|
|
2085
|
+
if (!rule || typeof rule !== "object" || typeof rule.route !== "string" || !rule.route || rule.route.length > ROUTE_LIMITS.name) throw new TypeError(`routeByMetadata rule ${i}: route must be a name (text, at most ${ROUTE_LIMITS.name} characters)`);
|
|
2086
|
+
return { route: rule.route, test: compileWhen(rule.when, i) };
|
|
2087
|
+
});
|
|
2088
|
+
const name = (v, fallback) => (typeof v === "string" && v ? v.slice(0, ROUTE_LIMITS.name) : fallback);
|
|
2089
|
+
if (!report || typeof report !== "object" || (report.ok === false && !report.format)) return { route: name(unreadable, "unreadable"), rule: -1 };
|
|
2090
|
+
for (let i = 0; i < compiled.length; i++) if (compiled[i].test(report)) return { route: compiled[i].route, rule: i };
|
|
2091
|
+
return { route: name(otherwise, "unmatched"), rule: -1 };
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
// ── putting metadata into a new file (after a re-encode) ─────────────────────
|
|
2095
|
+
|
|
2096
|
+
/**
|
|
2097
|
+
* The metadata of `source` (an image's bytes) that can travel into a re-encoded
|
|
2098
|
+
* picture: its EXIF block with orientation set to 1 (the pixels are upright now),
|
|
2099
|
+
* its pixel dimensions updated, its thumbnail dropped and, with `gps: false`,
|
|
2100
|
+
* its location gone; and its XMP likewise. The color profile is not carried (the
|
|
2101
|
+
* canvas converts to sRGB). Returns `{ exif?: Uint8Array, xmp?: Uint8Array, removed, kept, warnings }`.
|
|
2102
|
+
*/
|
|
2103
|
+
export function carry(source, { gps = true, width, height } = {}) {
|
|
2104
|
+
const errors = new Errors();
|
|
2105
|
+
const format = detectFormat(source);
|
|
2106
|
+
const out = { removed: [], kept: [], warnings: [] };
|
|
2107
|
+
if (!format) return out;
|
|
2108
|
+
let exif;
|
|
2109
|
+
let xmp;
|
|
2110
|
+
if (format === "jpeg") {
|
|
2111
|
+
const j = parseJpeg(source, errors);
|
|
2112
|
+
for (const seg of j.segments) {
|
|
2113
|
+
const kind = jpegKind(source, seg);
|
|
2114
|
+
if (kind === "exif" && !exif) exif = source.slice(seg.data + 6, seg.data + seg.size);
|
|
2115
|
+
else if (kind === "xmp" && !xmp) xmp = source.slice(seg.data + XMP_HEAD.length, seg.data + seg.size);
|
|
2116
|
+
}
|
|
2117
|
+
} else if (format === "png") {
|
|
2118
|
+
const p = parsePng(source, errors);
|
|
2119
|
+
for (const c of p.chunks) {
|
|
2120
|
+
if (c.type === "eXIf" && !exif) exif = source.slice(c.data, c.data + c.size);
|
|
2121
|
+
else if (c.type === "iTXt" && !xmp && pngText(source, c)?.keyword === "XML:com.adobe.xmp") xmp = pngText(source, c).text.slice();
|
|
2122
|
+
}
|
|
2123
|
+
} else {
|
|
2124
|
+
const w = parseWebp(source, errors);
|
|
2125
|
+
for (const c of w.chunks) {
|
|
2126
|
+
if (c.type === "EXIF" && !exif) exif = exifPayload(source, c).slice();
|
|
2127
|
+
else if (c.type === "XMP " && !xmp) xmp = source.slice(c.data, c.data + c.size);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
if (exif) {
|
|
2131
|
+
const dropsGps = !gps;
|
|
2132
|
+
if (dropsGps) {
|
|
2133
|
+
const r = removeGpsFromTiff(exif, errors);
|
|
2134
|
+
if (r.removed) out.removed.push("location (GPS)");
|
|
2135
|
+
else if (r.why) out.warnings.push(`EXIF: ${r.why}`);
|
|
2136
|
+
}
|
|
2137
|
+
setOrientationInTiff(exif, 1, errors);
|
|
2138
|
+
if (width && height) setDimensionsInTiff(exif, width, height, errors);
|
|
2139
|
+
exif = compactTiff(exif, { dropThumbnail: true }, errors);
|
|
2140
|
+
if (exif.length > LIMITS.exifBytes) {
|
|
2141
|
+
out.warnings.push(`the EXIF block is ${exif.length} bytes, more than a JPEG holds (${LIMITS.exifBytes}); it was not kept`);
|
|
2142
|
+
exif = undefined;
|
|
2143
|
+
} else out.kept.push("EXIF (orientation set to 1)");
|
|
2144
|
+
out.removed.push("EXIF thumbnail");
|
|
2145
|
+
}
|
|
2146
|
+
if (xmp) {
|
|
2147
|
+
if (!gps) {
|
|
2148
|
+
const r = blankXmpGps(xmp);
|
|
2149
|
+
xmp = r.bytes;
|
|
2150
|
+
if (r.count) out.removed.push("location in XMP");
|
|
2151
|
+
}
|
|
2152
|
+
xmp = setXmpOrientation(xmp, 1);
|
|
2153
|
+
out.kept.push("XMP");
|
|
2154
|
+
}
|
|
2155
|
+
out.exif = exif;
|
|
2156
|
+
out.xmp = xmp;
|
|
2157
|
+
return out;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
/**
|
|
2161
|
+
* `bytes` (a freshly encoded JPEG, PNG or WebP) with EXIF and XMP added.
|
|
2162
|
+
* @returns {Uint8Array | null} null when the format can't take them
|
|
2163
|
+
*/
|
|
2164
|
+
export function embed(bytes, { exif, xmp, width, height } = {}) {
|
|
2165
|
+
const errors = new Errors();
|
|
2166
|
+
const format = detectFormat(bytes);
|
|
2167
|
+
if (!format || (!exif && !xmp)) return bytes;
|
|
2168
|
+
if (format === "jpeg") {
|
|
2169
|
+
const j = parseJpeg(bytes, errors);
|
|
2170
|
+
const parts = [];
|
|
2171
|
+
let at = 2;
|
|
2172
|
+
const first = j.segments[0];
|
|
2173
|
+
if (first && jpegKind(bytes, first) === "jfif") at = first.end;
|
|
2174
|
+
parts.push(bytes.subarray(0, at));
|
|
2175
|
+
if (exif) parts.push(app1(EXIF_HEAD, exif));
|
|
2176
|
+
if (xmp) {
|
|
2177
|
+
if (xmp.length + XMP_HEAD.length + 2 > 65535) return bytes;
|
|
2178
|
+
parts.push(app1(XMP_HEAD, xmp));
|
|
2179
|
+
}
|
|
2180
|
+
parts.push(bytes.subarray(at));
|
|
2181
|
+
return concat(parts);
|
|
2182
|
+
}
|
|
2183
|
+
if (format === "png") {
|
|
2184
|
+
const p = parsePng(bytes, errors);
|
|
2185
|
+
const ihdr = p.chunks[0];
|
|
2186
|
+
if (!ihdr || ihdr.type !== "IHDR") return bytes;
|
|
2187
|
+
const parts = [bytes.subarray(0, ihdr.end)];
|
|
2188
|
+
if (exif) parts.push(pngChunk("eXIf", exif));
|
|
2189
|
+
if (xmp) {
|
|
2190
|
+
const head = fromLatin1("XML:com.adobe.xmp\0\0\0\0\0");
|
|
2191
|
+
parts.push(pngChunk("iTXt", concat([head, xmp])));
|
|
2192
|
+
}
|
|
2193
|
+
parts.push(bytes.subarray(ihdr.end));
|
|
2194
|
+
return concat(parts);
|
|
2195
|
+
}
|
|
2196
|
+
const w = parseWebp(bytes, errors);
|
|
2197
|
+
const chunks = w.chunks.slice();
|
|
2198
|
+
const flags = (exif ? 0x08 : 0) | (xmp ? 0x04 : 0);
|
|
2199
|
+
if (!chunks.length) return bytes;
|
|
2200
|
+
if (chunks[0].type !== "VP8X") {
|
|
2201
|
+
const head = new Uint8Array(10);
|
|
2202
|
+
head[0] = flags | (w.alpha || chunks.some((c) => c.type === "ALPH") ? 0x10 : 0);
|
|
2203
|
+
const cw = (width ?? w.width ?? 1) - 1;
|
|
2204
|
+
const ch = (height ?? w.height ?? 1) - 1;
|
|
2205
|
+
head[4] = cw & 255; head[5] = (cw >> 8) & 255; head[6] = (cw >> 16) & 255;
|
|
2206
|
+
head[7] = ch & 255; head[8] = (ch >> 8) & 255; head[9] = (ch >> 16) & 255;
|
|
2207
|
+
chunks.unshift({ type: "VP8X", bytes: head });
|
|
2208
|
+
}
|
|
2209
|
+
if (exif) chunks.push({ type: "EXIF", bytes: exif });
|
|
2210
|
+
if (xmp) chunks.push({ type: "XMP ", bytes: xmp });
|
|
2211
|
+
return buildWebp(bytes, chunks, 0, flags);
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
function app1(head, payload) {
|
|
2215
|
+
const h = fromLatin1(head);
|
|
2216
|
+
const out = new Uint8Array(4 + h.length + payload.length);
|
|
2217
|
+
out[0] = 0xff;
|
|
2218
|
+
out[1] = 0xe1;
|
|
2219
|
+
const size = 2 + h.length + payload.length;
|
|
2220
|
+
out[2] = size >> 8;
|
|
2221
|
+
out[3] = size & 255;
|
|
2222
|
+
out.set(h, 4);
|
|
2223
|
+
out.set(payload, 4 + h.length);
|
|
2224
|
+
return out;
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
// ── orientation ──────────────────────────────────────────────────────────────
|
|
2228
|
+
|
|
2229
|
+
/**
|
|
2230
|
+
* The canvas transform that draws an image of raw size `w`×`h` upright for EXIF
|
|
2231
|
+
* orientation `o` (1 to 8), and the upright size: `{ a, b, c, d, e, f, width, height }`
|
|
2232
|
+
* for `ctx.setTransform(a, b, c, d, e, f)`. Anything else is the identity.
|
|
2233
|
+
*/
|
|
2234
|
+
export function orientTransform(o, w, h) {
|
|
2235
|
+
const t = {
|
|
2236
|
+
1: [1, 0, 0, 1, 0, 0],
|
|
2237
|
+
2: [-1, 0, 0, 1, w, 0],
|
|
2238
|
+
3: [-1, 0, 0, -1, w, h],
|
|
2239
|
+
4: [1, 0, 0, -1, 0, h],
|
|
2240
|
+
5: [0, 1, 1, 0, 0, 0],
|
|
2241
|
+
6: [0, 1, -1, 0, h, 0],
|
|
2242
|
+
7: [0, -1, -1, 0, h, w],
|
|
2243
|
+
8: [0, -1, 1, 0, 0, w],
|
|
2244
|
+
}[o] ?? [1, 0, 0, 1, 0, 0];
|
|
2245
|
+
const swap = o >= 5 && o <= 8;
|
|
2246
|
+
const [a, b, c, d, e, f] = t;
|
|
2247
|
+
return { a, b, c, d, e, f, width: swap ? h : w, height: swap ? w : h };
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
/**
|
|
2251
|
+
* RGBA pixels (`w`×`h`) turned upright for EXIF orientation `o`: the same
|
|
2252
|
+
* transform as orientTransform, applied to the pixels, for checking it and for
|
|
2253
|
+
* where there is no canvas. Returns `{ data, width, height }`.
|
|
2254
|
+
*/
|
|
2255
|
+
export function orientPixels(rgba, w, h, o) {
|
|
2256
|
+
const { a, b, c, d, e, f, width, height } = orientTransform(o, w, h);
|
|
2257
|
+
const data = new Uint8ClampedArray(width * height * 4);
|
|
2258
|
+
for (let y = 0; y < h; y++) {
|
|
2259
|
+
for (let x = 0; x < w; x++) {
|
|
2260
|
+
// a pixel's centre maps through the transform; its square lands on exactly one destination pixel
|
|
2261
|
+
const dx = Math.floor(a * (x + 0.5) + c * (y + 0.5) + e);
|
|
2262
|
+
const dy = Math.floor(b * (x + 0.5) + d * (y + 0.5) + f);
|
|
2263
|
+
const from = (y * w + x) * 4;
|
|
2264
|
+
const to = (dy * width + dx) * 4;
|
|
2265
|
+
data[to] = rgba[from];
|
|
2266
|
+
data[to + 1] = rgba[from + 1];
|
|
2267
|
+
data[to + 2] = rgba[from + 2];
|
|
2268
|
+
data[to + 3] = rgba[from + 3];
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
return { data, width, height };
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
// ── provenance: what a result says about what happened ──────────────────────
|
|
2275
|
+
|
|
2276
|
+
/**
|
|
2277
|
+
* The record a result carries (the media value's `provenance`, small and free of personal values):
|
|
2278
|
+
* `{ pixels: "unchanged" | "re-encoded", metadata: "kept" | "removed" | "location-removed" | "partly-kept" | "dropped",
|
|
2279
|
+
* removed?: [...], kept?: [...], note? }`.
|
|
2280
|
+
*/
|
|
2281
|
+
export function provenance({ pixels = "unchanged", metadata, removed = [], kept = [], note } = {}) {
|
|
2282
|
+
const out = { pixels, metadata };
|
|
2283
|
+
if (removed.length) out.removed = removed.slice(0, 12).map((s) => clip(String(s), 80));
|
|
2284
|
+
if (kept.length) out.kept = kept.slice(0, 12).map((s) => clip(String(s), 80));
|
|
2285
|
+
if (note) out.note = clip(String(note), 200);
|
|
2286
|
+
return out;
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
/** One sentence for a provenance record. */
|
|
2290
|
+
export function provenanceText(p) {
|
|
2291
|
+
if (!p || typeof p !== "object") return "";
|
|
2292
|
+
const pixels = p.pixels === "re-encoded" ? "pixels re-encoded" : "pixels unchanged (the compressed image is copied byte for byte)";
|
|
2293
|
+
const meta = {
|
|
2294
|
+
kept: "metadata kept",
|
|
2295
|
+
removed: "all metadata removed",
|
|
2296
|
+
"location-removed": "location removed, other metadata kept",
|
|
2297
|
+
"partly-kept": "metadata partly kept",
|
|
2298
|
+
dropped: "metadata dropped by the re-encode",
|
|
2299
|
+
}[p.metadata] ?? "metadata not recorded";
|
|
2300
|
+
return `${meta}; ${pixels}`;
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
// ── blobs (the callers that have a Blob) ─────────────────────────────────────
|
|
2304
|
+
|
|
2305
|
+
async function bytesOf(blob) {
|
|
2306
|
+
if (blob.size > LIMITS.bytes) return refuse("too-large", `the image is ${blob.size} bytes; metadata is read from images up to ${LIMITS.bytes}`);
|
|
2307
|
+
return new Uint8Array(await blob.arrayBuffer());
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
/** inspect() for a Blob (or a media value's blob). */
|
|
2311
|
+
export async function inspectBlob(blob) {
|
|
2312
|
+
const bytes = await bytesOf(blob);
|
|
2313
|
+
return bytes.ok === false ? bytes : inspectAsync(bytes);
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
/** edit() for a Blob: `{ ok: true, blob, … }` with the result as a Blob of the same type. */
|
|
2317
|
+
export async function editBlob(blob, options) {
|
|
2318
|
+
const bytes = await bytesOf(blob);
|
|
2319
|
+
if (bytes.ok === false) return bytes;
|
|
2320
|
+
const r = await editAsync(bytes, options);
|
|
2321
|
+
if (!r.ok) return r;
|
|
2322
|
+
const { bytes: out, ...rest } = r;
|
|
2323
|
+
const metadata = options.all ? "removed" : rest.removed.some((x) => /location/.test(x)) ? "location-removed" : "kept";
|
|
2324
|
+
const note = rest.set ? `fields edited: ${rest.set.join(", ")}` : undefined;
|
|
2325
|
+
return { ...rest, blob: r.changed ? new Blob([out], { type: blob.type }) : blob, provenance: provenance({ pixels: "unchanged", metadata, removed: rest.removed, kept: rest.kept, note }) };
|
|
2326
|
+
}
|
|
2327
|
+
|
|
2328
|
+
/**
|
|
2329
|
+
* Put the EXIF and XMP of `source` (a Blob) into `target` (a Blob of an image that was made from it: an effects result, a canvas export),
|
|
2330
|
+
* for a target whose pixels are already upright (its orientation is written as 1). The target's own bytes are not touched beyond the
|
|
2331
|
+
* added segments. `gps: false` leaves the location out. The color profile does not come along.
|
|
2332
|
+
*/
|
|
2333
|
+
export async function carryBlob(source, target, { gps = true } = {}) {
|
|
2334
|
+
const from = await bytesOf(source);
|
|
2335
|
+
if (from.ok === false) return from;
|
|
2336
|
+
const to = await bytesOf(target);
|
|
2337
|
+
if (to.ok === false) return to;
|
|
2338
|
+
const src = inspect(from);
|
|
2339
|
+
if (!src.ok) return { ...src, message: `the source: ${src.message}` };
|
|
2340
|
+
const dst = inspect(to);
|
|
2341
|
+
if (!dst.ok) return { ...dst, message: `the target: ${dst.message}` };
|
|
2342
|
+
if (dst.has.exif || dst.has.xmp) return refuse("unsupported", "the target already has EXIF or XMP; remove it first so two sets do not meet");
|
|
2343
|
+
const c = carry(from, { gps, width: dst.width, height: dst.height });
|
|
2344
|
+
const removed = [...c.removed];
|
|
2345
|
+
const kept = [...c.kept];
|
|
2346
|
+
const lost = [src.has.iptc && "IPTC", src.has.text && "text entries", src.unsupported.some((u) => /MakerNote/.test(u)) && "MakerNote", src.has.icc && "color profile", src.has.contentCredentials && "Content Credentials"].filter(Boolean);
|
|
2347
|
+
if (!c.exif && !c.xmp) return { ok: true, blob: target, changed: false, removed, kept, warnings: [...c.warnings, "the source had no EXIF or XMP that could be carried"], provenance: provenance({ pixels: "unchanged", metadata: "dropped", removed: lost }) };
|
|
2348
|
+
const out = embed(to, { exif: c.exif, xmp: c.xmp, width: dst.width, height: dst.height });
|
|
2349
|
+
const metadata = !gps && src.has.location ? "location-removed" : lost.length ? "partly-kept" : "kept";
|
|
2350
|
+
return {
|
|
2351
|
+
ok: true,
|
|
2352
|
+
blob: new Blob([out], { type: target.type || MIME[dst.format] }),
|
|
2353
|
+
changed: true,
|
|
2354
|
+
removed: [...removed, ...lost],
|
|
2355
|
+
kept,
|
|
2356
|
+
warnings: c.warnings,
|
|
2357
|
+
provenance: provenance({ pixels: "unchanged", metadata, removed: [...removed, ...lost], kept, note: "EXIF and XMP carried over from the source; orientation set to 1" }),
|
|
2358
|
+
};
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
const MIME = { jpeg: "image/jpeg", png: "image/png", webp: "image/webp" };
|
|
2362
|
+
|
|
2363
|
+
/** What turning upright means for a TIFF, an AVIF, a HEIC or a GIF (inspect() refused them, naming the format and orientation): nothing is changed. */
|
|
2364
|
+
function orientationOfOther(blob, r) {
|
|
2365
|
+
const unchanged = (message) => ({ ok: true, blob, changed: false, orientation: r.orientation ?? 1, message, removed: [], kept: [], warnings: [], provenance: provenance({ pixels: "unchanged", metadata: "kept" }) });
|
|
2366
|
+
const name = OTHER_NAME[r.format];
|
|
2367
|
+
if (r.format === "gif") return unchanged("a GIF has no orientation: it is always drawn as stored, so the image is unchanged");
|
|
2368
|
+
if (r.format === "avif" || r.format === "heic") {
|
|
2369
|
+
if (!r.orientation || r.orientation === 1) return unchanged(`already upright (no rotation or mirror recorded in the ${name}): the image is unchanged`);
|
|
2370
|
+
return unchanged(`the ${name}'s rotation and mirror properties (orientation ${r.orientation}) are part of the image, and a browser applies them when it draws it, so it already shows upright; the file is unchanged`);
|
|
2371
|
+
}
|
|
2372
|
+
if (!r.orientation || r.orientation === 1) return unchanged("already upright (orientation 1 or none): the image is unchanged");
|
|
2373
|
+
if (r.orientation > 8) return { ...refuse("malformed", `orientation ${r.orientation} is not valid (1 to 8); the image is unchanged`), orientation: r.orientation };
|
|
2374
|
+
return { ...refuse("unsupported", `this TIFF has orientation ${r.orientation} (${r.orientationText}); turning a TIFF upright is not done, because browsers can't reliably draw or encode TIFF; it is unchanged`), orientation: r.orientation };
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
/**
|
|
2378
|
+
* An animated WebP or APNG turned upright: every frame decoded, turned and written again with its timing, disposal, blend and the
|
|
2379
|
+
* loop count (src/media/animated.js; the caller hands the codec over as `animated`, made by `createAnimated` there, because this module has no imports).
|
|
2380
|
+
* The color profile is kept (the pixels aren't converted); EXIF and XMP come along as for a still image.
|
|
2381
|
+
*/
|
|
2382
|
+
async function uprightAnimated(blob, bytes, report, { metadata, gps, animated }) {
|
|
2383
|
+
const o = report.orientation;
|
|
2384
|
+
const name = report.format === "png" ? "animated PNG" : "animated WebP";
|
|
2385
|
+
const codec = animated;
|
|
2386
|
+
if (!codec) return { ...refuse("unsupported", `this ${name} has orientation ${o} (${report.orientationText}) and the code that turns animations isn't available in this runtime; it is unchanged`), orientation: o };
|
|
2387
|
+
const r = await codec.upright(bytes, report.format, o);
|
|
2388
|
+
if (!r.ok) return { ...refuse(r.reason, `this ${name} has orientation ${o} (${report.orientationText}) and can't be turned: ${r.message}; it is unchanged`), orientation: o };
|
|
2389
|
+
let out = r.bytes;
|
|
2390
|
+
const type = MIME[report.format];
|
|
2391
|
+
const removed = [];
|
|
2392
|
+
const kept = [];
|
|
2393
|
+
const warnings = [];
|
|
2394
|
+
if (report.has.icc && !r.keptColor) removed.push("color profile");
|
|
2395
|
+
if (report.has.icc && r.keptColor) kept.push("color profile (the pixels are not converted)");
|
|
2396
|
+
if (report.has.thumbnail) removed.push("EXIF thumbnail");
|
|
2397
|
+
let meta = "dropped";
|
|
2398
|
+
if (metadata === "keep") {
|
|
2399
|
+
const c = carry(bytes, { gps, width: r.width, height: r.height });
|
|
2400
|
+
if (c.exif || c.xmp) {
|
|
2401
|
+
out = embed(out, { exif: c.exif, xmp: c.xmp, width: r.width, height: r.height });
|
|
2402
|
+
meta = !gps && report.has.location ? "location-removed" : "kept";
|
|
2403
|
+
}
|
|
2404
|
+
for (const x of c.removed) if (!removed.includes(x)) removed.push(x);
|
|
2405
|
+
kept.push(...c.kept);
|
|
2406
|
+
warnings.push(...c.warnings);
|
|
2407
|
+
if (report.has.contentCredentials) (removed.push("Content Credentials"), warnings.push("Content Credentials do not survive a re-encode"));
|
|
2408
|
+
if (!c.exif && !c.xmp) warnings.push("the source had no EXIF or XMP to keep");
|
|
2409
|
+
const lost = [report.has.iptc && "IPTC", report.has.text && "text entries"].filter(Boolean);
|
|
2410
|
+
removed.push(...lost);
|
|
2411
|
+
if (!c.exif && !c.xmp) meta = "dropped";
|
|
2412
|
+
else if (lost.length) meta = !gps && report.has.location ? "location-removed" : "partly-kept";
|
|
2413
|
+
} else {
|
|
2414
|
+
for (const label of ["EXIF", "XMP", "IPTC", "text entries"]) if (report.has[label === "text entries" ? "text" : label.toLowerCase()]) removed.push(label);
|
|
2415
|
+
meta = "removed";
|
|
2416
|
+
}
|
|
2417
|
+
if (report.format === "webp") warnings.push("every frame is written lossless, so the file can be larger than the lossy original");
|
|
2418
|
+
return {
|
|
2419
|
+
ok: true,
|
|
2420
|
+
blob: new Blob([out], { type }),
|
|
2421
|
+
changed: true,
|
|
2422
|
+
orientation: 1,
|
|
2423
|
+
from: o,
|
|
2424
|
+
width: r.width,
|
|
2425
|
+
height: r.height,
|
|
2426
|
+
frames: r.frames,
|
|
2427
|
+
removed,
|
|
2428
|
+
kept,
|
|
2429
|
+
warnings,
|
|
2430
|
+
provenance: provenance({ pixels: "re-encoded", metadata: meta, removed, kept, note: `${r.frames} frames turned upright from orientation ${o}; timing and loop count kept` }),
|
|
2431
|
+
};
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
/**
|
|
2435
|
+
* Turn an image upright: draw its pixels through the orientation transform and
|
|
2436
|
+
* encode them again, in the same format. This re-encodes (JPEG and WebP lose a
|
|
2437
|
+
* little quality, PNG is lossless), so the result says so.
|
|
2438
|
+
*
|
|
2439
|
+
* `metadata`: "keep" puts the source's EXIF and XMP into the result with orientation 1 (and its location
|
|
2440
|
+
* unless `gps: false`); "strip" puts none. The color profile never comes along.
|
|
2441
|
+
* An image that is already upright, or has no orientation tag, is returned as it is.
|
|
2442
|
+
*
|
|
2443
|
+
* Needs `createImageBitmap` and `OffscreenCanvas` (the page, the sandbox Worker); returns `{ ok: false }` without.
|
|
2444
|
+
*/
|
|
2445
|
+
export async function normalizeOrientation(blob, { metadata = "keep", gps = true, quality = 0.92, animated } = {}) {
|
|
2446
|
+
const bytes = await bytesOf(blob);
|
|
2447
|
+
if (bytes.ok === false) return bytes;
|
|
2448
|
+
const report = inspect(bytes);
|
|
2449
|
+
if (!report.ok) return report.format ? orientationOfOther(blob, report) : report;
|
|
2450
|
+
const o = report.orientation ?? 1;
|
|
2451
|
+
if (o === 1) return { ok: true, blob, changed: false, orientation: 1, message: "already upright (orientation 1 or none): the image is unchanged", removed: [], kept: [], warnings: [], provenance: provenance({ pixels: "unchanged", metadata: "kept" }) };
|
|
2452
|
+
if (o < 1 || o > 8) return refuse("malformed", `orientation ${o} is not valid (1 to 8); the image is unchanged`);
|
|
2453
|
+
if (report.has.animated) return uprightAnimated(blob, bytes, report, { metadata, gps, animated });
|
|
2454
|
+
if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas !== "function") return refuse("unsupported", "turning pixels needs createImageBitmap and OffscreenCanvas, which this runtime does not have");
|
|
2455
|
+
let bitmap;
|
|
2456
|
+
try {
|
|
2457
|
+
bitmap = await createImageBitmap(blob, { imageOrientation: "none" });
|
|
2458
|
+
} catch {
|
|
2459
|
+
return refuse("unsupported", `this browser can't decode the ${report.format.toUpperCase()}; the image is unchanged`);
|
|
2460
|
+
}
|
|
2461
|
+
try {
|
|
2462
|
+
const rawW = report.width ?? bitmap.width;
|
|
2463
|
+
const rawH = report.height ?? bitmap.height;
|
|
2464
|
+
// A browser that ignored "none" has turned a quarter-turn image already: don't turn it twice.
|
|
2465
|
+
const already = o >= 5 && bitmap.width === rawH && bitmap.height === rawW && rawW !== rawH;
|
|
2466
|
+
const t = orientTransform(already ? 1 : o, bitmap.width, bitmap.height);
|
|
2467
|
+
const canvas = new OffscreenCanvas(t.width, t.height);
|
|
2468
|
+
try {
|
|
2469
|
+
const g = canvas.getContext("2d");
|
|
2470
|
+
g.setTransform(t.a, t.b, t.c, t.d, t.e, t.f);
|
|
2471
|
+
g.drawImage(bitmap, 0, 0);
|
|
2472
|
+
const type = MIME[report.format];
|
|
2473
|
+
const encoded = await canvas.convertToBlob({ type, quality });
|
|
2474
|
+
if (!encoded || encoded.type !== type) return refuse("unsupported", `this browser can't encode ${type}; the image is unchanged`);
|
|
2475
|
+
let out = new Uint8Array(await encoded.arrayBuffer());
|
|
2476
|
+
const removed = ["EXIF thumbnail", "color profile (the result is sRGB)"].filter((_, i) => (i === 0 ? report.has.thumbnail : report.has.icc));
|
|
2477
|
+
const kept = [];
|
|
2478
|
+
const warnings = [];
|
|
2479
|
+
let meta = "dropped";
|
|
2480
|
+
if (metadata === "keep") {
|
|
2481
|
+
const c = carry(bytes, { gps, width: t.width, height: t.height });
|
|
2482
|
+
if (c.exif || c.xmp) {
|
|
2483
|
+
out = embed(out, { exif: c.exif, xmp: c.xmp, width: t.width, height: t.height });
|
|
2484
|
+
meta = !gps && report.has.location ? "location-removed" : "kept";
|
|
2485
|
+
}
|
|
2486
|
+
removed.push(...c.removed.filter((r) => !removed.includes(r)));
|
|
2487
|
+
kept.push(...c.kept);
|
|
2488
|
+
warnings.push(...c.warnings);
|
|
2489
|
+
if (report.has.contentCredentials) (removed.push("Content Credentials"), warnings.push("Content Credentials do not survive a re-encode"));
|
|
2490
|
+
if (!c.exif && !c.xmp) warnings.push("the source had no EXIF or XMP to keep");
|
|
2491
|
+
const lost = [report.has.iptc && "IPTC", report.has.text && "text entries", report.unsupported.some((u) => /MakerNote/.test(u)) && "MakerNote"].filter(Boolean);
|
|
2492
|
+
for (const l of lost) removed.push(l);
|
|
2493
|
+
if (!c.exif && !c.xmp) meta = "dropped";
|
|
2494
|
+
else if (lost.length || report.has.icc) meta = !gps && report.has.location ? "location-removed" : "partly-kept";
|
|
2495
|
+
} else {
|
|
2496
|
+
for (const label of ["EXIF", "XMP", "IPTC", "text entries"]) if (report.has[label === "text entries" ? "text" : label.toLowerCase()]) removed.push(label);
|
|
2497
|
+
meta = "removed";
|
|
2498
|
+
}
|
|
2499
|
+
return {
|
|
2500
|
+
ok: true,
|
|
2501
|
+
blob: new Blob([out], { type }),
|
|
2502
|
+
changed: true,
|
|
2503
|
+
orientation: 1,
|
|
2504
|
+
from: o,
|
|
2505
|
+
width: t.width,
|
|
2506
|
+
height: t.height,
|
|
2507
|
+
removed,
|
|
2508
|
+
kept,
|
|
2509
|
+
warnings,
|
|
2510
|
+
provenance: provenance({ pixels: "re-encoded", metadata: meta, removed, kept, note: `turned upright from orientation ${o}` }),
|
|
2511
|
+
};
|
|
2512
|
+
} finally {
|
|
2513
|
+
canvas.width = canvas.height = 0;
|
|
2514
|
+
}
|
|
2515
|
+
} finally {
|
|
2516
|
+
bitmap.close?.();
|
|
2517
|
+
}
|
|
2518
|
+
}
|