chore: initialize production repository

This commit is contained in:
Haperone 2026-06-15 00:41:06 +02:00
parent 1ee5b8f226
commit c08a5e3677
65 changed files with 30110 additions and 2 deletions

81
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,81 @@
name: Release
on:
pull_request:
push:
branches:
- main
tags:
- "[0-9]+.[0-9]+.[0-9]+"
permissions:
contents: read
jobs:
validate:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: npm ci
- name: Run gates and tests
run: npm run test:release
release:
needs: validate
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: npm ci
- name: Validate exact numeric tag matches manifest
shell: bash
run: |
tag="${GITHUB_REF_NAME}"
if [[ ! "$tag" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Release tag must be exact numeric SemVer without a v prefix: ${tag}"
exit 1
fi
manifest_version="$(node -p "require('./manifest.json').version")"
if [[ "$tag" != "$manifest_version" ]]; then
echo "Tag ${GITHUB_REF_NAME} does not match manifest version ${manifest_version}"
exit 1
fi
- name: Run release tests and build root bundle
run: npm run test:release
- name: Prepare artifacts
run: npm run prepare:release
- name: Create release
uses: softprops/action-gh-release@v2
with:
name: ${{ github.ref_name }}
tag_name: ${{ github.ref_name }}
files: |
build/manifest.json
build/main.js
build/styles.css
build/versions.json
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

27
.gitignore vendored Normal file
View file

@ -0,0 +1,27 @@
node_modules/
main.js
build/
dist-ts/
.DS_Store
Thumbs.db
*.log
.cache/
# Obsidian plugin generated folders
cache-backups/
original-files-backups/
qa-backups/
qa-screenshots/
# Editors/OS
.vscode/
.idea/
.obsidian/
*.iml
# Local state/caches/locks (do not commit)
data.json
tinyLocal-cache.json
# Local backup/script files
Бекап*сжатия.js

657
LICENSE Normal file
View file

@ -0,0 +1,657 @@
Local Image Compress
Copyright (C) 2025-2026 Haperone
SPDX-License-Identifier: GPL-3.0-or-later
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License below
for details.
The bundled libimagequant notice and complete GPL version 3 license text
follow.
libimagequant is derived from code by Jef Poskanzer and Greg Roelofs
licensed under pngquant's original license (at the end of this file),
and contains extensive changes and additions by Kornel Lesiński
licensed under GPL v3 or later.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
libimagequant © 2009-2018 by Kornel Lesiński.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
© 1989, 1991 by Jef Poskanzer.
© 1997, 2000, 2002 by Greg Roelofs.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation. This software is provided "as is" without express or
implied warranty.

160
README.md
View file

@ -1,3 +1,159 @@
# Local Image Compress
## Local Image Compress
Production repository bootstrap. The complete production source is published through a reviewed branch.
Compress PNG and JPEG images in your desktop vault locally with bundled WebAssembly codecs. No cloud services, no external binaries, and no `node_modules` setup are required for normal plugin use.
[Русская версия](README.ru.md)
### Features
- **Local compression**: PNG through libimagequant-wasm plus PNG WASM decoding; JPEG through mozjpeg-wasm.
- **Commands**:
- Compress all images in the current note
- Compress all images in a folder
- Compress all images in the entire vault
- Move compressed files back to original locations
- **Automation**:
- Auto-compress new files on add
- Background compression when inactive and threshold is exceeded
- **UI & convenience**:
- Context menu for files/folders
- Space savings indicator with tooltip
- Status bar progress
- **Safety & reliability**:
- Cache of processed files with cache backups
- Backups before moving compressed files
### Installation
1. Install `Local Image Compress` from Obsidian Community Plugins, or copy the release files to `Vault/.obsidian/plugins/local-image-compress`.
2. Enable the plugin in `Settings -> Community plugins`.
3. Start compressing images.
The release is self-contained. You do not need `pngquant`, `mozjpeg`, Homebrew, Scoop, or plugin-level `node_modules`.
### Build and release model
Source lives in `src-ts`. Root `main.js` is generated and ignored, so readable TypeScript rather than compiled output stays in Git. `npm run build` creates a production-minified local bundle; `npm run test:release` rebuilds it twice, requires deterministic bytes, validates inline WASM, and stages the release allowlist.
The GitHub release artifact contains only Obsidian install files: `manifest.json`, `main.js`, `styles.css`, and `versions.json`. Production minification is not obfuscation: the complete source remains readable in the repository. Tags are exact numeric SemVer without a `v` prefix. See [RELEASE_POLICY.md](RELEASE_POLICY.md).
### Commands
- **Compress all images in note**: Processes images referenced/used in the active note.
- **Compress all images in folder**: Lets you choose a folder and compress all supported images inside, excluding the output folder.
- **Compress all images in vault**: Full scan of the vault, excluding the output folder.
- **Move compressed files**: Moves compressed results back to original locations. Backups of originals and compressed versions are created beforehand.
### Supported formats
- PNG (`imagequant` WASM pipeline)
- JPEG/JPG (`mozjpeg` WASM pipeline)
WebP, GIF, BMP, HEIC/HEIF, and AVIF are intentionally skipped in this release because no encoder pipeline for those formats is bundled.
### Settings
| Setting | Description | Type/range | Default |
|---|---|---|---|
| PNG quality (min-max) | Quality range for lossy PNG quantization | 1-100 (e.g. `65-80`) | `65-80` |
| JPEG quality | JPEG compression quality | 1-95 | `85` |
| Allowed roots | Relative paths where compression is allowed. Empty = everywhere | list of strings | empty |
| Output folder | Where to store compressed files | string | `Compressed` |
| Auto-compress new files | Compress new images on add | boolean | `false` |
| Background compression | Compress in background when inactive | boolean | `true` |
| Background threshold | Number of uncompressed images to auto-start | 10-1000 | `50` |
| Inactivity threshold | Minutes without user input before background compression may start | 1-60 minutes | `2` |
| Cache retention | Months to keep stale cache entries after last access | 1-60 months | `12` |
| Auto-clean ghosts on start | Remove cache entries pointing to deleted files on startup | boolean | `false` |
| Auto backup retention | Delete old move backups automatically | boolean | `false` |
| Keep backups, days | Delete move backups older than N days when retention is enabled | 1-365 | `30` |
| Auto-move compressed files | Move compressed outputs back to original locations on startup when enough files are ready | boolean | `false` |
| Auto-move threshold | Number of movable compressed files required to trigger auto-move | 1-1000 | `50` |
The settings page also shows WASM module status, space savings, cache controls, ghost-entry cleanup, and backup controls.
### How it works
1. Compressed files are saved in the `Compressed` folder mirroring original paths.
2. The cache records processed files and original sizes to avoid re-compression and calculate savings correctly.
3. “Move compressed files” moves files from `Compressed` back to original locations if the original is in allowed roots. Backups are created before moving.
Minimum sizes for compression: tiny images are skipped, typically `<5KB` for PNG and `<10KB` for JPEG.
Internal safety limits are fixed: files larger than `100 MB` are skipped before reading, images above `100 million` pixels are skipped after header validation, one compression job may run for up to `120 seconds`, and worker initialization may run for up to `60 seconds`.
### Cache and backups
- **Cache**: stored at `Vault/.obsidian/plugins/local-image-compress/tinyLocal-cache.json`.
- **Cache backups**: created automatically on important changes in `Vault/.local-image-compress/backups/cache/` and capped at 50 files.
- **Backups before moving**: stored in `Vault/.local-image-compress/backups/originals/`. Includes originals and compressed files by vault-relative path.
- Existing backup folders from older versions are migrated automatically on startup. The primary cache file stays in the plugin directory.
### Automation
- “Background compression” shows a threshold slider when enabled.
- “Keep backups, days” shows a retention slider when enabled.
- “Auto-move compressed files” shows an item threshold slider. On startup, if `Compressed` count is at or above the threshold, moving starts.
### Compatibility
- `isDesktopOnly: true`.
- Requires Obsidian `1.4.0+`.
- No native compressor binaries are required on Windows, macOS, or Linux.
- Mobile support is not declared yet because cache, move, and backup file management still rely on desktop Node filesystem APIs.
- During compression and move operations, the compatible plugin `obsidian-paste-image-rename` is temporarily disabled if enabled, to avoid naming/moving conflicts. The guard restores plugins it disabled and skips restore ownership if the plugin state changed externally during the operation.
### Interaction with Paste Image Rename
This plugin temporarily disables the third-party plugin `obsidian-paste-image-rename` while compressing or moving files. There is no opt-out setting because the compressed-output mapping depends on those fresh files not being renamed by another plugin.
Why it is needed:
- Paste Image Rename registers a `vault.on("create")` handler that fires for every image added to the vault within about one second of creation. It always acts on files whose name starts with `Pasted image `, and on all other images when its "Handle all attachments" option is enabled.
- While this plugin writes compressed copies into the output folder, those fresh files trigger that handler. With an active Markdown view, Paste Image Rename renames the just-written output (which breaks this plugin's compressed-to-original mapping that the move step relies on) or shows a rename modal for each file. With no active Markdown view, it shows an `Error: No active file found` notice for every created file, which spams the interface during batch runs.
- Obsidian has no public API for one plugin to ask another to pause, so disabling that one plugin for the duration is the only reliable mitigation.
How it is kept safe:
- Only the single known plugin id `obsidian-paste-image-rename` is affected, and only while a compression or move operation is running.
- The plugin is always restored afterwards, with retries. The guard tracks whether it was the one that disabled it and skips restore ownership if the plugin's state changed externally during the operation.
- Enabling/disabling that plugin uses Obsidian's internal `app.plugins` API because there is no public equivalent; the calls are feature-detected and fail gracefully.
### Privacy and external behavior
- **Network**: the plugin makes no runtime network requests. PNG/JPEG codecs are bundled in `main.js`; images are not uploaded.
- **Telemetry and ads**: no analytics, telemetry, crash reporting, tracking, dynamic ads, or self-update mechanism is included.
- **Accounts and payments**: no account, subscription, license key, or payment is required. The manifest funding link is optional and is not contacted by the plugin.
- **Vault files**: the plugin reads supported images selected by commands, automation, or allowed roots. It writes compressed outputs to the configured vault-relative folder and can replace originals only through the documented move/auto-move flow after creating backups.
- **Local state**: cache data is stored in the plugin directory. Cache and move backups are stored under `Vault/.local-image-compress/backups/`.
- **External files**: plugin-managed data stays inside the current vault. The “Open folder” actions only ask the operating system to reveal documented backup folders; they do not transmit data.
- **Other plugins**: `obsidian-paste-image-rename` may be temporarily disabled during compression/move as disclosed above, then restored with ownership checks.
### Tips
- Reasonable quality ranges: PNG `65-80`, JPEG `75-90`.
- Configure “Allowed roots” if you want to compress only in specific folders, such as `files/` or `images/`.
- Use background compression if you have many uncompressed images; it starts on inactivity and threshold.
### FAQ
**The plugin says WebAssembly modules failed to initialize.**
Reload the plugin. If it repeats, report a bug with the Obsidian version, platform, and console error.
**Where do compressed files go?**
Into `Compressed` by default. To replace originals, use “Move compressed files”.
**How is savings calculated?**
Savings are exact when the cache has original/output sizes. For uncompressed PNG/JPEG files, the plugin uses conservative estimates with capped ratios; current compressed output sizes are read live when needed.
**What are ghost entries?**
Cache entries pointing to removed or missing files. You can clear them in settings.
### Troubleshooting
- Ensure files are large enough: very small images are skipped.
- Check “Allowed roots”: files outside these paths are not processed.
- If moving does not happen, make sure a compressed file has a corresponding original in an allowed root.
- Watch app notices and the developer console for `Local Image Compress` logs.
### Metadata
- ID: `local-image-compress`
- Name: `Local Image Compress`
- Version: `1.0.0`
- Min app version: `1.4.0`
- Desktop-only: yes
- Repository: `https://github.com/haperone/local-image-compress`
### License
- Plugin distribution: GPL-3.0-or-later (see `LICENSE`).
- The plugin bundles `imagequant`/libimagequant WebAssembly code under GPL v3, so the distributed plugin license is GPL-3.0-or-later.
- Third-party codecs: see `THIRD_PARTY_NOTICES.md` and the exact tracked texts under `licenses/`.

159
README.ru.md Normal file
View file

@ -0,0 +1,159 @@
## Local Image Compress
Сжимает PNG и JPEG файлы в desktop-хранилище локально через встроенные WebAssembly-кодеки. Облако не используется, внешние бинарники и `node_modules` для обычной установки не нужны.
[English version](README.md)
### Установка
1. Установите `Local Image Compress` через Obsidian Community Plugins или скопируйте release-файлы в `Vault/.obsidian/plugins/local-image-compress`.
2. Включите плагин в `Settings -> Community plugins`.
3. Запускайте сжатие изображений.
Release самодостаточный. Устанавливать `pngquant`, `mozjpeg`, Homebrew, Scoop или зависимости в папку плагина не нужно.
### Модель сборки и релиза
Исходники находятся в `src-ts`. Корневой `main.js` генерируется и игнорируется Git, поэтому в репозитории остаётся читаемый TypeScript, а не compiled output. `npm run build` создаёт production-minified локальный bundle; `npm run test:release` собирает его дважды, проверяет детерминированные байты, inline WASM и точный allowlist релиза.
GitHub release artifact содержит только install-файлы Obsidian: `manifest.json`, `main.js`, `styles.css` и `versions.json`. Минификация не является обфускацией: полный читаемый исходный код остаётся в репозитории. Теги имеют точный numeric SemVer без префикса `v`. См. [RELEASE_POLICY.md](RELEASE_POLICY.md).
### Возможности
- **Локальное сжатие**: PNG через libimagequant-wasm и PNG WASM decode; JPEG через mozjpeg-wasm.
- **Команды**:
- Сжать все изображения в текущей заметке
- Сжать все изображения в папке
- Сжать все изображения во всём vault
- Переместить сжатые файлы на места оригиналов
- **Автоматизация**:
- Автосжатие новых файлов при добавлении
- Фоновое сжатие при неактивности пользователя и превышении порога
- **UI и удобства**:
- Контекстное меню для файлов/папок
- Индикатор экономии места и tooltip с деталями
- Статус-бар с индикатором процесса
- **Безопасность и надёжность**:
- Кэш обработанных файлов с бэкапами кэша
- Резервные копии перед перемещением сжатых файлов
### Команды
- **Сжать все изображения в заметке**: Обрабатывает изображения, упомянутые или используемые в активной заметке.
- **Сжать все изображения в папке**: Даёт выбрать папку и сжимает все поддерживаемые изображения внутри, кроме папки вывода.
- **Сжать все изображения в vault**: Полный проход по хранилищу, исключая папку вывода.
- **Переместить сжатые файлы**: Переносит результаты сжатия туда, где лежали оригиналы. Перед перемещением создаётся резервная копия оригиналов и сжатых версий.
### Поддерживаемые форматы
- PNG (`imagequant` WASM pipeline)
- JPEG/JPG (`mozjpeg` WASM pipeline)
WebP, GIF, BMP, HEIC/HEIF и AVIF в этом релизе намеренно пропускаются: для них не встроен encoder pipeline.
### Настройки
| Параметр | Описание | Тип/диапазон | По умолчанию |
|---|---|---|---|
| Качество PNG (мин-макс) | Диапазон качества для lossy PNG quantization | 1-100 (например `65-80`) | `65-80` |
| Качество JPEG | Качество сжатия JPEG | 1-95 | `85` |
| Разрешённые корни | Относительные пути, где разрешено сжатие. Пусто = везде | список строк | пусто |
| Выходная папка | Папка для сохранения сжатых файлов | строка | `Compressed` |
| Автосжатие новых файлов | Сжимать новые изображения при добавлении | boolean | `false` |
| Автоматическое фоновое сжатие | Сжимать в фоне при неактивности | boolean | `true` |
| Порог фонового сжатия | Количество несжатых изображений для автозапуска | 10-1000 | `50` |
| Порог неактивности | Минуты без действий пользователя перед запуском фонового сжатия | 1-60 минут | `2` |
| Срок хранения кэша | Сколько месяцев хранить устаревшие записи кэша после последнего доступа | 1-60 месяцев | `12` |
| Автоочистка призраков при старте | Удалять записи кэша на удалённые файлы при запуске | boolean | `false` |
| Автохранение бэкапов | Автоматически удалять старые бэкапы перед переносом | boolean | `false` |
| Хранить бэкапы, дней | Удалять бэкапы переноса старше N дней, если автохранение включено | 1-365 | `30` |
| Автоперемещение сжатых файлов | При запуске переносить сжатые файлы обратно к оригиналам, если готово достаточно файлов | boolean | `false` |
| Порог автоперемещения | Количество готовых к переносу сжатых файлов для автозапуска | 1-1000 | `50` |
Страница настроек также показывает статус WASM-модулей, экономию места, управление кэшем, очистку призрачных записей и управление бэкапами.
### Как это работает
1. Сжатые файлы сохраняются в папку `Compressed` с повторением структуры путей.
2. Кэш фиксирует факт обработки файлов и исходный размер, чтобы не сжимать повторно и корректно считать экономию.
3. Команда «Переместить сжатые файлы» переносит файлы из `Compressed` на места оригиналов, если оригинал найден в разрешённых корнях. Перед перемещением создаётся бэкап.
Минимальные размеры для сжатия: очень маленькие файлы обычно пропускаются (`<5KB` для PNG и `<10KB` для JPEG).
Внутренние лимиты безопасности фиксированы: файлы больше `100 МБ` пропускаются до чтения, изображения выше `100 млн` пикселей пропускаются после проверки заголовка, одно задание сжатия может выполняться до `120 секунд`, а инициализация воркеров — до `60 секунд`.
### Кэш и бэкапы
- **Кэш**: `Vault/.obsidian/plugins/local-image-compress/tinyLocal-cache.json`.
- **Бэкапы кэша**: автоматически создаются при важных изменениях в `Vault/.local-image-compress/backups/cache/`; хранится не более 50 файлов.
- **Бэкапы перед переносом**: сохраняются в `Vault/.local-image-compress/backups/originals/`. Включают оригиналы и сжатые файлы по относительным путям vault.
- Существующие папки бэкапов из старых версий автоматически переносятся при запуске. Основной файл кэша остается в директории плагина.
### Автоматизация
- «Автоматическое фоновое сжатие» при включении показывает ползунок порога.
- «Хранить бэкапы, дней» при включении показывает ползунок срока хранения.
- «Автоперемещение сжатых файлов» при включении показывает порог по количеству файлов. При запуске плагина, если в `Compressed` файлов не меньше порога, запускается перемещение.
### Совместимость
- `isDesktopOnly: true`.
- Требуется Obsidian `1.4.0+`.
- Нативные бинарники компрессоров не нужны на Windows, macOS и Linux.
- Поддержка mobile пока не заявляется: управление кэшем, перемещение и бэкапы всё ещё используют desktop Node filesystem API.
- Во время сжатия и перемещения совместимый плагин `obsidian-paste-image-rename` временно отключается, если он включён, чтобы избежать конфликтов имён и перемещения. Защита восстанавливает плагины, которые отключила сама, и не присваивает себе восстановление, если состояние плагина изменилось извне во время операции.
### Взаимодействие с Paste Image Rename
Плагин временно отключает сторонний плагин `obsidian-paste-image-rename` на время сжатия или перемещения файлов. Настройки для отключения этой защиты нет, потому что сопоставление сжатого вывода с оригиналом зависит от того, что свежие файлы не будут переименованы другим плагином.
Зачем это нужно:
- Paste Image Rename вешает обработчик `vault.on("create")`, который срабатывает на каждое изображение, добавленное в хранилище в пределах ~1 секунды с момента создания. Он всегда обрабатывает файлы с именем, начинающимся на `Pasted image `, и все остальные изображения, если включена его опция «Handle all attachments».
- Когда наш плагин пишет сжатые копии в папку вывода, эти свежие файлы запускают тот обработчик. При активной Markdown-вкладке Paste Image Rename переименовывает только что записанный вывод (это ломает сопоставление «сжатый → оригинал», на которое опирается перемещение) или показывает модалку переименования на каждый файл. Без активной Markdown-вкладки он показывает уведомление `Error: No active file found` на каждый созданный файл — при пакетном прогоне это засыпает интерфейс ошибками.
- В Obsidian нет публичного API, чтобы один плагин попросил другой приостановиться, поэтому временное отключение этого одного плагина — единственный надёжный способ.
Как это сделано безопасно:
- Затрагивается только один известный id `obsidian-paste-image-rename` и только пока идёт операция сжатия или перемещения.
- Плагин всегда восстанавливается потом, с повторами. Защита отслеживает, она ли его отключила, и не присваивает себе восстановление, если состояние плагина изменилось извне во время операции.
- Включение/отключение этого плагина использует внутренний API Obsidian `app.plugins`, так как публичного аналога нет; вызовы feature-detected и мягко обрабатывают ошибки.
### Приватность и внешнее поведение
- **Сеть**: плагин не выполняет runtime-сетевые запросы. PNG/JPEG-кодеки встроены в `main.js`; изображения не загружаются.
- **Телеметрия и реклама**: нет аналитики, телеметрии, crash reporting, tracking, динамической рекламы или механизма самообновления.
- **Аккаунты и платежи**: аккаунт, подписка, лицензионный ключ и оплата не нужны. Funding-ссылка в manifest необязательна и самим плагином не запрашивается.
- **Файлы vault**: плагин читает поддерживаемые изображения, выбранные командами, автоматизацией или allowed roots. Сжатые результаты пишутся в настроенную vault-relative папку; оригиналы заменяются только через документированный move/auto-move flow после создания бэкапов.
- **Локальное состояние**: кэш хранится в папке плагина. Бэкапы кэша и перемещения хранятся в `Vault/.local-image-compress/backups/`.
- **Внешние файлы**: управляемые данные остаются внутри текущего vault. Команды «Открыть папку» только просят ОС показать документированные папки бэкапов и ничего не передают.
- **Другие плагины**: `obsidian-paste-image-rename` может временно отключаться во время сжатия/перемещения, как описано выше, а затем восстанавливается с проверкой ownership.
### Советы
- Разумный диапазон качества: PNG `65-80`, JPEG `75-90`.
- Настройте «Разрешённые корни», если хотите сжимать только определённые папки, например `files/` или `images/`.
- Используйте фоновое сжатие, если в хранилище много несжатых изображений.
### Частые вопросы
**Плагин пишет, что WebAssembly-модули не инициализировались.**
Перезагрузите плагин. Если ошибка повторяется, приложите версию Obsidian, платформу и ошибку из консоли к bug report.
**Где оказываются сжатые файлы?**
По умолчанию в `Compressed`. Для замены оригиналов используйте команду «Переместить сжатые файлы».
**Как считается экономия?**
Экономия точная, когда в кэше есть исходный и выходной размеры. Для несжатых PNG/JPEG плагин использует консервативную оценку с ограниченными коэффициентами; текущие размеры сжатых файлов при необходимости читаются с диска.
**Что такое призрачные записи?**
Записи кэша, которые указывают на удалённые или отсутствующие файлы. Их можно очистить в настройках.
### Диагностика
- Убедитесь, что файлы достаточно большие: слишком маленькие изображения пропускаются.
- Проверьте «Разрешённые корни»: файлы вне этих путей не обрабатываются.
- Если перенос не происходит, убедитесь, что у сжатого файла есть соответствующий оригинал в разрешённом корне.
- Смотрите уведомления приложения и консоль разработчика для логов `Local Image Compress`.
### Метаданные
- ID: `local-image-compress`
- Имя: `Local Image Compress`
- Версия: `1.0.0`
- Минимальная версия приложения: `1.4.0`
- Desktop-only: да
- Репозиторий: `https://github.com/haperone/local-image-compress`
### Лицензия
- Дистрибутив плагина: GPL-3.0-or-later (см. `LICENSE`).
- Плагин включает WebAssembly-код `imagequant`/libimagequant под GPL v3, поэтому распространяемый плагин лицензирован как GPL-3.0-or-later.
- Сторонние кодеки: см. `THIRD_PARTY_NOTICES.md` и точные отслеживаемые тексты в `licenses/`.

54
RELEASE_POLICY.md Normal file
View file

@ -0,0 +1,54 @@
# Release policy
This repository keeps readable TypeScript source in Git and generates the
installed production bundle locally or in CI.
## Source and generated output
- TypeScript source lives in `src-ts`.
- Root `main.js` is generated, ignored, and must not be tracked.
- `npm run build` creates a production-minified root `main.js` for local
Obsidian development.
- `dist-ts/main.js` is also generated and ignored.
- The generated banner points reviewers to the readable repository source;
minification is used for production size, not obfuscation.
## Verification
`npm run test:release`:
1. Runs lint, scanner, smoke, typecheck, manifest, license, and inline WASM
checks against readable source and a review bundle.
2. Builds the production-minified worker and root bundle.
3. Rebuilds production output and requires byte-identical SHA-256 results.
4. Runs `verify:root-ts` to prove root `main.js` equals the generated
production artifact.
5. Recreates `build/` from an explicit four-file allowlist.
The production build has no source map and keeps WASM codecs inline, so users
do not need package dependencies, external binaries, or separate `.wasm`
files.
## Release contract
Future releases use an exact numeric SemVer tag equal to `manifest.json`, for
example `1.0.0`. A `v` prefix is rejected. Historical remote tags are not
rewritten.
GitHub release assets are exactly:
- `manifest.json`
- `main.js`
- `styles.css`
- `versions.json`
The ignored `build/` staging directory is recreated on every release. It must
not contain source workspaces, package metadata, caches, settings, backups,
QA output, or dependencies.
## Version ownership
The current version must agree across `manifest.json`, `versions.json`, root
`package.json`, README metadata, and the release tag. `minAppVersion` remains
`1.4.0` while current API types are used only as a compile-time review
surface.

62
THIRD_PARTY_NOTICES.md Normal file
View file

@ -0,0 +1,62 @@
# Third-Party Notices
This project uses third-party WebAssembly codecs bundled into `main.js`.
Because the distributed plugin bundles `imagequant`/libimagequant, which is
licensed under GPL v3 or later, the plugin distribution is licensed as
GPL-3.0-or-later. See `LICENSE`.
Exact license texts copied from the pinned packages are tracked locally:
- `licenses/Apache-2.0.txt` for the `@jsquash/jpeg` and `@jsquash/png`
JavaScript wrappers.
- `licenses/jpeg-codec.txt` for the bundled libjpeg-turbo codec.
- `licenses/png-codec.txt` for the bundled PNG codec.
- `LICENSE` for `imagequant`/libimagequant and this GPL-3.0-or-later
distribution.
`npm run test:release` verifies these copies byte-for-byte against the pinned
installed packages and validates the embedded WASM hashes.
## imagequant / libimagequant
- Package: `imagequant`
- Source: https://github.com/valterkraemer/imagequant-wasm
- Upstream codec: https://github.com/ImageOptim/libimagequant
- License: GPL v3
The PNG lossy quantization path uses the `imagequant` WASM binding so the
plugin can preserve the previous pngquant-style quality range and quality-fail
semantics without shipping native binaries.
Full license: https://www.gnu.org/licenses/gpl-3.0.txt
## @jsquash/jpeg / mozjpeg
- Package: `@jsquash/jpeg`
- Pinned version: `1.6.0`
- Source: https://github.com/jamsinclair/jSquash
- Upstream codec: https://github.com/mozilla/mozjpeg
- License: Apache-2.0 for the package wrapper; the bundled libjpeg-turbo codec
uses IJG, Modified BSD, and zlib terms.
Required attribution: This software is based in part on the work of the
Independent JPEG Group.
Exact texts: `licenses/Apache-2.0.txt` and `licenses/jpeg-codec.txt`.
## @jsquash/png
- Package: `@jsquash/png`
- Pinned version: `3.1.1`
- Source: https://github.com/jamsinclair/jSquash
- License: Apache-2.0 for the package wrapper; BSD-3-Clause for the bundled
codec.
Exact texts: `licenses/Apache-2.0.txt` and `licenses/png-codec.txt`.
## imagequant / libimagequant integrity
- Package version: `0.1.2`.
- Exact GPL-3.0 text: `LICENSE`.
- Embedded codec hashes: `wasm-hashes.json`.
The release artifact does not include native compressor executables or
`node_modules/pngquant-bin/vendor` / `node_modules/mozjpeg/vendor` binaries.

40
eslint.config.mjs Normal file
View file

@ -0,0 +1,40 @@
import tsParser from "@typescript-eslint/parser";
import tsPlugin from "@typescript-eslint/eslint-plugin";
export default [
{
ignores: [
"dist/**",
"dist-ts/**",
"node_modules/**",
"qa-backups/**",
"qa-screenshots/**",
"src-ts/.claude/**",
"**/.claude/**"
]
},
{
files: ["src-ts/**/*.ts"],
languageOptions: {
parser: tsParser,
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: import.meta.dirname
}
},
plugins: {
"@typescript-eslint": tsPlugin
},
rules: {
"@typescript-eslint/no-floating-promises": ["error", { ignoreVoid: false }],
"no-empty": ["error", { allowEmptyCatch: false }],
"no-restricted-syntax": [
"error",
{
selector: "CallExpression[callee.object.name='console'][callee.property.name='log']",
message: "console.log is forbidden in production code."
}
]
}
}
];

View file

@ -0,0 +1,43 @@
// Blocking mirror of the current Obsidian community-plugin submission scanner.
import tsParser from "@typescript-eslint/parser";
import tseslint from "typescript-eslint";
import obsidianmd from "eslint-plugin-obsidianmd";
const sourceFiles = ["src-ts/**/*.ts"];
export default [
{
ignores: [
"node_modules/**",
"dist/**",
"dist-ts/**",
"qa-backups/**",
"qa-screenshots/**",
"**/.claude/**",
"**/.supergoal/**",
"*.mjs"
]
},
...tseslint.configs.recommendedTypeChecked.map((config) => ({
...config,
files: sourceFiles
})),
...obsidianmd.configs.recommendedWithLocalesEn,
{
files: sourceFiles,
languageOptions: {
parser: tsParser,
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: import.meta.dirname,
sourceType: "module"
}
}
},
{
files: ["src-ts/i18n.ts"],
rules: {
"obsidianmd/ui/sentence-case-locale-module": "error"
}
}
];

201
licenses/Apache-2.0.txt Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [2023] jamsinclair
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

132
licenses/jpeg-codec.txt Normal file
View file

@ -0,0 +1,132 @@
libjpeg-turbo Licenses
======================
libjpeg-turbo is covered by three compatible BSD-style open source licenses:
- The IJG (Independent JPEG Group) License, which is listed in
[README.ijg](README.ijg)
This license applies to the libjpeg API library and associated programs
(any code inherited from libjpeg, and any modifications to that code.)
- The Modified (3-clause) BSD License, which is listed below
This license covers the TurboJPEG API library and associated programs, as
well as the build system.
- The [zlib License](https://opensource.org/licenses/Zlib)
This license is a subset of the other two, and it covers the libjpeg-turbo
SIMD extensions.
Complying with the libjpeg-turbo Licenses
=========================================
This section provides a roll-up of the libjpeg-turbo licensing terms, to the
best of our understanding.
1. If you are distributing a modified version of the libjpeg-turbo source,
then:
1. You cannot alter or remove any existing copyright or license notices
from the source.
**Origin**
- Clause 1 of the IJG License
- Clause 1 of the Modified BSD License
- Clauses 1 and 3 of the zlib License
2. You must add your own copyright notice to the header of each source
file you modified, so others can tell that you modified that file (if
there is not an existing copyright header in that file, then you can
simply add a notice stating that you modified the file.)
**Origin**
- Clause 1 of the IJG License
- Clause 2 of the zlib License
3. You must include the IJG README file, and you must not alter any of the
copyright or license text in that file.
**Origin**
- Clause 1 of the IJG License
2. If you are distributing only libjpeg-turbo binaries without the source, or
if you are distributing an application that statically links with
libjpeg-turbo, then:
1. Your product documentation must include a message stating:
This software is based in part on the work of the Independent JPEG
Group.
**Origin**
- Clause 2 of the IJG license
2. If your binary distribution includes or uses the TurboJPEG API, then
your product documentation must include the text of the Modified BSD
License (see below.)
**Origin**
- Clause 2 of the Modified BSD License
3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
contributors thereof in advertising, publicity, etc.
**Origin**
- IJG License
- Clause 3 of the Modified BSD License
4. The IJG and The libjpeg-turbo Project do not warrant libjpeg-turbo to be
free of defects, nor do we accept any liability for undesirable
consequences resulting from your use of the software.
**Origin**
- IJG License
- Modified BSD License
- zlib License
The Modified (3-clause) BSD License
===================================
Copyright (C)2009-2020 D. R. Commander. All Rights Reserved.
Copyright (C)2015 Viktor Szathmáry. All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the libjpeg-turbo Project nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Why Three Licenses?
===================
The zlib License could have been used instead of the Modified (3-clause) BSD
License, and since the IJG License effectively subsumes the distribution
conditions of the zlib License, this would have effectively placed
libjpeg-turbo binary distributions under the IJG License. However, the IJG
License specifically refers to the Independent JPEG Group and does not extend
attribution and endorsement protections to other entities. Thus, it was
desirable to choose a license that granted us the same protections for new code
that were granted to the IJG for code derived from their software.

29
licenses/png-codec.txt Normal file
View file

@ -0,0 +1,29 @@
Copyright (c) 2010, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

11
manifest.json Normal file
View file

@ -0,0 +1,11 @@
{
"id": "local-image-compress",
"name": "Local Image Compress",
"version": "1.0.0",
"minAppVersion": "1.4.0",
"description": "Local PNG/JPEG compression without cloud APIs.",
"author": "Haperone",
"authorUrl": "https://github.com/haperone",
"fundingUrl": "https://buymeacoffee.com/haperone",
"isDesktopOnly": true
}

5338
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

69
package.json Normal file
View file

@ -0,0 +1,69 @@
{
"name": "obsidian-local-image-compress",
"version": "1.0.0",
"private": true,
"description": "Desktop local PNG/JPEG compression for Obsidian using bundled WASM codecs, no cloud.",
"type": "commonjs",
"main": "main.js",
"files": [
"manifest.json",
"main.js",
"styles.css",
"versions.json"
],
"scripts": {
"lint": "node scripts/class-wide-gates.js",
"audit:policy": "node scripts/audit-policy.js",
"audit:policy:bundle": "node scripts/audit-policy.js --require-bundle",
"lint:eslint": "eslint src-ts/",
"lint:obsidian": "node scripts/lint-obsidian.js",
"build": "npm run build:root",
"build:ts": "node scripts/build-ts.js",
"smoke:ts": "node scripts/smoke-ts.js",
"typecheck": "tsc --noEmit",
"validate:manifest": "node scripts/validate-manifest.js",
"validate:license": "node scripts/validate-license.js",
"validate:wasm": "node scripts/validate-wasm.js",
"qa:runtime": "node scripts/run-runtime-qa.js",
"test:ts": "npm run build:ts && npm run smoke:ts",
"verify:root-ts": "node scripts/verify-root-ts.js",
"verify:release": "node scripts/verify-release.js",
"prepare:release": "node scripts/prepare-release.js",
"build:root": "node scripts/build-root.js",
"test:release": "npm test && npm run build:root && npm run audit:policy:bundle && npm run verify:release && npm run verify:root-ts",
"test": "npm run lint && npm run audit:policy && npm run lint:eslint && npm run lint:obsidian && npm run test:ts && npm run typecheck && npm run validate:manifest && npm run validate:license && npm run validate:wasm",
"release": "node -e \"process.stdout.write('Release tag must be exact numeric SemVer: ' + require('./package.json').version + '\\n')\""
},
"keywords": [
"obsidian",
"plugin",
"images",
"compression",
"png",
"jpeg"
],
"author": "Haperone",
"license": "GPL-3.0-or-later",
"repository": {
"type": "git",
"url": "git+https://github.com/haperone/local-image-compress.git"
},
"bugs": {
"url": "https://github.com/haperone/local-image-compress/issues"
},
"homepage": "https://github.com/haperone/local-image-compress#readme",
"devDependencies": {
"@jsquash/jpeg": "1.6.0",
"@jsquash/png": "3.1.1",
"@types/node": "25.7.0",
"@typescript-eslint/eslint-plugin": "^8.60.0",
"@typescript-eslint/parser": "^8.60.0",
"esbuild": "0.25.12",
"eslint": "^10.4.0",
"eslint-plugin-obsidianmd": "0.3.0",
"imagequant": "0.1.2",
"obsidian": "1.13.0",
"typescript": "6.0.3",
"typescript-eslint": "^8.60.1"
}
}

193
scripts/audit-policy.js Normal file
View file

@ -0,0 +1,193 @@
"use strict";
const fs = require("fs");
const path = require("path");
const sourceRoot = path.resolve(__dirname, "..");
const repoRoot = sourceRoot;
const tsRoot = path.join(sourceRoot, "src-ts");
const requireBundle = process.argv.includes("--require-bundle");
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
function collectTypeScriptFiles(directory) {
const files = [];
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
files.push(...collectTypeScriptFiles(entryPath));
} else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".d.ts")) {
files.push(entryPath);
}
}
return files;
}
function relativeSourcePath(filePath) {
return path.relative(sourceRoot, filePath).replace(/\\/g, "/");
}
function matchingFiles(files, pattern) {
return files
.filter((file) => pattern.test(file.source))
.map((file) => file.relativePath)
.sort();
}
function countMatches(source, pattern) {
return (source.match(pattern) || []).length;
}
const files = collectTypeScriptFiles(tsRoot).map((filePath) => ({
filePath,
relativePath: relativeSourcePath(filePath),
source: fs.readFileSync(filePath, "utf8")
}));
const combinedSource = files.map((file) => file.source).join("\n");
const packageJson = JSON.parse(fs.readFileSync(path.join(sourceRoot, "package.json"), "utf8"));
const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, "manifest.json"), "utf8"));
const readme = fs.readFileSync(path.join(repoRoot, "README.md"), "utf8");
const readmeRu = fs.readFileSync(path.join(repoRoot, "README.ru.md"), "utf8");
const mainBundlePath = path.join(repoRoot, "main.js");
const mainBundleExists = fs.existsSync(mainBundlePath);
assert(!requireBundle || mainBundleExists, "Production main.js is required after build");
const mainBundle = mainBundleExists ? fs.readFileSync(mainBundlePath, "utf8") : "";
const cacheSource = fs.readFileSync(path.join(tsRoot, "cache.ts"), "utf8");
const i18nSource = fs.readFileSync(path.join(tsRoot, "i18n.ts"), "utf8");
const utilsSource = fs.readFileSync(path.join(tsRoot, "utils.ts"), "utf8");
const pluginSource = fs.readFileSync(path.join(tsRoot, "plugin.ts"), "utf8");
const compressionWorkerSource = fs.readFileSync(path.join(tsRoot, "compression-worker.ts"), "utf8");
const workerSlotSource = fs.readFileSync(path.join(tsRoot, "worker-slot.ts"), "utf8");
const forbiddenSourcePatterns = [
[/\bfetch\s*\(/, "fetch"],
[/\brequestUrl\s*\(/, "requestUrl"],
[/\bXMLHttpRequest\b/, "XMLHttpRequest"],
[/\bWebSocket\b/, "WebSocket"],
[/\bEventSource\b/, "EventSource"],
[/\bsendBeacon\s*\(/, "sendBeacon"],
[/\b(?:import|require)\b[^\n]*(?:node:)?(?:http|https|net|dns)["']/, "network module"],
[/\b(?:innerHTML|outerHTML|insertAdjacentHTML|document\.write|document\.writeln)\b/, "raw HTML sink"],
[/\beval\s*\(|new\s+Function\b|set(?:Timeout|Interval)\s*\(\s*["']/, "string-to-code execution"],
[/setAttribute\s*\(\s*["']on/i, "string event handler"],
[/\brequire\s*\(\s*["']child_process["']\s*\)/, "child_process"],
[/\b(?:localStorage|sessionStorage)\b/, "web storage"],
[/\bprocess\.cwd\s*\(/, "ambient working-directory fallback"],
[/\b(?:api[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|refresh[_-]?token|BEGIN (?:RSA|OPENSSH|EC) PRIVATE KEY)\b/i, "secret material"]
];
for (const [pattern, label] of forbiddenSourcePatterns) {
assert(!pattern.test(combinedSource), `Policy audit found ${label} in application TypeScript`);
}
const dependencyNames = Object.keys(packageJson.dependencies || {});
assert(dependencyNames.length === 0, `Runtime npm dependencies must stay bundled and explicit; found ${dependencyNames.join(", ")}`);
for (const [name, version] of Object.entries({
"@jsquash/jpeg": "1.6.0",
"@jsquash/png": "3.1.1",
imagequant: "0.1.2"
})) {
assert(packageJson.devDependencies?.[name] === version, `${name} must stay pinned to ${version}`);
}
assert(manifest.isDesktopOnly === true, "Node/Electron plugin must remain desktop-only");
assert(/^https:\/\/buymeacoffee\.com\//.test(manifest.fundingUrl || ""), "fundingUrl must remain an optional support link");
assert(!combinedSource.includes(manifest.fundingUrl), "Runtime source must not contact or gate on fundingUrl");
for (const token of [
"Network",
"Telemetry and ads",
"Accounts and payments",
"Vault files",
"Local state",
"External files",
"Other plugins"
]) {
assert(readme.includes(token), `README.md is missing policy disclosure: ${token}`);
}
for (const token of [
"Сеть",
"Телеметрия и реклама",
"Аккаунты и платежи",
"Файлы vault",
"Локальное состояние",
"Внешние файлы",
"Другие плагины"
]) {
assert(readmeRu.includes(token), `README.ru.md is missing policy disclosure: ${token}`);
}
const expectedFsBoundaryFiles = [
"src-ts/cache.ts",
"src-ts/i18n.ts",
"src-ts/move-service.ts",
"src-ts/plugin.ts",
"src-ts/savings-calculator.ts",
"src-ts/services/cache-backups-view.ts",
"src-ts/services/migration-runner.ts",
"src-ts/settings-tab.ts",
"src-ts/utils.ts"
];
const fsBoundaryFiles = matchingFiles(files, /import\s+\*\s+as\s+fs\w*\s+from\s+["']fs["']/);
assert(JSON.stringify(fsBoundaryFiles) === JSON.stringify(expectedFsBoundaryFiles), `Raw fs boundary inventory changed: ${fsBoundaryFiles.join(", ")}`);
const electronBoundaryFiles = matchingFiles(files, /from\s+["']electron["']/);
assert(JSON.stringify(electronBoundaryFiles) === JSON.stringify(["src-ts/utils.ts"]), `Electron boundary inventory changed: ${electronBoundaryFiles.join(", ")}`);
assert(!/getVaultBasePathFromAdapter\([^)]*process\.cwd/.test(utilsSource), "Vault base-path helper still defaults to process.cwd()");
assert(utilsSource.includes("refusing filesystem access outside the vault"), "Vault base-path helper must fail closed");
assert(cacheSource.includes("isSafeVaultRelativePath(vaultRelativePath)") && !cacheSource.includes("return rawPath;"), "Cache raw filesystem resolution must reject outside-vault paths");
assert(
i18nSource.includes("if (!pluginDir)") && i18nSource.includes("return {};"),
"External language loading must skip filesystem access when the vault plugin directory is unavailable"
);
const onloadSource = pluginSource.match(/override onload\(\): void \{[\s\S]*?\n \}/)?.[0] || "";
assert(onloadSource.includes("onLayoutReady") && !/\bawait\b|getFiles\(|loadData\(|readFile/.test(onloadSource), "onload must remain registration-only");
const expectedFullVaultScans = [
"src-ts/image-index.ts",
"src-ts/image-scanner.ts",
"src-ts/move-service.ts",
"src-ts/move-service.ts",
"src-ts/plugin.ts",
"src-ts/plugin.ts"
];
const fullVaultScans = [];
for (const file of files) {
for (const match of file.source.matchAll(/\.vault\.getFiles\(\)/g)) {
void match;
fullVaultScans.push(file.relativePath);
}
}
fullVaultScans.sort();
assert(JSON.stringify(fullVaultScans) === JSON.stringify(expectedFullVaultScans), `Full-vault scan inventory changed: ${fullVaultScans.join(", ")}`);
assert(compressionWorkerSource.includes("initJpegDecode(getCachedWasmModule") && compressionWorkerSource.includes("initPngDecode(message.wasm.png)"), "Codec initialization must use transferred inline WASM");
assert(
workerSlotSource.includes("wasmBytes")
&& workerSlotSource.includes('worker.postMessage({ id, type: "init", wasm }, [')
&& ["wasm.jpegDecode", "wasm.jpegEncode", "wasm.png", "wasm.imagequant"].every((token) => workerSlotSource.includes(token)),
"Worker must transfer bundled WASM bytes explicitly"
);
if (mainBundleExists) {
assert(countMatches(mainBundle, /\brequire\(["'](?:node:)?https?["']\)/g) === 0, "Production bundle imports a network module");
assert(countMatches(mainBundle, /\b(?:WebSocket|EventSource|sendBeacon)\b/g) === 0, "Production bundle contains an unreviewed network API");
assert(countMatches(mainBundle, /\b(?:innerHTML|outerHTML|insertAdjacentHTML)\b/g) === 0, "Production bundle contains a raw HTML sink");
assert(countMatches(mainBundle, /\beval\s*\(|new Function/g) === 0, "Production bundle contains eval-like execution");
assert(countMatches(mainBundle, /\bfetch\s*\(/g) === 5 && countMatches(mainBundle, /\bXMLHttpRequest\b/g) === 6, "Dormant pinned codec fallback inventory changed");
}
process.stdout.write([
"Policy audit passed.",
`TypeScript files: ${files.length}`,
`Raw fs boundaries: ${fsBoundaryFiles.length}`,
`Full-vault scans: ${fullVaultScans.length}`,
"Application network/HTML/eval/secret findings: 0",
`Production bundle policy check: ${mainBundleExists ? "passed" : "skipped until build"}`,
...(mainBundleExists ? [
"Production network modules/unsafe sinks: 0",
"Dormant vendor fallbacks: fetch=5, XMLHttpRequest=6"
] : [])
].join("\n") + "\n");

52
scripts/build-root.js Normal file
View file

@ -0,0 +1,52 @@
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { spawnSync } = require("child_process");
const root = path.resolve(__dirname, "..");
const rootMainPath = path.join(root, "main.js");
const generatedPath = path.join(root, "dist-ts", "main.js");
const build = spawnSync(process.execPath, [path.join(root, "scripts", "build-ts.js"), "--production"], {
cwd: root,
stdio: "inherit",
windowsHide: true
});
if (build.status !== 0) {
process.exit(build.status || 1);
}
function sha256(buffer) {
return crypto.createHash("sha256").update(buffer).digest("hex").toUpperCase();
}
let updateMethod = "copyFileSync";
try {
fs.copyFileSync(generatedPath, rootMainPath);
} catch (error) {
if (error && error.code === "EPERM") {
console.warn("[build-root] copyFileSync failed with EPERM; trying writeFileSync fallback. Close Obsidian if main.js is locked.");
try {
fs.writeFileSync(rootMainPath, fs.readFileSync(generatedPath));
updateMethod = "writeFileSync fallback";
} catch (writeError) {
console.error("[build-root] copyFileSync and writeFileSync fallback both failed. Close Obsidian and retry.");
throw writeError;
}
} else {
throw error;
}
}
const generated = fs.readFileSync(generatedPath);
const rootMain = fs.readFileSync(rootMainPath);
const generatedHash = sha256(generated);
const rootMainHash = sha256(rootMain);
if (generatedHash !== rootMainHash) {
throw new Error(`build-root post-copy SHA mismatch: dist-ts=${generatedHash}, root=${rootMainHash}`);
}
console.log(`Updated ${path.relative(root, rootMainPath)} via ${updateMethod} (${rootMain.length} bytes, SHA-256 ${rootMainHash})`);

133
scripts/build-ts.js Normal file
View file

@ -0,0 +1,133 @@
"use strict";
const fs = require("fs");
const path = require("path");
const childProcess = require("child_process");
const esbuild = require("esbuild");
const root = path.resolve(__dirname, "..");
const esbuildCli = require.resolve("esbuild/bin/esbuild");
const production = process.argv.includes("--production");
const generatedBanner = "/* GENERATED/BUNDLED FILE. Review source at https://github.com/haperone/local-image-compress */";
function runEsbuildCli(args) {
childProcess.execFileSync(process.execPath, [esbuildCli, ...args], {
cwd: root,
stdio: "inherit"
});
}
function buildWithCliFallback() {
const tempDir = path.join(root, "dist-ts", ".build");
const workerBundlePath = path.join(tempDir, "compression-worker.js");
const workerSourceModulePath = path.join(tempDir, "compression-worker-source.js");
fs.mkdirSync(tempDir, { recursive: true });
try {
runEsbuildCli([
path.join("src-ts", "compression-worker.ts"),
"--bundle",
"--platform=browser",
"--target=es2020",
"--format=iife",
"--loader:.wasm=binary",
`--outfile=${workerBundlePath}`,
...(production ? ["--minify"] : []),
"--log-level=silent"
]);
const compressionWorkerSource = fs.readFileSync(workerBundlePath, "utf8");
fs.writeFileSync(workerSourceModulePath, `export default ${JSON.stringify(compressionWorkerSource)};\n`);
runEsbuildCli([
path.join("src-ts", "main.ts"),
"--bundle",
"--platform=node",
"--target=es2020",
"--format=cjs",
"--loader:.wasm=binary",
"--external:obsidian",
"--external:electron",
`--alias:virtual:compression-worker=./${path.relative(root, workerSourceModulePath).replace(/\\/g, "/")}`,
`--outfile=${path.join(root, "dist-ts", "main.js")}`,
`--banner:js=${generatedBanner}`,
...(production ? ["--minify"] : []),
"--log-level=info"
]);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}
async function buildWithApi() {
const workerResult = await esbuild.build({
entryPoints: [path.join(root, "src-ts", "compression-worker.ts")],
bundle: true,
platform: "browser",
target: "es2020",
format: "iife",
write: false,
sourcemap: false,
minify: production,
loader: {
".wasm": "binary"
},
logLevel: "silent"
});
const compressionWorkerSource = Buffer.from(workerResult.outputFiles[0].contents).toString("utf8");
await esbuild.build({
entryPoints: [path.join(root, "src-ts", "main.ts")],
outfile: path.join(root, "dist-ts", "main.js"),
bundle: true,
platform: "node",
target: "es2020",
format: "cjs",
sourcemap: false,
minify: production,
banner: {
js: generatedBanner
},
loader: {
".wasm": "binary"
},
external: [
"obsidian",
"electron"
],
plugins: [
{
name: "compression-worker-source",
setup(build) {
build.onResolve({ filter: /^virtual:compression-worker$/ }, (args) => ({
path: args.path,
namespace: "compression-worker-source"
}));
build.onLoad({ filter: /.*/, namespace: "compression-worker-source" }, () => ({
contents: `export default ${JSON.stringify(compressionWorkerSource)};`,
loader: "js"
}));
}
}
],
logLevel: "info"
});
}
async function main() {
process.stdout.write(`Building ${production ? "production minified" : "review"} bundle...\n`);
try {
await buildWithApi();
} catch (error) {
if (error?.code !== "EPERM") {
throw error;
}
console.warn("esbuild JS API spawn failed with EPERM; falling back to esbuild CLI.");
buildWithCliFallback();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});

265
scripts/class-wide-gates.js Normal file
View file

@ -0,0 +1,265 @@
"use strict";
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const sourceRoot = path.join(root, "src-ts");
const syncFsMethods = [
"accessSync",
"appendFileSync",
"chmodSync",
"chownSync",
"closeSync",
"copyFileSync",
"existsSync",
"lstatSync",
"mkdirSync",
"openSync",
"readFileSync",
"readdirSync",
"readlinkSync",
"realpathSync",
"renameSync",
"rmSync",
"rmdirSync",
"statSync",
"symlinkSync",
"unlinkSync",
"writeFileSync"
];
const syncFsPattern = new RegExp(`\\bfs\\d*\\.(${syncFsMethods.join("|")})\\s*\\(`);
const lineRules = [
{
id: "sync-fs",
pattern: syncFsPattern,
message: "Sync fs is forbidden in src-ts; use fs.promises.* or document a cold-path exception outside this gate."
},
{
id: "console-log",
pattern: /\bconsole\.log\s*\(/,
message: "console.log is forbidden in production code; use a logger/debug path or remove it."
},
{
id: "empty-promise-catch",
pattern: /\.catch\(\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>\s*\{\s*\}\s*\)/,
message: "Empty promise rejection handlers hide async failures."
},
{
id: "void-promise",
pattern: /^\s*void\s+(?:this\.|[A-Za-z_$][\w$]*\.|[A-Za-z_$][\w$]*\(|Promise\.)/,
message: "Explicitly discarded promises must be awaited or have an explained error path."
},
{
id: "explicit-any",
pattern: /(?::\s*any\b|\bas\s+any\b|\bis\s+any\b|\bany\s*\[\]|<[^>\n]*\bany\b[^>\n]*>)/,
message: "Explicit any is forbidden in src-ts; use a domain type, unknown with narrowing, or a narrow structural boundary type."
}
];
const syncFsExceptionScopes = [
{
file: "src-ts/cache.ts",
startPattern: /^\s*removeStaleCacheLockSync\(/,
endPattern: /^\s*async acquireCacheWriteLock\(/,
reason: "Synchronous cache lock cleanup is isolated to the unload durability path and explicit recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*acquireCacheWriteLockSync\(/,
endPattern: /^\s*async releaseCacheWriteLock\(/,
reason: "Synchronous cache lock acquisition is isolated to the unload durability path and explicit recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*releaseCacheWriteLockSync\(/,
endPattern: /^\s*mergeCacheEntries\(/,
reason: "Synchronous cache lock release is isolated to the unload durability path and explicit recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*mergeDiskCacheEntriesSync\(/,
endPattern: /^\s*createBrokenCacheCopySync\(/,
reason: "Synchronous disk merge is isolated to the unload durability path and explicit recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*createBrokenCacheCopySync\(/,
endPattern: /^\s*async createBrokenCacheCopy\(/,
reason: "Synchronous corrupt-cache recovery is retained only for explicit recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*writeCacheFileSyncAtomic\(/,
endPattern: /^\s*async writeCacheFileAtomic\(/,
reason: "Synchronous atomic write is required only to flush pending cache state during unload and by recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*loadCacheSync\(/,
endPattern: /^\s*async loadCache\(/,
reason: "Legacy synchronous cache load is test-only; normal startup always awaits async loadCache."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*createBackupSync\(/,
endPattern: /^\s*async cleanupOldBackups\(/,
reason: "Synchronous backup helper is retained only for explicit recovery tests."
},
{
file: "src-ts/cache.ts",
startPattern: /^\s*cleanupRetainedFilesSync\(/,
endPattern: /^\s*\/\/ Enhanced restore-from-backup method/,
reason: "Synchronous retention cleanup is retained only for explicit recovery tests."
},
{
file: "src-ts/i18n.ts",
startPattern: /^export function getMergedDict\(/,
endPattern: /^export function getUserLang\(/,
reason: "Translation lookup is synchronous; optional external locale probing is cached and cold."
}
];
function findSyncFsException(relativePath, lineIndex, lines) {
for (const scope of syncFsExceptionScopes) {
if (scope.file !== relativePath) {
continue;
}
const startIndex = lines.findIndex((line) => scope.startPattern.test(line));
if (startIndex === -1 || lineIndex < startIndex) {
continue;
}
const endOffset = lines.slice(startIndex + 1).findIndex((line) => scope.endPattern.test(line));
const endIndex = endOffset === -1 ? lines.length : startIndex + 1 + endOffset;
if (lineIndex < endIndex) {
return scope;
}
}
return null;
}
function collectFiles(target) {
const stat = fs.statSync(target);
if (stat.isFile()) {
return target.endsWith(".ts") && !target.endsWith(".d.ts") ? [target] : [];
}
const files = [];
for (const entry of fs.readdirSync(target, { withFileTypes: true })) {
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist" || entry.name === "dist-ts") {
continue;
}
const entryPath = path.join(target, entry.name);
if (entry.isDirectory()) {
files.push(...collectFiles(entryPath));
} else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".d.ts")) {
files.push(entryPath);
}
}
return files;
}
function parseTargets(argv) {
const targets = argv.filter((arg) => arg !== "--quiet");
if (targets.length === 0) {
return [sourceRoot];
}
return targets.map((target) => path.resolve(root, target));
}
function toRelative(filePath) {
return path.relative(root, filePath).replace(/\\/g, "/");
}
function getLineNumber(source, offset) {
let lineNumber = 1;
for (let index = 0; index < offset; index += 1) {
if (source.charCodeAt(index) === 10) {
lineNumber += 1;
}
}
return lineNumber;
}
function addEmptyCatchFindings(source, relativePath, findings) {
const emptyCatchPattern = /\bcatch\s*(?:\([^)]*\)\s*)?\{\s*\}/g;
let match;
while ((match = emptyCatchPattern.exec(source)) !== null) {
findings.push({
rule: "empty-catch",
file: relativePath,
line: getLineNumber(source, match.index),
text: match[0].replace(/\s+/g, " ").trim(),
message: "Empty catch blocks hide cleanup and lifecycle failures."
});
}
}
if (process.argv.includes("--self-test")) {
const selfTestFindings = [];
addEmptyCatchFindings("function demo() {\n try {\n work();\n } catch (error) {\n }\n}\n", "self-test.ts", selfTestFindings);
if (!selfTestFindings.some((finding) => finding.rule === "empty-catch" && finding.line === 4)) {
console.error("Class-wide gates self-test failed: multiline empty catch was not detected.");
process.exit(1);
}
console.log("Class-wide gates self-test passed.");
process.exit(0);
}
const findings = [];
for (const target of parseTargets(process.argv.slice(2))) {
if (!fs.existsSync(target)) {
findings.push({
rule: "missing-target",
file: toRelative(target),
line: 0,
text: "",
message: "Lint target does not exist."
});
continue;
}
for (const filePath of collectFiles(target)) {
const relativePath = toRelative(filePath);
const fileSource = fs.readFileSync(filePath, "utf8");
const lines = fileSource.split(/\r?\n/);
addEmptyCatchFindings(fileSource, relativePath, findings);
lines.forEach((line, index) => {
for (const rule of lineRules) {
if (rule.pattern.test(line)) {
if (rule.id === "sync-fs" && findSyncFsException(relativePath, index, lines)) {
continue;
}
findings.push({
rule: rule.id,
file: relativePath,
line: index + 1,
text: line.trim(),
message: rule.message
});
}
}
});
}
}
if (findings.length === 0) {
console.log("Class-wide gates passed.");
process.exit(0);
}
console.error(`Class-wide gates failed with ${findings.length} finding(s).`);
for (const finding of findings) {
const location = finding.line > 0 ? `${finding.file}:${finding.line}` : finding.file;
console.error(`\n[${finding.rule}] ${location}`);
console.error(` ${finding.message}`);
if (finding.text) {
console.error(` ${finding.text}`);
}
}
process.exit(1);

30
scripts/lint-obsidian.js Normal file
View file

@ -0,0 +1,30 @@
const path = require("path");
async function main() {
const repositoryRoot = path.resolve(__dirname, "..");
process.chdir(repositoryRoot);
const { ESLint } = require("eslint");
const eslint = new ESLint({
cwd: repositoryRoot,
overrideConfigFile: path.join(repositoryRoot, "eslint.obsidian.config.mjs"),
fix: process.argv.includes("--fix")
});
const results = await eslint.lintFiles(["src-ts/"]);
await ESLint.outputFixes(results);
const formatter = await eslint.loadFormatter("stylish");
const output = formatter.format(results);
if (output) {
process.stdout.write(output);
}
const errorCount = results.reduce((sum, result) => sum + result.errorCount, 0);
const warningCount = results.reduce((sum, result) => sum + result.warningCount, 0);
if (errorCount === 0 && warningCount === 0) {
process.stdout.write(`Obsidian lint passed: ${results.length} files, 0 errors, 0 warnings.\n`);
}
process.exitCode = errorCount === 0 && warningCount === 0 ? 0 : 1;
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -0,0 +1,27 @@
"use strict";
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const buildDir = path.join(root, "build");
const releaseFiles = ["manifest.json", "main.js", "styles.css", "versions.json"];
fs.rmSync(buildDir, { recursive: true, force: true });
fs.mkdirSync(buildDir, { recursive: true });
for (const fileName of releaseFiles) {
const sourcePath = path.join(root, fileName);
if (!fs.existsSync(sourcePath)) {
throw new Error(`Release file is missing: ${fileName}`);
}
fs.copyFileSync(sourcePath, path.join(buildDir, fileName));
}
const stagedFiles = fs.readdirSync(buildDir).sort();
const expectedFiles = [...releaseFiles].sort();
if (JSON.stringify(stagedFiles) !== JSON.stringify(expectedFiles)) {
throw new Error(`Unexpected release contents: ${stagedFiles.join(", ")}`);
}
process.stdout.write(`Prepared release files: ${stagedFiles.join(", ")}\n`);

226
scripts/run-runtime-qa.js Normal file
View file

@ -0,0 +1,226 @@
"use strict";
const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");
const pluginId = "local-image-compress";
const sourceRoot = path.resolve(__dirname, "..");
const repoRoot = sourceRoot;
const runnerPath = path.join(__dirname, "runtime-qa.js");
const reportDir = path.join(repoRoot, "qa-backups");
const dataJsonPath = path.join(repoRoot, "data.json");
const preQaSettingsBackupPath = path.join(reportDir, "pre-qa-data-backup.json");
const QA_STATE_MARKER = "QA-LIC-Runtime-";
const cliPath = process.env.OBSIDIAN_CLI || (
process.platform === "win32" ? "C:\\Program Files\\Obsidian\\Obsidian.com" : "obsidian"
);
const args = new Set(process.argv.slice(2));
const skipReload = args.has("--skip-reload");
const skipDevErrors = args.has("--skip-dev-errors");
function printHelp() {
console.log([
"Usage: npm run qa:runtime [-- --skip-reload] [-- --skip-dev-errors]",
"",
"Runs scripts/runtime-qa.js inside a live Obsidian instance.",
"Set OBSIDIAN_CLI to override the Obsidian CLI executable path."
].join("\n"));
}
function timestampForFile() {
return new Date().toISOString().replace(/[:.]/g, "-").replace(/Z$/, "");
}
function runObsidianCli(cliArgs, description, options = {}) {
const result = spawnSync(cliPath, cliArgs, {
cwd: repoRoot,
encoding: "utf8",
windowsHide: true,
maxBuffer: 64 * 1024 * 1024
});
if (result.error) {
throw new Error(`Failed to run Obsidian CLI for ${description}: ${result.error.message}\nCLI: ${cliPath}`);
}
if (result.status !== 0 && !options.allowFailure) {
throw new Error([
`Obsidian CLI failed during ${description} with exit ${result.status}.`,
result.stdout ? `stdout:\n${result.stdout}` : "",
result.stderr ? `stderr:\n${result.stderr}` : ""
].filter(Boolean).join("\n"));
}
return result;
}
function extractEvalPayload(stdout) {
const markerIndex = stdout.lastIndexOf("=>");
if (markerIndex === -1) {
throw new Error(`Obsidian eval output did not contain a return marker.\nOutput:\n${stdout}`);
}
const payload = stdout.slice(markerIndex + 2).trim();
if (!payload) {
throw new Error("Obsidian eval return marker was empty.");
}
try {
const parsed = JSON.parse(payload);
return typeof parsed === "string" ? parsed : JSON.stringify(parsed);
} catch (error) {
const firstBrace = payload.indexOf("{");
const lastBrace = payload.lastIndexOf("}");
if (firstBrace !== -1 && lastBrace > firstBrace) {
return payload.slice(firstBrace, lastBrace + 1);
}
throw error;
}
}
function parseRuntimeReport(stdout) {
const reportJson = extractEvalPayload(stdout);
try {
return JSON.parse(reportJson);
} catch (error) {
throw new Error(`Could not parse runtime QA report: ${error.message}\nPayload:\n${reportJson.slice(0, 4000)}`);
}
}
function hasPluginRelevantDevErrors(output) {
return /plugin:local-image-compress|local-image-compress|tinyLocal|Tiny Local/i.test(output);
}
function writeTextReport(prefix, text) {
const filePath = path.join(reportDir, `${prefix}-${timestampForFile()}.txt`);
fs.writeFileSync(filePath, text);
return filePath;
}
function readJsonSafe(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch (error) {
return null;
}
}
// Runtime QA overwrites the real plugin data.json with isolated test settings (a "QA-LIC-Runtime-*"
// output folder / allowed root). These guards make the run transactional so a crashed or hard-killed
// run cannot leave those test settings behind as the user's real configuration.
function settingsLookPolluted(data) {
if (!data || typeof data !== "object") {
return false;
}
const outputFolder = String(data.outputFolder || "");
const roots = Array.isArray(data.allowedRoots) ? data.allowedRoots : [];
return outputFolder.includes(QA_STATE_MARKER) || roots.some((root) => String(root).includes(QA_STATE_MARKER));
}
function ensurePreQaSettingsBackup() {
try {
const current = readJsonSafe(dataJsonPath);
if (!current) {
return;
}
if (settingsLookPolluted(current)) {
if (fs.existsSync(preQaSettingsBackupPath)) {
fs.copyFileSync(preQaSettingsBackupPath, dataJsonPath);
console.warn("Detected leftover QA settings in data.json; restored from the pre-QA backup before running.");
} else {
console.warn("data.json looks like leftover QA state, but no pre-QA backup exists to restore from.");
}
return;
}
fs.copyFileSync(dataJsonPath, preQaSettingsBackupPath);
} catch (error) {
console.warn(`Could not create pre-QA settings backup: ${error.message}`);
}
}
function restoreSettingsIfPolluted() {
try {
const current = readJsonSafe(dataJsonPath);
if (!settingsLookPolluted(current)) {
return;
}
if (!fs.existsSync(preQaSettingsBackupPath)) {
console.warn("Runtime QA left QA settings in data.json, but no pre-QA backup was found to restore from.");
return;
}
fs.copyFileSync(preQaSettingsBackupPath, dataJsonPath);
console.warn("Runtime QA left QA settings in data.json; restored your settings from the pre-QA backup.");
try {
runObsidianCli(["plugin:reload", `id=${pluginId}`], "post-QA settings restore reload", { allowFailure: true });
} catch (error) {
// Obsidian may be closed; the on-disk data.json is already restored for the next launch.
}
} catch (error) {
console.error(`Failed to restore data.json after runtime QA: ${error.message}`);
}
}
async function main() {
if (args.has("--help") || args.has("-h")) {
printHelp();
return;
}
if (!fs.existsSync(runnerPath)) {
throw new Error(`Missing runtime QA runner: ${runnerPath}`);
}
fs.mkdirSync(reportDir, { recursive: true });
ensurePreQaSettingsBackup();
if (!skipReload) {
console.log(`Reloading ${pluginId} through Obsidian CLI...`);
runObsidianCli(["plugin:reload", `id=${pluginId}`], "plugin reload");
}
console.log("Running Obsidian runtime QA...");
const evalExpression = `eval(require("fs").readFileSync(${JSON.stringify(runnerPath)}, "utf8"))`;
const qaResult = runObsidianCli(["eval", `code=${evalExpression}`], "runtime QA", { allowFailure: true });
if (qaResult.status !== 0) {
const rawPath = writeTextReport("runtime-qa-raw", `${qaResult.stdout || ""}\n${qaResult.stderr || ""}`);
throw new Error(`Runtime QA eval failed with exit ${qaResult.status}. Raw output: ${rawPath}`);
}
const report = parseRuntimeReport(qaResult.stdout);
const reportPath = path.join(reportDir, `runtime-qa-report-${timestampForFile()}.json`);
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
const summary = report.summary || {};
const failed = Number(summary.failed || report.failures?.length || 0);
const warnings = Number(summary.warnings || report.warnings?.length || 0);
const passed = Number(summary.passed || 0);
console.log(`Runtime QA summary: ${passed} passed, ${failed} failed, ${warnings} warnings.`);
console.log(`Runtime QA report: ${reportPath}`);
let failedGate = failed > 0;
if (failedGate) {
for (const failure of report.failures || []) {
console.error(`FAILED ${failure.name}: ${failure.error?.message || "unknown error"}`);
}
}
if (!skipDevErrors) {
console.log("Collecting Obsidian dev:errors...");
const devErrors = runObsidianCli(["dev:errors"], "dev:errors", { allowFailure: true });
const devErrorsText = `${devErrors.stdout || ""}${devErrors.stderr || ""}`.trim();
const devErrorsPath = writeTextReport("runtime-qa-dev-errors", devErrorsText || "(no dev errors)");
console.log(`dev:errors report: ${devErrorsPath}`);
if (hasPluginRelevantDevErrors(devErrorsText)) {
console.error("Plugin-relevant dev:errors were found after runtime QA.");
failedGate = true;
} else {
console.log("No plugin-relevant dev:errors found.");
}
}
if (failedGate) {
process.exitCode = 1;
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
}).finally(() => {
restoreSettingsIfPolluted();
});

1412
scripts/runtime-qa.js Normal file

File diff suppressed because it is too large Load diff

7983
scripts/smoke-ts.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,63 @@
"use strict";
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
function readText(relativePath) {
return fs.readFileSync(path.join(root, relativePath), "utf8");
}
function readJson(relativePath) {
return JSON.parse(readText(relativePath));
}
const packageJson = readJson("package.json");
const licenseText = readText("LICENSE");
const thirdPartyNotices = readText("THIRD_PARTY_NOTICES.md");
const readme = readText("README.md");
const readmeRu = readText("README.ru.md");
const apacheLicense = readText("licenses/Apache-2.0.txt");
const jpegCodecLicense = readText("licenses/jpeg-codec.txt");
const pngCodecLicense = readText("licenses/png-codec.txt");
const installedApacheLicense = fs.readFileSync(path.join(root, "node_modules", "@jsquash", "jpeg", "LICENSE"), "utf8");
const installedPngApacheLicense = fs.readFileSync(path.join(root, "node_modules", "@jsquash", "png", "LICENSE"), "utf8");
const installedJpegCodecLicense = fs.readFileSync(path.join(root, "node_modules", "@jsquash", "jpeg", "codec", "LICENSE.codec.md"), "utf8");
const installedPngCodecLicense = fs.readFileSync(path.join(root, "node_modules", "@jsquash", "png", "codec", "LICENSE.codec.md"), "utf8");
const bundlesGplCodec = /imagequant[\s\S]*GPL\s*v?3/i.test(thirdPartyNotices);
if (bundlesGplCodec) {
assert(packageJson.license === "GPL-3.0-or-later", `package.json license must be GPL-3.0-or-later when GPL codecs are bundled, got ${packageJson.license}`);
assert(/SPDX-License-Identifier:\s*GPL-3\.0-or-later/i.test(licenseText), "LICENSE must declare GPL-3.0-or-later SPDX identifier");
assert(/Copyright \(C\) 2025-2026 Haperone/i.test(licenseText), "LICENSE must contain the project copyright notice");
assert(/GNU GENERAL PUBLIC LICENSE[\s\S]*Version 3, 29 June 2007/i.test(licenseText), "LICENSE must contain the complete GPL v3 text");
assert(/0\.\s+Definitions\.[\s\S]*17\.\s+Interpretation of Sections 15 and 16\./i.test(licenseText), "LICENSE is missing GPL v3 sections");
assert(licenseText.length > 30000, "LICENSE is too short to contain the complete GPL v3 text");
assert(/GPL-3\.0-or-later/i.test(readme), "README.md must document the GPL-3.0-or-later distribution license");
assert(/GPL-3\.0-or-later/i.test(readmeRu), "README.ru.md must document the GPL-3.0-or-later distribution license");
assert(!/Plugin code:\s*MIT/i.test(readme), "README.md still documents plugin code as MIT");
assert(!/Код плагина:\s*MIT/i.test(readmeRu), "README.ru.md still documents plugin code as MIT");
}
assert(apacheLicense === installedApacheLicense, "Tracked Apache-2.0 text does not match @jsquash/jpeg");
assert(apacheLicense === installedPngApacheLicense, "Tracked Apache-2.0 text does not match @jsquash/png");
assert(jpegCodecLicense === installedJpegCodecLicense, "Tracked JPEG codec license does not match the pinned package");
assert(pngCodecLicense === installedPngCodecLicense, "Tracked PNG codec license does not match the pinned package");
assert(/This software is based in part on the work of the\s+Independent JPEG Group\./i.test(thirdPartyNotices), "JPEG codec attribution is missing");
for (const localLicensePath of [
"licenses/Apache-2.0.txt",
"licenses/jpeg-codec.txt",
"licenses/png-codec.txt",
"wasm-hashes.json"
]) {
assert(thirdPartyNotices.includes(localLicensePath), `Third-party notices are missing ${localLicensePath}`);
}
console.log("License validation passed.");

View file

@ -0,0 +1,187 @@
"use strict";
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const manifestPath = path.join(root, "manifest.json");
const versionsPath = path.join(root, "versions.json");
const packagePath = path.join(root, "package.json");
const releaseWorkflowPath = path.join(root, ".github", "workflows", "release.yml");
const gitignorePath = path.join(root, ".gitignore");
const releasePreparePath = path.join(root, "scripts", "prepare-release.js");
const sourceTsRoot = path.join(root, "src-ts");
const MIN_API_SURFACE_APP_VERSION = "1.4.0";
const DESKTOP_ONLY_REQUIRED_REASON = "cache, move, backup, and WASM artifact paths still depend on desktop Node fs/path APIs";
const DESKTOP_ONLY_API_PATTERNS = [
{ label: "Node fs", pattern: /(?:from\s+["']fs["']|require\(["']fs["']\)|\bfs\.promises\b)/ },
{ label: "Node path", pattern: /(?:from\s+["']path["']|require\(["']path["']\)|\bpath\.)/ },
{ label: "Node crypto", pattern: /(?:from\s+["']crypto["']|require\(["']crypto["']\)|\bcrypto\.)/ },
{ label: "FileSystemAdapter.getBasePath", pattern: /\bFileSystemAdapter\b|\bgetBasePath\(/ }
];
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function listFilesRecursive(dir) {
const files = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...listFilesRecursive(fullPath));
} else if (entry.isFile()) {
files.push(fullPath);
}
}
return files;
}
function collectDesktopOnlyApiMatches() {
if (!fs.existsSync(sourceTsRoot)) {
return [];
}
const matches = [];
for (const filePath of listFilesRecursive(sourceTsRoot)) {
if (!filePath.endsWith(".ts")) {
continue;
}
const source = fs.readFileSync(filePath, "utf8");
for (const { label, pattern } of DESKTOP_ONLY_API_PATTERNS) {
if (pattern.test(source)) {
matches.push(`${path.relative(root, filePath)} (${label})`);
break;
}
}
}
return matches;
}
function compareSemver(left, right) {
const leftParts = left.split(".").map((part) => Number(part));
const rightParts = right.split(".").map((part) => Number(part));
for (let index = 0; index < 3; index += 1) {
if (leftParts[index] !== rightParts[index]) {
return leftParts[index] > rightParts[index] ? 1 : -1;
}
}
return 0;
}
const manifest = readJson(manifestPath);
const rootPackage = readJson(packagePath);
const requiredStringFields = [
"id",
"name",
"version",
"minAppVersion",
"description",
"author"
];
for (const field of requiredStringFields) {
assert(typeof manifest[field] === "string" && manifest[field].trim(), `manifest.json is missing required string field: ${field}`);
}
assert(!manifest.id.includes("obsidian"), "manifest.json id must not contain 'obsidian'");
assert(/^\d+\.\d+\.\d+$/.test(manifest.version), "manifest.json version must be semver x.y.z");
assert(/^\d+\.\d+\.\d+$/.test(manifest.minAppVersion), "manifest.json minAppVersion must be semver x.y.z");
assert(
compareSemver(manifest.minAppVersion, MIN_API_SURFACE_APP_VERSION) >= 0,
`manifest.json minAppVersion must be at least ${MIN_API_SURFACE_APP_VERSION} for activeWindow/activeDocument/getBasePath API usage`
);
assert(typeof manifest.isDesktopOnly === "boolean", "manifest.json isDesktopOnly must be a boolean");
assert(rootPackage.version === manifest.version, "package.json version must match manifest.json");
const desktopOnlyApiMatches = collectDesktopOnlyApiMatches();
assert(
desktopOnlyApiMatches.length === 0 || manifest.isDesktopOnly === true,
`manifest.json isDesktopOnly must remain true until ${DESKTOP_ONLY_REQUIRED_REASON}; found ${desktopOnlyApiMatches.slice(0, 5).join(", ")}`
);
if (manifest.authorUrl) {
let authorUrl;
try {
authorUrl = new URL(manifest.authorUrl);
} catch (error) {
throw new Error(`manifest.json authorUrl must be a valid URL: ${manifest.authorUrl}`);
}
assert(["http:", "https:"].includes(authorUrl.protocol), "manifest.json authorUrl must use http or https");
assert(authorUrl.protocol === "https:", "manifest.json authorUrl must use https");
assert(!["localhost", "127.0.0.1", "::1"].includes(authorUrl.hostname), "manifest.json authorUrl must not point to localhost");
assert(!/^10\./.test(authorUrl.hostname), "manifest.json authorUrl must not point to a private network");
assert(!/^192\.168\./.test(authorUrl.hostname), "manifest.json authorUrl must not point to a private network");
assert(!/^172\.(1[6-9]|2\d|3[0-1])\./.test(authorUrl.hostname), "manifest.json authorUrl must not point to a private network");
}
assert(fs.existsSync(versionsPath), "versions.json is required for rollback-friendly auto updates");
const versions = readJson(versionsPath);
assert(typeof versions === "object" && versions && !Array.isArray(versions), "versions.json must be an object");
assert(versions[manifest.version] === manifest.minAppVersion, "versions.json must map the current manifest version to minAppVersion");
for (const [version, minAppVersion] of Object.entries(versions)) {
assert(/^\d+\.\d+\.\d+$/.test(version), `versions.json key is not semver: ${version}`);
assert(typeof minAppVersion === "string" && /^\d+\.\d+\.\d+$/.test(minAppVersion), `versions.json value must be a semver minAppVersion string for ${version}`);
assert(
compareSemver(minAppVersion, MIN_API_SURFACE_APP_VERSION) >= 0,
`versions.json minAppVersion for ${version} must be at least ${MIN_API_SURFACE_APP_VERSION}`
);
}
const releaseFiles = [
"manifest.json",
"main.js",
"styles.css",
"versions.json"
];
const forbiddenReleaseEntries = [
"cache-backups",
"original-files-backups",
"qa-backups",
"qa-screenshots",
".claude",
"source-recovery",
"node_modules",
"tinyLocal-cache.json",
"data.json"
];
assert(Array.isArray(rootPackage.files), "package.json must declare a files allowlist for release packaging");
for (const filePath of rootPackage.files) {
assert(releaseFiles.includes(filePath), `package.json files contains non-release entry: ${filePath}`);
}
for (const filePath of releaseFiles) {
assert(rootPackage.files.includes(filePath), `package.json files is missing release entry: ${filePath}`);
}
for (const forbidden of forbiddenReleaseEntries) {
assert(!rootPackage.files.includes(forbidden), `package.json files includes forbidden dev artifact: ${forbidden}`);
}
assert(fs.existsSync(releaseWorkflowPath), "Release workflow is required");
const releaseWorkflow = fs.readFileSync(releaseWorkflowPath, "utf8");
assert(fs.existsSync(releasePreparePath), "Release preparation script is required");
const releasePrepare = fs.readFileSync(releasePreparePath, "utf8");
const gitignore = fs.readFileSync(gitignorePath, "utf8");
assert(
releaseWorkflow.includes("npm run prepare:release"),
"Release workflow must use the validated release preparation script"
);
assert(releaseWorkflow.includes('"[0-9]+.[0-9]+.[0-9]+"'), "Release workflow must trigger only on exact numeric SemVer-shaped tags");
assert(releaseWorkflow.includes("^[0-9]+\\.[0-9]+\\.[0-9]+$"), "Release workflow must validate exact numeric SemVer tags");
assert(!releaseWorkflow.includes("GITHUB_REF_NAME#v") && !releaseWorkflow.includes('"v*"'), "Release workflow must reject v-prefixed tags");
assert(releasePrepare.includes('["manifest.json", "main.js", "styles.css", "versions.json"]'), "Release preparation script must use the explicit install-file allowlist");
assert(/^main\.js$/m.test(gitignore), "Generated root main.js must be ignored");
assert(/^build\/$/m.test(gitignore), "Release staging directory must be ignored");
const buildDir = path.join(root, "build");
if (fs.existsSync(buildDir)) {
for (const forbidden of forbiddenReleaseEntries) {
assert(!fs.existsSync(path.join(buildDir, forbidden)), `Dev folder leaked into release artifact: ${forbidden}`);
}
}
console.log("Manifest validation passed.");

155
scripts/validate-wasm.js Normal file
View file

@ -0,0 +1,155 @@
#!/usr/bin/env node
"use strict";
// WASM integrity gate (WWW2-A hardening).
//
// The plugin inlines four WebAssembly codecs into the bundle at build time:
// - @jsquash/jpeg mozjpeg decode + encode
// - @jsquash/png squoosh PNG
// - imagequant PNG quantizer (pinned 0.1.2, unmaintained upstream)
//
// npm already verifies the package tarballs against package-lock.json on
// `npm ci`. This gate adds a second, build-local check: it asserts the exact
// bytes we are about to bundle match a committed known-good SHA-256 manifest,
// so a compromised/republished package, an accidental version bump, or local
// tampering of node_modules fails the build with a clear error instead of
// silently shipping in main.js.
//
// Regenerate the manifest only after you have verified provenance of a
// deliberate dependency change: node scripts/validate-wasm.js --write
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const ROOT = path.join(__dirname, "..");
const MANIFEST = path.join(ROOT, "wasm-hashes.json");
// Logical name -> { wasm file (relative to node_modules), package.json for the version }
const TARGETS = {
"jpeg-decode": {
wasm: "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm",
pkg: "@jsquash/jpeg/package.json"
},
"jpeg-encode": {
wasm: "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm",
pkg: "@jsquash/jpeg/package.json"
},
"png": {
wasm: "@jsquash/png/codec/pkg/squoosh_png_bg.wasm",
pkg: "@jsquash/png/package.json"
},
"imagequant": {
wasm: "imagequant/imagequant_bg.wasm",
pkg: "imagequant/package.json"
}
};
function nodeModulesPath(relative) {
return path.join(ROOT, "node_modules", relative);
}
function readVersion(pkgRelative) {
try {
const pkg = JSON.parse(fs.readFileSync(nodeModulesPath(pkgRelative), "utf8"));
return typeof pkg.version === "string" ? pkg.version : "unknown";
} catch (error) {
return "unknown";
}
}
function computeEntries() {
const entries = {};
const missing = [];
for (const [name, target] of Object.entries(TARGETS)) {
const wasmPath = nodeModulesPath(target.wasm);
if (!fs.existsSync(wasmPath)) {
missing.push(target.wasm);
continue;
}
const bytes = fs.readFileSync(wasmPath);
entries[name] = {
file: target.wasm,
version: readVersion(target.pkg),
bytes: bytes.byteLength,
sha256: crypto.createHash("sha256").update(bytes).digest("hex")
};
}
return { entries, missing };
}
function fail(message) {
console.error(`[validate:wasm] ${message}`);
process.exit(1);
}
function main() {
const write = process.argv.includes("--write");
const { entries, missing } = computeEntries();
if (missing.length > 0) {
fail(
`Missing bundled WASM file(s): ${missing.join(", ")}.\n` +
`Run \`npm ci\` to install the exact, lockfile-verified dependencies first.`
);
}
if (write) {
const manifest = {
_comment: "Known-good SHA-256 of every WASM codec inlined into the bundle. Regenerate via `npm run validate:wasm -- --write` only after verifying a deliberate dependency change.",
generatedAt: new Date().toISOString(),
wasm: entries
};
fs.writeFileSync(MANIFEST, JSON.stringify(manifest, null, 2) + "\n");
console.log(`[validate:wasm] Wrote ${MANIFEST} with ${Object.keys(entries).length} entries.`);
return;
}
if (!fs.existsSync(MANIFEST)) {
fail(
`Manifest ${path.basename(MANIFEST)} not found.\n` +
`After verifying dependency provenance, generate it with: npm run validate:wasm -- --write`
);
}
let manifest;
try {
manifest = JSON.parse(fs.readFileSync(MANIFEST, "utf8"));
} catch (error) {
fail(`Could not parse ${path.basename(MANIFEST)}: ${error.message}`);
}
const expected = manifest && manifest.wasm ? manifest.wasm : {};
const problems = [];
for (const [name, actual] of Object.entries(entries)) {
const want = expected[name];
if (!want) {
problems.push(`${name} (${actual.file}): no entry in manifest — add it via --write after verifying provenance`);
continue;
}
if (want.sha256 !== actual.sha256) {
problems.push(
`${name} (${actual.file}): SHA-256 mismatch\n` +
` expected ${want.sha256} (v${want.version})\n` +
` actual ${actual.sha256} (v${actual.version})`
);
}
}
for (const name of Object.keys(expected)) {
if (!entries[name]) {
problems.push(`${name}: present in manifest but the WASM file was not found`);
}
}
if (problems.length > 0) {
fail(
`WASM integrity check failed:\n - ${problems.join("\n - ")}\n` +
`If this change is intentional and provenance is verified, regenerate the manifest: npm run validate:wasm -- --write`
);
}
console.log(`[validate:wasm] OK — ${Object.keys(entries).length} WASM codecs match wasm-hashes.json.`);
}
main();

68
scripts/verify-release.js Normal file
View file

@ -0,0 +1,68 @@
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");
const sourceRoot = path.resolve(__dirname, "..");
const root = sourceRoot;
const rootMainPath = path.join(root, "main.js");
const releaseFiles = ["manifest.json", "main.js", "styles.css", "versions.json"];
function sha256(buffer) {
return crypto.createHash("sha256").update(buffer).digest("hex").toUpperCase();
}
function readProductionBundle() {
if (!fs.existsSync(rootMainPath)) {
throw new Error("Production main.js is missing");
}
return fs.readFileSync(rootMainPath);
}
const firstBundle = readProductionBundle();
const firstHash = sha256(firstBundle);
const firstText = firstBundle.toString("utf8");
const lineCount = firstText.split(/\r?\n/).length;
if (!firstText.startsWith("/* GENERATED/BUNDLED FILE.")) {
throw new Error("Production bundle is missing the generated-file source banner");
}
if (firstText.includes("sourceMappingURL=")) {
throw new Error("Production bundle unexpectedly contains a source map");
}
if (lineCount > 100) {
throw new Error(`Production bundle does not appear minified: ${lineCount} lines`);
}
const rebuild = spawnSync(process.execPath, [path.join(sourceRoot, "scripts", "build-root.js")], {
cwd: sourceRoot,
stdio: "inherit",
windowsHide: true
});
if (rebuild.status !== 0) {
process.exit(rebuild.status || 1);
}
const secondBundle = readProductionBundle();
const secondHash = sha256(secondBundle);
if (!firstBundle.equals(secondBundle)) {
throw new Error(`Production build is not deterministic: ${firstHash} != ${secondHash}`);
}
const prepare = spawnSync(process.execPath, [path.join(sourceRoot, "scripts", "prepare-release.js")], {
cwd: sourceRoot,
stdio: "inherit",
windowsHide: true
});
if (prepare.status !== 0) {
process.exit(prepare.status || 1);
}
const stagedFiles = fs.readdirSync(path.join(root, "build")).sort();
if (JSON.stringify(stagedFiles) !== JSON.stringify([...releaseFiles].sort())) {
throw new Error(`Release staging mismatch: ${stagedFiles.join(", ")}`);
}
process.stdout.write(`Verified deterministic minified release (${firstBundle.length} bytes, ${lineCount} lines, SHA-256 ${firstHash})\n`);

55
scripts/verify-root-ts.js Normal file
View file

@ -0,0 +1,55 @@
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const root = path.resolve(__dirname, "..");
const generatedPath = path.join(root, "dist-ts", "main.js");
const rootMainPath = path.join(root, "main.js");
function sha256(buffer) {
return crypto.createHash("sha256").update(buffer).digest("hex").toUpperCase();
}
function firstDifferenceOffset(a, b) {
const length = Math.min(a.length, b.length);
for (let i = 0; i < length; i += 1) {
if (a[i] !== b[i]) return i;
}
return a.length === b.length ? -1 : length;
}
function readRequired(file) {
if (!fs.existsSync(file)) {
throw new Error(`File not found: ${file}`);
}
return fs.readFileSync(file);
}
const generated = readRequired(generatedPath);
const rootMain = readRequired(rootMainPath);
const generatedHash = sha256(generated);
const rootMainHash = sha256(rootMain);
if (generated.length === rootMain.length && generatedHash === rootMainHash) {
console.log(`Verified root main.js matches dist-ts/main.js (${generated.length} bytes, SHA-256 ${generatedHash})`);
process.exit(0);
}
console.error("Root TS verification failed.");
console.error(`Generated SHA-256: ${generatedHash}`);
console.error(`Root main SHA-256: ${rootMainHash}`);
console.error(`Generated size: ${generated.length}`);
console.error(`Root main size: ${rootMain.length}`);
const offset = firstDifferenceOffset(generated, rootMain);
if (offset >= 0) {
const generatedByte = offset < generated.length ? `0x${generated[offset].toString(16).padStart(2, "0")}` : "<EOF>";
const rootByte = offset < rootMain.length ? `0x${rootMain[offset].toString(16).padStart(2, "0")}` : "<EOF>";
console.error(`First differing byte offset: ${offset}`);
console.error(`Generated byte: ${generatedByte}`);
console.error(`Root byte: ${rootByte}`);
}
process.exit(1);

View file

@ -0,0 +1,161 @@
import { getLogTag } from "./utils";
import { ConcurrencyLimiter } from "./concurrency-limiter";
import type LocalImageCompressPlugin from "./plugin";
import type { TimerHandle } from "./types";
import type { TFile } from "obsidian";
const BACKGROUND_FILTER_CONCURRENCY = 8;
// Owns background auto-compression: user-activity/inactivity tracking state and
// the idle-trigger logic. The plugin holds a reference and forwards runtime
// settings (applySettings) and unload cleanup.
export class BackgroundCompressionService {
private readonly plugin: LocalImageCompressPlugin;
AUTO_BACKGROUND_THRESHOLD = 50;
USER_INACTIVITY_THRESHOLD = 2 * 60 * 1e3;
readonly INACTIVITY_CHECK_INTERVAL = 5 * 60 * 1e3;
lastUserActivity = Date.now();
lastUserActivityPerfTime: number;
isBackgroundCompressionRunning = false;
inactivityTimer: TimerHandle | null = null;
inactivityCheckActive = false;
constructor(plugin: LocalImageCompressPlugin) {
this.plugin = plugin;
this.lastUserActivityPerfTime = plugin.getMonotonicTime();
}
// Applies normalized runtime limits (called from plugin.applyRuntimeSettings).
applySettings(autoBackgroundThreshold: number, userInactivityThresholdMs: number) {
this.AUTO_BACKGROUND_THRESHOLD = autoBackgroundThreshold;
this.USER_INACTIVITY_THRESHOLD = userInactivityThresholdMs;
}
// Stops the inactivity loop and clears its timer (called from plugin onunload).
cleanup() {
this.inactivityCheckActive = false;
if (this.inactivityTimer) {
this.plugin.clearWindowTimeout(this.inactivityTimer);
this.inactivityTimer = null;
}
}
setupUserActivityTracking() {
const updateActivity: EventListener = () => {
this.lastUserActivity = Date.now();
this.lastUserActivityPerfTime = this.plugin.getMonotonicTime();
};
const activeDocument = this.plugin.getActiveDocument();
// Plugin-lifetime listeners: registerDomEvent auto-removes them on unload.
const activityEvents: Array<keyof DocumentEventMap> = [
"mousemove",
"mousedown",
"keydown",
"scroll",
"wheel",
"touchstart"
];
for (const event of activityEvents) {
this.plugin.registerDomEvent(activeDocument, event, updateActivity, { passive: true });
}
}
isUserInactive() {
const timeSinceLastActivity = Math.max(0, this.plugin.getMonotonicTime() - this.lastUserActivityPerfTime);
return timeSinceLastActivity > this.USER_INACTIVITY_THRESHOLD;
}
startInactivityCheck() {
if (this.inactivityCheckActive) {
return;
}
this.inactivityCheckActive = true;
const checkInactivity = async () => {
if (!this.inactivityCheckActive || this.plugin.isUnloading) {
return;
}
try {
if (this.plugin.settings.autoBackgroundCompression && this.isUserInactive()) {
await this.checkAndStartBackgroundCompression();
}
} catch (error) {
console.error(getLogTag(this.plugin), "Inactivity check error:", error);
} finally {
if (this.inactivityCheckActive && !this.plugin.isUnloading) {
this.inactivityTimer = this.plugin.setWindowTimeout(checkInactivity, this.INACTIVITY_CHECK_INTERVAL);
}
}
};
this.inactivityTimer = this.plugin.setWindowTimeout(checkInactivity, this.INACTIVITY_CHECK_INTERVAL);
}
async checkAndStartBackgroundCompression() {
if (!this.plugin.settings.autoBackgroundCompression || !this.isUserInactive()) {
return;
}
const uncompressedCount = this.getReadyUncompressedCount();
if (uncompressedCount === null) {
return;
}
if (!this.plugin.settings.autoBackgroundCompression || !this.isUserInactive()) {
return;
}
if (uncompressedCount >= this.getAutoBackgroundThreshold()) {
await this.startBackgroundCompression();
}
}
async startBackgroundCompression() {
if (this.isBackgroundCompressionRunning || !this.plugin.settings.autoBackgroundCompression || !this.isUserInactive()) {
return;
}
this.isBackgroundCompressionRunning = true;
try {
const hasReadyIndex = !!this.plugin.imageIndex?.isReady?.();
const imageFiles = hasReadyIndex
? await this.plugin.getImageFiles()
: this.plugin.getAllImageFiles();
const filteredFiles = imageFiles.filter(
(file): file is TFile => this.plugin.isImageFile(file) && this.plugin.isAllowedPath(file.path)
);
const uncompressedFiles = hasReadyIndex
? filteredFiles
: await this.filterUnprocessedFiles(filteredFiles);
if (!this.plugin.settings.autoBackgroundCompression || !this.isUserInactive()) {
return;
}
await this.plugin.processBatchCompressionBackground(uncompressedFiles);
} catch (error) {
console.error(getLogTag(this.plugin), "Background compression error:", error);
} finally {
this.isBackgroundCompressionRunning = false;
await this.plugin.statusBarController.update();
}
}
private async filterUnprocessedFiles(files: TFile[]) {
const limiter = new ConcurrencyLimiter(BACKGROUND_FILTER_CONCURRENCY);
const checkedFiles = await Promise.all(files.map((file) =>
limiter.run(async () => !await this.plugin.cache.isFileAlreadyProcessed(file) ? file : null)
));
return checkedFiles.filter((file): file is TFile => file !== null);
}
private getReadyUncompressedCount() {
if (!this.plugin.imageIndex?.isReady?.()) {
return null;
}
const snapshot = this.plugin.imageIndex.getSnapshot?.();
const count = snapshot?.uncompressedImages;
return typeof count === "number" && Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : null;
}
private getAutoBackgroundThreshold() {
const threshold = this.plugin.settings.autoBackgroundThreshold;
if (typeof threshold === "number" && Number.isFinite(threshold)) {
return Math.max(1, Math.trunc(threshold));
}
const fallback = this.AUTO_BACKGROUND_THRESHOLD;
return typeof fallback === "number" && Number.isFinite(fallback) ? Math.max(1, Math.trunc(fallback)) : 50;
}
}

23
src-ts/backup-storage.ts Normal file
View file

@ -0,0 +1,23 @@
import * as path from "path";
import type * as obsidian from "obsidian";
import { getVaultBasePath } from "./utils";
export const BACKUP_STORAGE_FOLDER = ".local-image-compress";
export interface BackupStoragePaths {
root: string;
backupsRoot: string;
cacheBackups: string;
originalFilesBackups: string;
}
export function getBackupStoragePaths(app: obsidian.App): BackupStoragePaths {
const root = path.resolve(getVaultBasePath(app), BACKUP_STORAGE_FOLDER);
const backupsRoot = path.join(root, "backups");
return {
root,
backupsRoot,
cacheBackups: path.join(backupsRoot, "cache"),
originalFilesBackups: path.join(backupsRoot, "originals")
};
}

View file

@ -0,0 +1,44 @@
import * as path from "path";
// Persisted cache artifacts keep the historical TinyLocal filenames for backward
// compatibility with existing vaults and backup/restore flows.
export const LEGACY_CACHE_FILE_NAME = "tinyLocal-cache.json";
export const LEGACY_CACHE_TEMP_PREFIX = ".tinyLocal-cache-";
export const LEGACY_CACHE_BACKUP_PREFIX = "tinyLocal-cache-backup-";
export const LEGACY_BROKEN_CACHE_PREFIX = "tinyLocal-cache.broken-";
export function getCacheBackupTimestamp(now = new Date()) {
return now.toISOString().replace(/[:.]/g, "-").replace(/Z$/, "");
}
export function getBrokenCacheFilePath(cacheBackupsDir: string, timestamp: string, randomSuffix: string) {
return path.join(cacheBackupsDir, "broken", `${LEGACY_BROKEN_CACHE_PREFIX}${timestamp}-${randomSuffix}.json`);
}
export function getCacheTempFilePath(cacheFile: string, processId: number, timestamp: number, randomSuffix: string) {
return path.join(path.dirname(cacheFile), `${LEGACY_CACHE_TEMP_PREFIX}${processId}-${timestamp}-${randomSuffix}.tmp`);
}
export function getCacheBackupPath(cacheBackupsDir: string, randomSuffix: string, now = new Date()) {
const backupDir = cacheBackupsDir;
const timestamp = getCacheBackupTimestamp(now);
const backupFile = path.join(backupDir, `${LEGACY_CACHE_BACKUP_PREFIX}${timestamp}-${randomSuffix}.json`);
return { backupDir, backupFile };
}
export function isCacheTempFileName(fileName: string) {
return fileName.startsWith(LEGACY_CACHE_TEMP_PREFIX) && fileName.endsWith(".tmp");
}
export function isCacheBackupFileName(fileName: string) {
return fileName.startsWith(LEGACY_CACHE_BACKUP_PREFIX) && fileName.endsWith(".json");
}
export function isBrokenCacheFileName(fileName: string) {
return fileName.startsWith(LEGACY_BROKEN_CACHE_PREFIX) && fileName.endsWith(".json");
}
export function isValidCacheBackupFileName(fileName: string) {
const safePattern = /^tinyLocal-cache-backup-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(?:\d{3}(?:-[0-9a-f]{8,32})?|[0-9a-f]{8,32})\.json$/i;
return safePattern.test(fileName) && !fileName.includes("/") && !fileName.includes("\\") && !fileName.includes("..");
}

1968
src-ts/cache.ts Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,387 @@
import jpegDecode, { init as initJpegDecode } from "@jsquash/jpeg/decode.js";
import jpegEncode, { init as initJpegEncode } from "@jsquash/jpeg/encode.js";
import pngDecode, { init as initPngDecode } from "@jsquash/png/decode.js";
import * as imagequantBindings from "imagequant/imagequant_bg.js";
import { validateEncodedOutputFormat } from "./encoded-output-validator";
type WorkerInitMessage = {
id: number;
type: "init";
wasm: {
jpegDecode: ArrayBuffer;
jpegEncode: ArrayBuffer;
png: ArrayBuffer;
imagequant: ArrayBuffer;
};
};
type WorkerCompressMessage = {
id: number;
type: "compress";
format: "png" | "jpeg";
buffer: ArrayBuffer;
settings: {
pngQuality: { min: number; max: number };
jpegQuality: number;
};
};
type WorkerScope = {
onmessage: ((event: MessageEvent<unknown>) => void) | null;
postMessage(message: unknown, transfer?: Transferable[]): void;
};
type ImagequantConstructor = new (...args: never[]) => {
set_quality(min: number, max: number): void;
set_speed(speed: number): void;
process(image: unknown): Uint8Array;
free(): void;
};
type ImagequantImageConstructor = new (data: Uint8Array, width: number, height: number, gamma: number) => {
free(): void;
};
type ImagequantBindingModule = typeof imagequantBindings & {
__wbg_set_wasm(exports: WebAssembly.Exports): void;
Imagequant: ImagequantConstructor;
ImagequantImage: ImagequantImageConstructor;
};
type WasmInstantiateResult = WebAssembly.WebAssemblyInstantiatedSource | {
instance?: { exports?: WebAssembly.Exports };
exports?: WebAssembly.Exports;
};
let initialized = false;
let imagequantSmokeValidated = false;
let jpegDecodeModule: WebAssembly.Module | null = null;
let jpegEncodeModule: WebAssembly.Module | null = null;
const workerScope = self as unknown as WorkerScope;
const REQUIRED_IMAGEQUANT_FUNCTION_EXPORTS = [
"__wbg_imagequant_free",
"__wbg_imagequantimage_free",
"__wbindgen_add_to_stack_pointer",
"__wbindgen_free",
"__wbindgen_malloc",
"imagequant_new",
"imagequant_new_image",
"imagequant_process",
"imagequant_set_quality",
"imagequant_set_speed",
"imagequantimage_new"
];
function formatWorkerError(error: unknown) {
if (error instanceof Error) {
return error.message;
}
return typeof error === "string" && error ? error : "unknown error";
}
function isPngQualityFailure(error: unknown) {
if (error instanceof PngQualityFailureError) {
return true;
}
return false;
}
function isImagequantQualityError(error: unknown) {
const message = formatWorkerError(error).toLowerCase();
return message.includes("quality_too_low") || message.includes("quality too low") || message.includes("minimum quality");
}
function isJpegEncodingFailureMessage(message: string) {
const normalized = String(message || "").toLowerCase();
return normalized.includes("mozjpeg") || normalized.includes("jpeg encode");
}
class PngQualityFailureError extends Error {
constructor(cause: unknown) {
super(`PNG quality target could not be satisfied: ${formatWorkerError(cause)}`);
this.name = "PngQualityFailureError";
}
}
function toUint8Array(input: ArrayBuffer | Uint8Array | Uint8ClampedArray) {
if (input instanceof Uint8Array && !(input instanceof Uint8ClampedArray)) {
return input;
}
if (input instanceof Uint8ClampedArray) {
const copy = new Uint8Array(input.byteLength);
copy.set(input);
return copy;
}
return new Uint8Array(input);
}
function toTransferableArrayBuffer(input: ArrayBuffer | Uint8Array): ArrayBuffer {
if (input instanceof ArrayBuffer) {
return input;
}
if (input.byteOffset === 0 && input.byteLength === input.buffer.byteLength) {
return input.buffer as ArrayBuffer;
}
return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength) as ArrayBuffer;
}
function validateEncodedOutput(format: WorkerCompressMessage["format"], output: ArrayBuffer | Uint8Array) {
validateEncodedOutputFormat(format, output);
}
function getCachedWasmModule(cacheKey: "jpegDecode" | "jpegEncode", bytes: ArrayBuffer) {
if (cacheKey === "jpegDecode") {
jpegDecodeModule = jpegDecodeModule || new WebAssembly.Module(bytes);
return jpegDecodeModule;
}
jpegEncodeModule = jpegEncodeModule || new WebAssembly.Module(bytes);
return jpegEncodeModule;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isArrayBuffer(value: unknown): value is ArrayBuffer {
return value instanceof ArrayBuffer;
}
function isFiniteMessageId(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
function isWorkerInitMessage(message: unknown): message is WorkerInitMessage {
if (!isPlainRecord(message)) {
return false;
}
const id = message["id"];
const type = message["type"];
const wasm = message["wasm"];
if (!isFiniteMessageId(id) || type !== "init" || !isPlainRecord(wasm)) {
return false;
}
return isArrayBuffer(wasm["jpegDecode"]) &&
isArrayBuffer(wasm["jpegEncode"]) &&
isArrayBuffer(wasm["png"]) &&
isArrayBuffer(wasm["imagequant"]);
}
function isWorkerCompressMessage(message: unknown): message is WorkerCompressMessage {
if (!isPlainRecord(message)) {
return false;
}
const id = message["id"];
const type = message["type"];
const format = message["format"];
if (!isFiniteMessageId(id) || type !== "compress") {
return false;
}
if (format !== "png" && format !== "jpeg") {
return false;
}
return isArrayBuffer(message["buffer"]) && isPlainRecord(message["settings"]);
}
function postWorkerFailure(id: number, kind: string, message: string, skipReason?: string) {
workerScope.postMessage({
id,
type: "result",
ok: false,
error: { kind, message, skipReason }
});
}
function clampInteger(value: unknown, fallback: number, min: number, max: number) {
const numeric = typeof value === "number" ? value : Number(value);
const integer = Number.isFinite(numeric) ? Math.trunc(numeric) : fallback;
return Math.max(min, Math.min(max, integer));
}
function validateImagequantBindings(bindings: unknown) {
const candidate = bindings as {
__wbg_set_wasm?: unknown;
Imagequant?: unknown;
ImagequantImage?: unknown;
};
if (typeof candidate.__wbg_set_wasm !== "function") {
throw new Error("Invalid imagequant bindings: __wbg_set_wasm missing");
}
if (typeof candidate.Imagequant !== "function" || typeof candidate.ImagequantImage !== "function") {
throw new Error("Invalid imagequant bindings: wrapper classes missing");
}
}
function getImagequantBindingModule(): ImagequantBindingModule {
validateImagequantBindings(imagequantBindings);
return imagequantBindings;
}
function getImagequantExports(instanceResult: WasmInstantiateResult): WebAssembly.Exports {
const directExports = "exports" in instanceResult ? instanceResult.exports : undefined;
const exports = instanceResult.instance?.exports || directExports;
if (!exports || typeof exports !== "object") {
throw new Error("Invalid imagequant WASM module: exports missing");
}
return exports;
}
function validateImagequantExports(exports: WebAssembly.Exports) {
const memory = exports["memory"];
if (!(memory instanceof WebAssembly.Memory)) {
throw new Error("Invalid imagequant WASM module: missing memory export");
}
for (const exportName of REQUIRED_IMAGEQUANT_FUNCTION_EXPORTS) {
if (typeof exports[exportName] !== "function") {
throw new Error(`Invalid imagequant WASM module: missing ${exportName} export`);
}
}
}
async function initializeCodecs(message: WorkerInitMessage) {
const locateFile = (fileName: string) => fileName;
let initStage = "jpeg-decode";
initialized = false;
imagequantSmokeValidated = false;
try {
await initJpegDecode(getCachedWasmModule("jpegDecode", message.wasm.jpegDecode), { locateFile });
initStage = "jpeg-encode";
await initJpegEncode(getCachedWasmModule("jpegEncode", message.wasm.jpegEncode), { locateFile });
initStage = "png";
await initPngDecode(message.wasm.png);
initStage = "imagequant";
const imagequantWasmInstance = await WebAssembly.instantiate(message.wasm.imagequant, {
"./imagequant_bg.js": imagequantBindings
}) as WasmInstantiateResult;
const imagequantModule = getImagequantBindingModule();
const imagequantExports = getImagequantExports(imagequantWasmInstance);
validateImagequantExports(imagequantExports);
imagequantModule.__wbg_set_wasm(imagequantExports);
initStage = "complete";
initialized = true;
} catch (error) {
initialized = false;
throw new Error(`WASM init failed at stage ${initStage}: ${formatWorkerError(error)}`);
}
}
function validateImagequantRuntimeSmoke() {
if (imagequantSmokeValidated) {
return;
}
const { Imagequant } = getImagequantBindingModule();
const smokeQuantizer = new Imagequant();
try {
smokeQuantizer.set_quality(0, 100);
imagequantSmokeValidated = true;
} finally {
try {
smokeQuantizer.free();
} catch (error) {
console.warn("[CompressionWorker]", "Imagequant smoke quantizer cleanup failed:", error);
}
}
}
function quantizePngToPng(imageData: ImageData, settings: WorkerCompressMessage["settings"]) {
validateImagequantRuntimeSmoke();
const imagequantModule = getImagequantBindingModule();
const Imagequant = imagequantModule.Imagequant;
const ImagequantImage = imagequantModule.ImagequantImage;
const quantizer = new Imagequant();
let image: InstanceType<ImagequantImageConstructor> | null = null;
try {
const safeMin = clampInteger(settings.pngQuality?.min, 65, 1, 100);
const safeMax = Math.max(safeMin, clampInteger(settings.pngQuality?.max, 80, 1, 100));
quantizer.set_quality(safeMin, safeMax);
quantizer.set_speed(6);
image = new ImagequantImage(toUint8Array(imageData.data), imageData.width, imageData.height, 0);
return quantizer.process(image);
} catch (error) {
if (isImagequantQualityError(error)) {
throw new PngQualityFailureError(error);
}
throw error;
} finally {
try {
image?.free?.();
} catch (error) {
console.warn("[CompressionWorker]", "Imagequant image cleanup failed:", error);
}
try {
quantizer.free();
} catch (error) {
console.warn("[CompressionWorker]", "Imagequant quantizer cleanup failed:", error);
}
}
}
async function compressInWorker(message: WorkerCompressMessage) {
if (!initialized) {
throw new Error("Worker codecs are not initialized");
}
if (message.format === "png") {
const decoded = await pngDecode(message.buffer);
const output = toTransferableArrayBuffer(quantizePngToPng(decoded, message.settings));
validateEncodedOutput(message.format, output);
return output;
}
const decoded = await jpegDecode(message.buffer);
const output = toTransferableArrayBuffer(await jpegEncode(decoded, { quality: clampInteger(message.settings.jpegQuality, 85, 1, 95) }));
validateEncodedOutput(message.format, output);
return output;
}
workerScope.onmessage = (event: MessageEvent<unknown>) => {
const message = event.data;
if (!isPlainRecord(message)) {
console.warn("[CompressionWorker]", "Malformed worker message:", message);
return;
}
const messageId = message["id"];
const messageType = message["type"];
if (!isFiniteMessageId(messageId)) {
console.warn("[CompressionWorker]", "Malformed worker message:", message);
return;
}
if (messageType === "init") {
if (!isWorkerInitMessage(message)) {
workerScope.postMessage({
id: messageId,
type: "init-failed",
error: { kind: "invalid_init_message", message: "Malformed init message" }
});
return;
}
initializeCodecs(message)
.then(() => {
workerScope.postMessage({ id: message.id, type: "ready" });
})
.catch((error) => {
workerScope.postMessage({
id: message.id,
type: "init-failed",
error: { kind: "init_failed", message: formatWorkerError(error) }
});
});
return;
}
if (!isWorkerCompressMessage(message)) {
postWorkerFailure(messageId, "unknown_message_type", `Unknown or malformed message type: ${String(messageType)}`);
return;
}
compressInWorker(message)
.then((output) => {
workerScope.postMessage({ id: message.id, type: "result", ok: true, output }, [output]);
})
.catch((error) => {
const qualityFailed = message.format === "png" && isPngQualityFailure(error);
const formattedError = formatWorkerError(error);
const jpegEncodeFailed = !qualityFailed && message.format === "jpeg" && isJpegEncodingFailureMessage(formattedError);
const corruptEncoderOutput = !qualityFailed && !jpegEncodeFailed && formattedError.startsWith("Invalid compressed output:");
postWorkerFailure(
message.id,
qualityFailed ? "quality_failed" : jpegEncodeFailed ? "jpeg_encode_failed" : corruptEncoderOutput ? "corrupt_encoder_output" : "unknown",
formattedError,
qualityFailed ? "pngquant_quality_failed" : jpegEncodeFailed ? "mozjpeg_failed" : corruptEncoderOutput ? "corrupt_encoder_output" : undefined
);
});
};

503
src-ts/compressor.ts Normal file
View file

@ -0,0 +1,503 @@
import workerSource from "virtual:compression-worker";
import jpegDecodeWasm from "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm";
import jpegEncodeWasm from "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm";
import * as pngWasmModule from "@jsquash/png/codec/pkg/squoosh_png_bg.wasm";
import imagequantWasm from "imagequant/imagequant_bg.wasm";
import jpegPackage from "@jsquash/jpeg/package.json";
import pngPackage from "@jsquash/png/package.json";
import imagequantPackage from "imagequant/package.json";
import type { CompressionResult } from "./types";
import {
getInternalWorkerPoolSize,
INTERNAL_COMPRESSION_TIMEOUT_SECONDS,
INTERNAL_MAX_IMAGE_PIXELS_MILLIONS,
INTERNAL_MAX_INPUT_SIZE_MB,
INTERNAL_MAX_WORKER_POOL_SIZE,
INTERNAL_WASM_INIT_TIMEOUT_SECONDS,
type LocalImageCompressSettings
} from "./settings";
import { t } from "./i18n";
import { validateEncodedOutputFormat } from "./encoded-output-validator";
import { getActiveWindowForApp, getLogTag, normalizeOutputFolder, normalizeVaultPathRoot, randomHexSuffix, sanitizeErrorForUser } from "./utils";
import { WorkerPool } from "./worker-pool";
import { WorkerCompressionError, type WasmBytes, type WorkerFactory, type WorkerFormat } from "./worker-slot";
import type { App, TFile } from "obsidian";
// The package ships a wasm-bindgen declaration, while esbuild's binary loader exposes default bytes.
const pngWasm = (pngWasmModule as unknown as { default: Uint8Array }).default;
export const PACKAGE_VERSIONS = {
jpeg: jpegPackage.version,
png: pngPackage.version,
imagequant: imagequantPackage.version
};
type BinaryInput = ArrayBuffer | Uint8Array | Buffer;
type BinaryVault = {
readBinary(file: TFile): Promise<BinaryInput>;
adapter: WritableBinaryAdapter;
};
type FileWithOptionalVault = TFile & {
vault?: BinaryVault;
};
type WritableBinaryAdapter = {
exists?: (path: string) => Promise<boolean> | boolean;
mkdir?: (path: string) => Promise<void> | void;
writeBinary?: (path: string, data: ArrayBuffer) => Promise<void> | void;
rename?: (oldPath: string, newPath: string) => Promise<void> | void;
remove?: (path: string) => Promise<void> | void;
};
type ImageDimensions = {
width: number;
height: number;
};
export class Compressor {
processTimeoutMs: number;
initTimeoutMs: number;
maxInputBytes: number;
maxImagePixels: number;
app: App | null;
workerFactory: WorkerFactory | null;
workerPool: WorkerPool;
activeWorkerCount: number;
wasmBytes: WasmBytes;
constructor(settings: LocalImageCompressSettings, app: App | null = null, workerFactory: WorkerFactory | null = null) {
this.processTimeoutMs = INTERNAL_COMPRESSION_TIMEOUT_SECONDS * 1000;
this.initTimeoutMs = INTERNAL_WASM_INIT_TIMEOUT_SECONDS * 1000;
this.maxInputBytes = INTERNAL_MAX_INPUT_SIZE_MB * 1024 * 1024;
this.maxImagePixels = INTERNAL_MAX_IMAGE_PIXELS_MILLIONS * 1_000_000;
this.app = app;
this.workerFactory = workerFactory;
this.activeWorkerCount = getInternalWorkerPoolSize(getActiveWindowForApp(this.app)?.navigator?.hardwareConcurrency);
this.applySettings(settings);
this.wasmBytes = {
jpegDecode: jpegDecodeWasm,
jpegEncode: jpegEncodeWasm,
png: pngWasm,
imagequant: imagequantWasm
};
this.workerPool = this.createWorkerPool(this.activeWorkerCount);
}
applySettings(settings: LocalImageCompressSettings) {
void settings;
this.processTimeoutMs = INTERNAL_COMPRESSION_TIMEOUT_SECONDS * 1000;
this.initTimeoutMs = INTERNAL_WASM_INIT_TIMEOUT_SECONDS * 1000;
this.maxInputBytes = INTERNAL_MAX_INPUT_SIZE_MB * 1024 * 1024;
this.maxImagePixels = INTERNAL_MAX_IMAGE_PIXELS_MILLIONS * 1_000_000;
}
text(key: string, fallback: string): string {
return this.app ? t(this.app, key) : fallback;
}
getSavingsPercentage(originalSize: number, compressedSize: number) {
if (!Number.isFinite(originalSize) || originalSize <= 0 || !Number.isFinite(compressedSize) || compressedSize < 0) {
return 0;
}
return Math.max(0, Math.min(100, Math.round(((originalSize - compressedSize) / originalSize) * 100)));
}
createWorkerPool(size = this.activeWorkerCount) {
return new WorkerPool(
this.workerFactory,
() => this.app,
() => this.processTimeoutMs,
() => this.initTimeoutMs,
workerSource,
this.wasmBytes,
size
);
}
async ensureWasmReady() {
await this.workerPool.ensureAnyReady();
}
getWasmInitError() {
return this.workerPool.getInitError();
}
checkBinaries() {
return this.workerPool.getReadyState();
}
destroy() {
this.workerPool.destroy(new Error("Compressor worker stopped because the plugin was unloaded"));
}
resize(newSize: number) {
const numeric = typeof newSize === "number" ? newSize : Number(newSize);
const integer = Number.isFinite(numeric)
? Math.trunc(numeric)
: getInternalWorkerPoolSize(getActiveWindowForApp(this.app)?.navigator?.hardwareConcurrency);
this.activeWorkerCount = Math.max(1, Math.min(INTERNAL_MAX_WORKER_POOL_SIZE, integer));
this.workerPool.resize(this.activeWorkerCount);
}
async compress(file: FileWithOptionalVault, settings: LocalImageCompressSettings, pathOverride: string | null = null): Promise<CompressionResult> {
let fileExtension = "";
try {
const vault = file?.vault || this.app?.vault;
if (!vault || typeof vault.readBinary !== "function") {
return {
success: false,
error: this.text("compress.error.fileAccess", "Unable to access file")
};
}
const filePath = pathOverride || file?.path;
if (!filePath) {
return {
success: false,
error: this.text("compress.error.fileAccess", "Unable to access file")
};
}
fileExtension = this.getExtension(filePath);
if (!this.isSupportedExtension(fileExtension)) {
throw new Error(this.text("compress.error.unsupportedFormat", "Unsupported file format"));
}
if (this.isTooLargeInput(file?.stat?.size)) {
return this.getTooLargeResult(file?.stat?.size || 0, "file-size");
}
try {
await this.ensureWasmReady();
} catch (error) {
return {
success: false,
error: `${this.text("warning.wasmInitFailed", "WebAssembly modules failed to initialize. Please reload the plugin or report a bug.")}: ${this.formatErrorForUser(error)}`,
skipReason: "wasm_init_failed"
};
}
const input = await this.readBinaryWithTimeout(vault, file);
const originalBuffer = this.toArrayBuffer(input);
const originalSize = originalBuffer.byteLength;
if (this.isTooLargeInput(originalSize)) {
return this.getTooLargeResult(originalSize, "file-size");
}
const dimensions = this.readImageDimensions(originalBuffer, fileExtension);
if (dimensions && this.hasInvalidDimensions(dimensions)) {
return {
success: false,
error: "Invalid image dimensions",
skipReason: "invalid_image_dimensions"
};
}
if (dimensions && this.isTooManyPixels(dimensions)) {
return this.getTooLargeResult(dimensions.width * dimensions.height, "pixel-count");
}
const encoded = await this.compressBuffer(originalBuffer, fileExtension, settings);
const encodedBytes = this.toUint8Array(encoded);
this.validateEncodedOutput(fileExtension, encodedBytes);
if (encodedBytes.byteLength >= originalSize) {
return this.getNotSmallerResult(originalSize, encodedBytes.byteLength);
}
const finalOutputPath = this.getOutputPath(filePath, settings.outputFolder);
await this.writeStagedOutput(vault.adapter, finalOutputPath, encodedBytes);
return {
success: true,
savings: this.getSavingsPercentage(originalSize, encodedBytes.byteLength)
};
} catch (error) {
if (this.isPngQualityFailure(error)) {
return {
success: false,
error: `${this.text("compress.error.pngQuality", "PNG encoder could not meet the configured quality range")}: ${this.formatErrorForUser(error)}`,
skipReason: "pngquant_quality_failed"
};
}
if (this.isJpegEncodingFailure(error, fileExtension)) {
return {
success: false,
error: this.formatErrorForUser(error),
skipReason: "mozjpeg_failed"
};
}
if (this.isCorruptEncoderOutput(error)) {
return {
success: false,
error: this.formatErrorForUser(error),
skipReason: "corrupt_encoder_output"
};
}
return {
success: false,
error: this.formatErrorForUser(error)
};
}
}
async readBinaryWithTimeout(vault: BinaryVault, file: TFile): Promise<BinaryInput> {
return await new Promise<BinaryInput>((resolve, reject) => {
let settled = false;
const windowRef = getActiveWindowForApp(this.app) || window;
const timeout = windowRef.setTimeout(() => {
if (settled) {
return;
}
settled = true;
reject(new Error(`File read timed out after ${this.processTimeoutMs}ms`));
}, this.processTimeoutMs);
Promise.resolve()
.then(() => vault.readBinary(file))
.then((input) => {
if (settled) {
return;
}
settled = true;
windowRef.clearTimeout(timeout);
resolve(input);
}, (error) => {
if (settled) {
return;
}
settled = true;
windowRef.clearTimeout(timeout);
reject(error instanceof Error ? error : new Error(this.formatError(error)));
});
});
}
async compressBuffer(buffer: ArrayBuffer, fileExtension: string, settings: LocalImageCompressSettings): Promise<ArrayBuffer> {
if (fileExtension === ".png") {
return await this.runWorkerCompression("png", buffer, settings);
}
if (fileExtension === ".jpg" || fileExtension === ".jpeg") {
return await this.runWorkerCompression("jpeg", buffer, settings);
}
throw new Error(this.text("compress.error.unsupportedFormat", "Unsupported file format"));
}
isSupportedExtension(fileExtension: string) {
return fileExtension === ".png" || fileExtension === ".jpg" || fileExtension === ".jpeg";
}
validateEncodedOutput(fileExtension: string, bytes: Uint8Array) {
if (fileExtension === ".png") {
validateEncodedOutputFormat("png", bytes);
return;
}
if (fileExtension === ".jpg" || fileExtension === ".jpeg") {
validateEncodedOutputFormat("jpeg", bytes);
}
}
async runWorkerCompression(format: WorkerFormat, buffer: ArrayBuffer, settings: LocalImageCompressSettings) {
return await this.workerPool.runJob(format, buffer, settings);
}
getNotSmallerResult(originalSize: number, compressedSize: number): CompressionResult {
void originalSize;
void compressedSize;
return {
success: false,
error: this.text("compress.error.notSmaller", "Compressed file is not smaller than original"),
skipReason: "compressed_not_smaller"
};
}
getTooLargeResult(size: number, reason: "file-size" | "pixel-count"): CompressionResult {
const limit = reason === "file-size" ? this.maxInputBytes : this.maxImagePixels;
return {
success: false,
error: `${this.text("compress.error.tooLarge", "Image is too large to compress safely")} (${size} > ${limit})`,
skipReason: "too_large"
};
}
getOutputPath(relativePath: string, outputFolder: string) {
return `${normalizeOutputFolder(outputFolder)}/${normalizeVaultPathRoot(relativePath)}`;
}
async ensureAdapterDirectory(adapter: WritableBinaryAdapter | null | undefined, outputPath: string) {
if (!adapter || typeof adapter.mkdir !== "function") {
throw new Error(this.text("compress.error.fileAccess", "Unable to access file"));
}
const directoryPath = normalizeVaultPathRoot(outputPath).split("/").slice(0, -1).join("/");
if (!directoryPath) {
return;
}
const parts = directoryPath.split("/");
let currentPath = "";
for (const part of parts) {
currentPath = currentPath ? `${currentPath}/${part}` : part;
if (typeof adapter.exists !== "function" || !await adapter.exists(currentPath)) {
try {
await adapter.mkdir(currentPath);
} catch (error) {
if (typeof adapter.exists !== "function" || !await adapter.exists(currentPath)) {
throw error;
}
}
}
}
}
async writeStagedOutput(adapter: WritableBinaryAdapter | null | undefined, finalOutputPath: string, bytes: Uint8Array) {
await this.ensureAdapterDirectory(adapter, finalOutputPath);
const randomSuffix = await randomHexSuffix();
const tempOutputPath = `${finalOutputPath}.tinylocal-${Date.now()}-${randomSuffix}.tmp`;
try {
if (!adapter || typeof adapter.writeBinary !== "function" || typeof adapter.rename !== "function") {
throw new Error(this.text("compress.error.fileAccess", "Unable to access file"));
}
await adapter.writeBinary(tempOutputPath, this.toArrayBuffer(bytes));
await adapter.rename(tempOutputPath, finalOutputPath);
} catch (error) {
try {
if (typeof adapter?.exists === "function" && typeof adapter.remove === "function" && await adapter.exists(tempOutputPath)) {
await adapter.remove(tempOutputPath);
}
} catch (cleanupError) {
console.warn(getLogTag(this), "Temporary compressed output cleanup failed:", cleanupError);
}
throw new Error(`${this.text("compress.error.copyCompressed", "Could not copy compressed file")}: ${this.formatErrorForUser(error)}`);
}
}
toArrayBuffer(input: BinaryInput): ArrayBuffer {
if (input instanceof ArrayBuffer) {
return input;
}
const view = input instanceof Uint8Array ? input : new Uint8Array(input as Buffer);
if (view.byteOffset === 0 && view.byteLength === view.buffer.byteLength) {
return view.buffer as ArrayBuffer;
}
return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength) as ArrayBuffer;
}
toUint8Array(input: ArrayBuffer | Uint8Array | Uint8ClampedArray): Uint8Array {
if (input instanceof Uint8Array && !(input instanceof Uint8ClampedArray)) {
return input;
}
if (input instanceof Uint8ClampedArray) {
const copy = new Uint8Array(input.byteLength);
copy.set(input);
return copy;
}
return new Uint8Array(input);
}
isPngQualityFailure(error: unknown) {
if (error instanceof WorkerCompressionError) {
return error.kind === "quality_failed" || error.skipReason === "pngquant_quality_failed";
}
return false;
}
isJpegEncodingFailure(error: unknown, fileExtension: string) {
if (fileExtension !== ".jpg" && fileExtension !== ".jpeg") {
return false;
}
if (error instanceof WorkerCompressionError) {
return error.kind === "jpeg_encode_failed" || error.skipReason === "mozjpeg_failed";
}
const message = this.formatError(error).toLowerCase();
return message.includes("mozjpeg") || message.includes("jpeg encode");
}
isCorruptEncoderOutput(error: unknown) {
if (error instanceof WorkerCompressionError) {
return error.kind === "corrupt_encoder_output" || error.skipReason === "corrupt_encoder_output";
}
return this.formatError(error).startsWith("Invalid compressed output:");
}
isTooLargeInput(size: unknown) {
return typeof size === "number" && Number.isFinite(size) && size > this.maxInputBytes;
}
isTooManyPixels(dimensions: ImageDimensions) {
return dimensions.width > 0 && dimensions.height > 0 && dimensions.width * dimensions.height > this.maxImagePixels;
}
hasInvalidDimensions(dimensions: ImageDimensions) {
return dimensions.width <= 0 || dimensions.height <= 0;
}
getExtension(filePath: string) {
const match = String(filePath || "").toLowerCase().match(/\.[^./\\]+$/);
return match ? match[0] : "";
}
readImageDimensions(buffer: ArrayBuffer, fileExtension: string): ImageDimensions | null {
const bytes = new Uint8Array(buffer);
if (fileExtension === ".png") {
return this.readPngDimensions(bytes);
}
if (fileExtension === ".jpg" || fileExtension === ".jpeg") {
return this.readJpegDimensions(bytes);
}
return null;
}
readPngDimensions(bytes: Uint8Array): ImageDimensions | null {
if (bytes.byteLength < 24) {
return null;
}
const signature = [137, 80, 78, 71, 13, 10, 26, 10];
if (!signature.every((value, index) => bytes[index] === value)) {
return null;
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return {
width: view.getUint32(16, false),
height: view.getUint32(20, false)
};
}
readJpegDimensions(bytes: Uint8Array): ImageDimensions | null {
if (bytes.byteLength < 4 || bytes[0] !== 255 || bytes[1] !== 216) {
return null;
}
let offset = 2;
while (offset + 9 < bytes.byteLength) {
while (offset < bytes.byteLength && bytes[offset] === 255) {
offset++;
}
if (offset >= bytes.byteLength) {
return null;
}
const marker = bytes[offset++] ?? 0;
if (marker === 217 || marker === 218) {
return null;
}
if (offset + 1 >= bytes.byteLength) {
return null;
}
const length = ((bytes[offset] ?? 0) << 8) | (bytes[offset + 1] ?? 0);
if (length < 2 || offset + length > bytes.byteLength) {
return null;
}
if (this.isJpegStartOfFrame(marker) && length >= 7) {
return {
height: ((bytes[offset + 3] ?? 0) << 8) | (bytes[offset + 4] ?? 0),
width: ((bytes[offset + 5] ?? 0) << 8) | (bytes[offset + 6] ?? 0)
};
}
offset += length;
}
return null;
}
isJpegStartOfFrame(marker: number) {
return marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker);
}
formatError(error: unknown) {
if (error instanceof Error) {
return error.message;
}
return typeof error === "string" && error
? error
: this.text("compress.error.unknown", "unknown error");
}
formatErrorForUser(error: unknown) {
return sanitizeErrorForUser(this.formatError(error));
}
}

View file

@ -0,0 +1,48 @@
export class ConcurrencyLimiter {
private active = 0;
private queue: Array<() => void> = [];
private readonly limit: number;
constructor(limit = 1) {
if (!ConcurrencyLimiter.isValidLimit(limit)) {
throw new RangeError(`ConcurrencyLimiter limit must be a positive integer, got: ${limit}`);
}
this.limit = limit;
}
getLimit() {
return this.limit;
}
async run<T>(task: () => Promise<T>): Promise<T> {
if (!ConcurrencyLimiter.isValidLimit(this.limit)) {
throw new Error(`ConcurrencyLimiter is in an invalid state: limit=${this.limit}`);
}
if (this.active >= this.limit) {
await new Promise<void>((resolve) => this.queue.push(resolve));
}
this.active++;
try {
return await task();
} finally {
this.active--;
this.releaseNext();
}
}
private releaseNext() {
const next = this.queue.shift();
if (!next) {
return;
}
Promise.resolve()
.then(next)
.catch(() => {
this.releaseNext();
});
}
private static isValidLimit(limit: number) {
return Number.isInteger(limit) && limit >= 1;
}
}

5
src-ts/electron.d.ts vendored Normal file
View file

@ -0,0 +1,5 @@
declare module "electron" {
export const shell: {
openPath(targetPath: string): Promise<string>;
};
}

View file

@ -0,0 +1,285 @@
export type EncodedOutputFormat = "png" | "jpeg";
export type ValidationResult =
| { ok: true }
| { ok: false; reason: string };
const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
const MAX_PNG_CHUNK_LENGTH = 256 * 1024 * 1024;
const CRC32_TABLE = (() => {
const table = new Uint32Array(256);
for (let index = 0; index < table.length; index++) {
let value = index;
for (let bit = 0; bit < 8; bit++) {
value = (value & 1) ? (0xedb88320 ^ (value >>> 1)) : (value >>> 1);
}
table[index] = value >>> 0;
}
return table;
})();
function fail(reason: string): ValidationResult {
return { ok: false, reason };
}
function byteAt(bytes: Uint8Array, index: number) {
return bytes[index] ?? -1;
}
function crc32(bytes: Uint8Array, start: number, length: number) {
let crc = 0xffffffff;
for (let offset = start; offset < start + length; offset++) {
crc = (CRC32_TABLE[(crc ^ byteAt(bytes, offset)) & 0xff] ?? 0) ^ (crc >>> 8);
}
return (crc ^ 0xffffffff) >>> 0;
}
function chunkTypeAt(bytes: Uint8Array, offset: number) {
return String.fromCharCode(
byteAt(bytes, offset),
byteAt(bytes, offset + 1),
byteAt(bytes, offset + 2),
byteAt(bytes, offset + 3)
);
}
export function validatePngStructure(bytes: Uint8Array): ValidationResult {
if (bytes.byteLength < 57) {
return fail("too-small");
}
for (let index = 0; index < PNG_SIGNATURE.length; index++) {
if (byteAt(bytes, index) !== PNG_SIGNATURE[index]) {
return fail("bad-signature");
}
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
let offset = PNG_SIGNATURE.length;
let sawIHDR = false;
let sawIDAT = false;
let sawIEND = false;
while (offset + 12 <= bytes.byteLength) {
const chunkLength = view.getUint32(offset, false);
if (chunkLength > MAX_PNG_CHUNK_LENGTH) {
return fail("chunk-too-large");
}
const chunkTypeOffset = offset + 4;
const chunkDataOffset = offset + 8;
const crcOffset = chunkDataOffset + chunkLength;
const nextOffset = crcOffset + 4;
if (nextOffset > bytes.byteLength) {
return fail("truncated-chunk");
}
const chunkType = chunkTypeAt(bytes, chunkTypeOffset);
if (!/^[A-Za-z]{4}$/.test(chunkType)) {
return fail("invalid-chunk-type");
}
const expectedCrc = view.getUint32(crcOffset, false);
const actualCrc = crc32(bytes, chunkTypeOffset, 4 + chunkLength);
if (actualCrc !== expectedCrc) {
return fail(`crc-mismatch-${chunkType}`);
}
if (!sawIHDR && chunkType !== "IHDR") {
return fail("first-chunk-not-IHDR");
}
if (chunkType === "IHDR") {
if (sawIHDR) {
return fail("duplicate-IHDR");
}
if (chunkLength !== 13) {
return fail("IHDR-wrong-length");
}
const width = view.getUint32(chunkDataOffset, false);
const height = view.getUint32(chunkDataOffset + 4, false);
if (width === 0 || height === 0) {
return fail("zero-dimensions");
}
sawIHDR = true;
} else if (chunkType === "IDAT") {
if (!sawIHDR) {
return fail("IDAT-before-IHDR");
}
if (chunkLength > 0) {
sawIDAT = true;
}
} else if (chunkType === "IEND") {
if (chunkLength !== 0) {
return fail("IEND-wrong-length");
}
if (!sawIDAT) {
return fail("missing-or-empty-IDAT");
}
sawIEND = true;
offset = nextOffset;
break;
}
offset = nextOffset;
}
if (!sawIHDR) {
return fail("missing-IHDR");
}
if (!sawIDAT) {
return fail("missing-or-empty-IDAT");
}
if (!sawIEND) {
return fail("missing-IEND");
}
if (offset !== bytes.byteLength) {
return fail("trailing-data");
}
return { ok: true };
}
function isJpegStartOfFrame(marker: number) {
return marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
}
function isJpegRestartMarker(marker: number) {
return marker >= 0xd0 && marker <= 0xd7;
}
function readUint16(bytes: Uint8Array, offset: number) {
return ((byteAt(bytes, offset) & 0xff) << 8) | (byteAt(bytes, offset + 1) & 0xff);
}
export function validateJpegStructure(bytes: Uint8Array): ValidationResult {
if (bytes.byteLength < 4) {
return fail("too-small");
}
if (byteAt(bytes, 0) !== 0xff || byteAt(bytes, 1) !== 0xd8) {
return fail("bad-SOI");
}
let offset = 2;
let sawSOF = false;
let sawSOS = false;
let sawEOI = false;
while (offset < bytes.byteLength) {
if (byteAt(bytes, offset) !== 0xff) {
return fail("marker-misalign");
}
while (offset < bytes.byteLength && byteAt(bytes, offset) === 0xff) {
offset++;
}
if (offset >= bytes.byteLength) {
return fail("truncated-marker");
}
const marker = byteAt(bytes, offset);
offset++;
if (marker === 0x00) {
return fail("stuffed-marker-outside-scan");
}
if (marker === 0xd9) {
sawEOI = true;
if (offset !== bytes.byteLength) {
return fail("trailing-data");
}
break;
}
if (marker === 0xd8 || marker === 0x01 || isJpegRestartMarker(marker)) {
continue;
}
if (offset + 2 > bytes.byteLength) {
return fail("truncated-segment");
}
const segmentLength = readUint16(bytes, offset);
if (segmentLength < 2 || offset + segmentLength > bytes.byteLength) {
return fail("bad-segment-length");
}
const segmentDataOffset = offset + 2;
const segmentDataLength = segmentLength - 2;
if (isJpegStartOfFrame(marker)) {
if (segmentDataLength < 6) {
return fail("bad-SOF");
}
const height = readUint16(bytes, segmentDataOffset + 1);
const width = readUint16(bytes, segmentDataOffset + 3);
const componentCount = byteAt(bytes, segmentDataOffset + 5);
if (width <= 0 || height <= 0 || componentCount <= 0) {
return fail("bad-SOF-dimensions");
}
if (segmentDataLength < 6 + componentCount * 3) {
return fail("truncated-SOF");
}
sawSOF = true;
}
if (marker === 0xda) {
if (segmentDataLength < 4) {
return fail("bad-SOS");
}
const componentCount = byteAt(bytes, segmentDataOffset);
const expectedLength = 1 + componentCount * 2 + 3;
if (componentCount <= 0 || segmentDataLength < expectedLength) {
return fail("truncated-SOS");
}
sawSOS = true;
offset += segmentLength;
while (offset < bytes.byteLength) {
if (byteAt(bytes, offset) === 0xff) {
const next = byteAt(bytes, offset + 1);
if (next === 0x00) {
offset += 2;
continue;
}
if (isJpegRestartMarker(next)) {
offset += 2;
continue;
}
break;
}
offset++;
}
continue;
}
offset += segmentLength;
}
if (!sawSOF) {
return fail("missing-SOF");
}
if (!sawSOS) {
return fail("missing-SOS");
}
if (!sawEOI) {
return fail("missing-EOI");
}
return { ok: true };
}
export function toOutputBytes(output: ArrayBuffer | Uint8Array | Uint8ClampedArray) {
if (output instanceof Uint8Array && !(output instanceof Uint8ClampedArray)) {
return output;
}
if (output instanceof Uint8ClampedArray) {
const copy = new Uint8Array(output.byteLength);
copy.set(output);
return copy;
}
return new Uint8Array(output);
}
export function validateEncodedOutputFormat(format: EncodedOutputFormat, output: ArrayBuffer | Uint8Array | Uint8ClampedArray) {
const bytes = toOutputBytes(output);
if (bytes.byteLength === 0) {
throw new Error("Invalid compressed output: empty worker result");
}
const result = format === "png" ? validatePngStructure(bytes) : validateJpegStructure(bytes);
if (!result.ok) {
throw new Error(`Invalid compressed output: ${format.toUpperCase()} ${result.reason}`);
}
}

674
src-ts/i18n.ts Normal file
View file

@ -0,0 +1,674 @@
import * as fs from "fs";
import * as path from "path";
import { Notice, type App } from "obsidian";
import { getLogTag, getVaultBasePath, normalizeVaultPathForComparison } from "./utils";
type LocaleApp = Partial<App> & {
getLanguage?: () => string;
};
// i18n helper
export const I18N: Record<string, Record<string, string>> = {
en: {
"settings.title": "Settings",
"settings.loadFailed": "Settings could not be loaded; defaults were used",
"init.failed": "Plugin initialization failed. Reload the plugin after fixing the reported error.",
"migration.partialFailure": "Legacy plugin data migration completed with errors. Check the developer console.",
"i18n.externalLoadFailed": "External language file could not be loaded",
"warning.wasmInitFailed": "WebAssembly modules failed to initialize. Please reload the plugin or report a bug.",
"command.compressInNote": "Compress all images in note",
"command.compressInFolder": "Compress all images in folder",
"command.compressAll": "Compress all images in vault",
"command.moveCompressed": "Move compressed files",
"context.compressImage": "Compress image",
"context.compressImagesInFolder": "Compress images in folder",
"notice.cacheUpdated": "Cache updated",
"notice.cacheCleared": "Cache cleared",
"notice.compressionDeferredDueToMove": "Compression is deferred while a move operation is in progress",
"notice.operationFailed": "Operation failed. Check the developer console.",
"validation.pathNotAllowed": "Path is not allowed in settings",
"validation.outputFolder": "File is inside the output folder",
"validation.alreadyCompressed": "File is already compressed",
"validation.tooSmall": "File is too small",
"validation.bytes": "bytes",
"compress.error.fileAccess": "Unable to access file",
"compress.error.unknown": "unknown error",
"compress.error.tooLarge": "Image is too large to compress safely",
"compress.error.notSmaller": "Compressed file is not smaller than original",
"compress.error.unsupportedFormat": "Unsupported file format",
"compress.error.copyCompressed": "Could not copy compressed file",
"compress.error.copyCompressedJpeg": "Could not copy compressed JPEG file",
"compress.error.pngQuality": "PNG encoder could not meet the configured quality range",
"section.quality": "Compression quality",
"section.paths": "Paths",
"section.automation": "Automation",
"section.stats": "Statistics & cache",
"section.move": "Move compressed files",
"section.cacheBackups": "Cache backups",
"section.instructions": "Instructions",
"quality.png.name": "PNG quality (min-max)",
"quality.png.desc": "Quality range for PNG compression (65-80 by default)",
"quality.jpeg.name": "JPEG quality",
"quality.jpeg.desc": "JPEG compression quality (1-95)",
"paths.allowedRoots.name": "Allowed roots",
"paths.allowedRoots.desc": "Select folders where compression is allowed (empty = all paths)",
"paths.allowedRoots.empty": "Not selected (compress everywhere)",
"paths.allowedRoots.pill.remove": "Click to remove",
"paths.allowedRoots.modal.placeholder": "Select a folder...",
"paths.allowedRoots.cannotAddRoot": "Leave the list empty to allow all folders",
"paths.allowedRoots.clear": "Clear list",
"paths.output.name": "Output folder",
"paths.output.desc": "Folder name to store compressed files",
"auto.newFiles.name": "Auto-compress new files",
"auto.newFiles.desc": "Automatically compress new images when added to vault",
"auto.bg.name": "Automatic background compression",
"auto.bg.desc": "Automatically compress in background when you are inactive",
"auto.bg.threshold.name": "Background compression threshold",
"auto.bg.threshold.desc": "Number of uncompressed images to auto-start",
"auto.bg.inactivity.name": "Inactivity threshold (minutes)",
"auto.bg.inactivity.desc": "Minutes without input before background compression can start",
"guard.disabled": "{id} was temporarily disabled during compression",
"guard.restored": "{id} was restored after compression",
"auto.retention.toggle.name": "Auto-delete image backups",
"auto.retention.toggle.desc": "Delete image backups by retention period",
"auto.retention.days.name": "Backups retention (days)",
"auto.retention.days.desc": "Delete backups older than the specified number of days",
"auto.move.toggle.name": "Enable auto-move of compressed files",
"auto.move.toggle.desc": "Automatically move compressed files when threshold is reached",
"auto.move.threshold.name": "Auto-move threshold (items)",
"auto.move.threshold.desc": "How many files in 'Compressed' to trigger auto-move",
"auto.queueFull": "Auto-compress queue is full ({max}); new files were skipped",
"background.starting": "Background compression started for {count} images",
"background.finished": "Background compression finished: {count} images compressed",
"auto.cleanupGhosts.name": "Auto-clean ghost entries on start",
"auto.cleanupGhosts.desc": "Automatically remove cache entries pointing to deleted files on startup",
"stats.uncompressed.name": "Uncompressed images",
"stats.uncompressed.ready": "images ready to compress",
"stats.cache.name": "Cache entries",
"stats.cache.entries": "entries",
"stats.cache.size": "size",
"stats.cache.retention.name": "Cache retention (months)",
"stats.cache.retention.desc": "Remove cache entries that have not been used for the selected number of months",
"cache.corruptSaved": "Cache could not be read. A recovery copy was saved:",
"stats.ghosts.name": "Ghost entries",
"stats.ghosts.pointToMissing": "cache entries point to deleted files",
"stats.ghosts.clearedCount": "{count} ghost entries cleared",
"move.title": "Move compressed files",
"move.ready": "compressed files are ready to move",
"move.button": "Move",
"move.noCompressedFolder": "Compressed folder not found",
"move.noneToMove": "No compressed files to move",
"move.noneWithOriginals": "No compressed files with originals in allowed roots",
"move.backupCreated": "Created backup of original and compressed files",
"move.backup.createdCount": "Created backup of {count} original files",
"move.skip.ambiguousOriginal": "Ambiguous original filename",
"move.skip.originalMissingBeforeBackup": "Original missing before backup",
"move.skip.compressedMissingBeforeBackup": "Compressed output missing before backup",
"move.skip.originalModifiedDuringBackup": "Original changed during backup",
"move.skip.compressedModifiedDuringBackup": "Compressed output changed during backup",
"move.skip.originalContentChangedDuringBackup": "Original content changed during backup",
"move.skip.compressedContentChangedDuringBackup": "Compressed output content changed during backup",
"move.skip.contentChangedDuringCopy": "Content changed while backup was being copied",
"move.skip.originalNotFoundAtMoveTime": "Original not found at move time",
"move.skip.selfMove": "Compressed path matches the original file",
"move.skip.externalModification": "External modification detected during move",
"move.skip.invalidBackupTask": "Invalid backup task",
"move.skip.noOriginalCandidate": "Original candidate not found",
"move.skip.unloading": "Plugin unloading",
"move.warning.externalModification": "External modification detected during move: {name}",
"backups.imagesFolder.name": "Image backups folder",
"backups.imagesFolder.desc": "Open folder with backups of original/compressed images",
"backups.imagesFolder.openButton": "Open image backups folder",
"backups.imagesFolder.openError": "Failed to open image backups folder",
"backups.imagesFolder.clearName": "Clear image backups",
"backups.imagesFolder.clearDesc": "Delete backups of moved original/compressed images",
"backups.imagesFolder.clearButton": "Clear image backups",
"backups.imagesFolder.notFound": "Backups folder not found",
"backups.imagesFolder.noneToDelete": "No backups to delete",
"backups.imagesFolder.deletedCount": "Deleted {count} original file backups",
"backups.imagesFolder.clearError": "Error while clearing backups",
"backups.cache.title": "Cache backups",
"backups.cache.folder.name": "Cache backups folder",
"backups.cache.folder.desc": "Open folder with cache backup files",
"backups.cache.folder.openButton": "Open cache backups folder",
"backups.pathLabel": "Path",
"backups.foundLabel": "Backups found",
"backups.cache.none": "No cache backups available",
"backups.cache.restore": "Restore cache from backup",
"backups.cache.available": "Available backups:",
"backups.cache.selectPlaceholder": "-- Select backup --",
"common.add": "Add",
"common.refresh": "Refresh",
"common.refreshing": "Refreshing...",
"common.processing": "Processing...",
"common.clearCache": "Clear cache",
"common.refreshCache": "Refresh cache",
"common.clearGhosts": "Clear ghosts",
"common.clear": "Clear",
"common.clearing": "Clearing...",
"common.cancel": "Cancel",
"common.close": "Close",
"units.kb": "KB",
"instructions.usageTitle": "Usage:",
"instructions.notesTitle": "Notes:",
"instructions.notes.saved": "Compressed files are saved in",
"instructions.notes.originalUnchanged": "Original files are not modified",
"instructions.notes.recompressionSkipped": "Re-compression is skipped thanks to cache"
,"progress.start": "Starting..."
,"progress.processing": "Processing"
,"progress.skippedAlready": "Skipped (already compressed)"
,"progress.skipped": "Skipped"
,"progress.compressed": "Compressed"
,"progress.error": "Error"
,"progress.cancelling": "Cancelling..."
,"progress.cancelled": "Cancelled"
,"status.loading": "Loading..."
,"status.indexing": "Indexing images..."
,"progress.completed": "Completed! Compressed"
,"folders.noneInVault": "No folders found in vault"
,"folderSelect.title": "Select a folder for image compression"
,"folderSelect.selectLabel": "Folder"
,"folderSelect.root": "Root folder"
,"folderSelect.select": "Select"
,"folderSelect.cancel": "Cancel"
,"instructions.action.rightClick": "Right-click an image →"
,"instructions.action.commandPalette": "Command palette →"
,"savings.original": "Original"
,"savings.current": "Current"
,"savings.saved": "Saved"
,"tooltip.savings.header": "Space savings details"
,"tooltip.savings.original": "Original size:"
,"tooltip.savings.current": "Current size:"
,"tooltip.savings.saved": "Space saved:"
,"tooltip.savings.filesProcessed": "Files processed:"
,"tooltip.savings.estimated": "estimated"
},
ru: {
"settings.title": "Настройки",
"settings.loadFailed": "Не удалось загрузить настройки; использованы значения по умолчанию",
"init.failed": "Не удалось инициализировать плагин. Перезагрузите плагин после исправления ошибки.",
"migration.partialFailure": "Перенос данных старой версии завершился с ошибками. Проверьте консоль разработчика.",
"i18n.externalLoadFailed": "Не удалось загрузить внешний файл языка",
"warning.wasmInitFailed": "Не удалось инициализировать WebAssembly модули. Перезагрузите плагин или сообщите о проблеме.",
"command.compressInNote": "Сжать все изображения в заметке",
"command.compressInFolder": "Сжать все изображения в папке",
"command.compressAll": "Сжать все изображения в vault",
"command.moveCompressed": "Переместить сжатые файлы",
"context.compressImage": "Сжать изображение",
"context.compressImagesInFolder": "Сжать изображения в папке",
"notice.cacheUpdated": "Кэш обновлен",
"notice.cacheCleared": "Кэш очищен",
"notice.compressionDeferredDueToMove": "Сжатие отложено, пока выполняется перенос файлов",
"notice.operationFailed": "Операция не выполнена. Проверьте консоль разработчика.",
"validation.pathNotAllowed": "Путь не разрешён в настройках",
"validation.outputFolder": "Файл находится в папке для сжатых файлов",
"validation.alreadyCompressed": "Файл уже сжат",
"validation.tooSmall": "Файл слишком маленький",
"validation.bytes": "байт",
"compress.error.fileAccess": "Невозможно получить доступ к файлу",
"compress.error.unknown": "неизвестная ошибка",
"compress.error.tooLarge": "Изображение слишком большое для безопасного сжатия",
"compress.error.unsupportedFormat": "Неподдерживаемый формат файла",
"compress.error.copyCompressed": "Не удалось скопировать сжатый файл",
"compress.error.copyCompressedJpeg": "Не удалось скопировать сжатый JPEG файл",
"compress.error.pngQuality": "PNG-кодек не смог обеспечить заданный диапазон качества",
"section.quality": "Качество сжатия",
"section.paths": "Пути",
"section.automation": "Автоматизация",
"section.stats": "Статистика и кэш",
"section.move": "Перемещение сжатых файлов",
"section.cacheBackups": "Бэкапы кеша",
"section.instructions": "Инструкции",
"quality.png.name": "Качество PNG (мин-макс)",
"quality.png.desc": "Диапазон качества для сжатия PNG файлов (65-80 по умолчанию)",
"quality.jpeg.name": "Качество JPEG",
"quality.jpeg.desc": "Качество сжатия JPEG файлов (1-95)",
"paths.allowedRoots.name": "Разрешённые корни",
"paths.allowedRoots.desc": "Выберите папки, где разрешено сжатие (пусто = все пути)",
"paths.allowedRoots.empty": "Не выбрано (сжимаем везде)",
"paths.allowedRoots.pill.remove": "Нажмите, чтобы удалить",
"paths.allowedRoots.modal.placeholder": "Выберите папку...",
"paths.allowedRoots.cannotAddRoot": "Оставьте список пустым, чтобы разрешить все папки",
"paths.allowedRoots.clear": "Очистить список",
"paths.output.name": "Выходная папка",
"paths.output.desc": "Имя папки для сохранения сжатых файлов",
"auto.newFiles.name": "Автосжатие новых файлов",
"auto.newFiles.desc": "Автоматически сжимать новые изображения при добавлении в vault",
"auto.bg.name": "Автоматическое фоновое сжатие",
"auto.bg.desc": "Автоматически сжимать в фоне, когда вы неактивны",
"auto.bg.threshold.name": "Порог для фонового сжатия",
"auto.bg.threshold.desc": "Количество несжатых изображений для автозапуска",
"guard.disabled": "{id} временно отключён на время сжатия",
"guard.restored": "{id} восстановлен после сжатия",
"auto.retention.toggle.name": "Автоудаление бэкапов изображений",
"auto.retention.toggle.desc": "Удалять бэкапы изображений по сроку хранения",
"auto.retention.days.name": "Срок хранения бэкапов (дней)",
"auto.retention.days.desc": "Удалять бэкапы, которым больше указанного количества дней",
"auto.move.toggle.name": "Автоперемещение сжатых файлов — включить",
"auto.move.toggle.desc": "Автоматически перемещать сжатые файлы при достижении порога",
"auto.move.threshold.name": "Порог автоперемещения (шт.)",
"auto.move.threshold.desc": "Сколько сжатых файлов в 'Compressed' нужно для автоперемещения",
"auto.queueFull": "Очередь автосжатия заполнена ({max}); новые файлы пропущены",
"background.starting": "Фоновое сжатие запущено для изображений: {count}",
"background.finished": "Фоновое сжатие завершено, сжато изображений: {count}",
"auto.bg.inactivity.name": "Порог бездействия (минуты)",
"auto.bg.inactivity.desc": "Сколько минут без ввода ждать перед запуском фонового сжатия",
"auto.cleanupGhosts.name": "Автоочистка призраков при старте",
"auto.cleanupGhosts.desc": "Автоматически удалять записи кэша, указывающие на удалённые файлы, при запуске Obsidian",
"stats.uncompressed.name": "Несжатых изображений",
"stats.uncompressed.ready": "изображений готовы к сжатию",
"stats.cache.name": "Записей в кэше",
"stats.cache.entries": "записей",
"stats.cache.size": "размер",
"stats.cache.retention.name": "Хранение кеша (месяцы)",
"stats.cache.retention.desc": "Удалять записи кеша, которые не использовались выбранное количество месяцев",
"cache.corruptSaved": "Кеш не удалось прочитать. Копия для восстановления сохранена:",
"stats.ghosts.name": "Призрачные записи",
"stats.ghosts.pointToMissing": "записей в кэше ссылаются на удалённые файлы",
"stats.ghosts.clearedCount": "Очищено призрачных записей: {count}",
"move.title": "Переместить сжатые файлы",
"move.ready": "сжатых файлов готовы к перемещению",
"move.button": "Переместить",
"move.noCompressedFolder": "Папка Compressed не найдена",
"move.noneToMove": "Нет сжатых файлов для перемещения",
"move.noneWithOriginals": "Нет сжатых файлов с оригиналами в разрешённых корнях",
"move.backupCreated": "Создан бэкап оригинальных и сжатых файлов",
"move.backup.createdCount": "Создана резервная копия {count} оригинальных файлов",
"move.skip.ambiguousOriginal": "Неоднозначное имя оригинала",
"move.skip.originalMissingBeforeBackup": "Оригинал отсутствует перед бэкапом",
"move.skip.compressedMissingBeforeBackup": "Сжатый файл отсутствует перед бэкапом",
"move.skip.originalModifiedDuringBackup": "Оригинал изменился во время бэкапа",
"move.skip.compressedModifiedDuringBackup": "Сжатый файл изменился во время бэкапа",
"move.skip.originalContentChangedDuringBackup": "Содержимое оригинала изменилось во время бэкапа",
"move.skip.compressedContentChangedDuringBackup": "Содержимое сжатого файла изменилось во время бэкапа",
"move.skip.contentChangedDuringCopy": "Содержимое изменилось во время копирования бэкапа",
"move.skip.originalNotFoundAtMoveTime": "Оригинал не найден во время перемещения",
"move.skip.selfMove": "Путь сжатого файла совпадает с оригиналом",
"move.skip.externalModification": "Внешнее изменение во время перемещения",
"move.skip.invalidBackupTask": "Некорректная задача бэкапа",
"move.skip.noOriginalCandidate": "Кандидат оригинала не найден",
"move.skip.unloading": "Плагин выгружается",
"move.warning.externalModification": "Обнаружено внешнее изменение во время перемещения: {name}",
"backups.imagesFolder.name": "Папка с бэкапами изображений",
"backups.imagesFolder.desc": "Открыть папку с бэкапами оригинальных/сжатых изображений",
"backups.imagesFolder.openButton": "Открыть папку бэкапов изображений",
"backups.imagesFolder.openError": "Не удалось открыть папку бэкапов изображений",
"backups.imagesFolder.clearName": "Очистить бэкапы изображений",
"backups.imagesFolder.clearDesc": "Удалить бэкапы перемещённых оригинальных/сжатых изображений",
"backups.imagesFolder.clearButton": "Очистить бэкапы изображений",
"backups.imagesFolder.notFound": "Папка бэкапов не найдена",
"backups.imagesFolder.noneToDelete": "Нет бэкапов для удаления",
"backups.imagesFolder.deletedCount": "Удалено бэкапов оригинальных файлов: {count}",
"backups.imagesFolder.clearError": "Ошибка при очистке бэкапов",
"backups.cache.title": "Бэкапы кеша",
"backups.cache.folder.name": "Папка бэкапов кеша",
"backups.cache.folder.desc": "Открыть папку с файлами бэкапов кеша",
"backups.cache.folder.openButton": "Открыть папку бэкапов кеша",
"backups.pathLabel": "Путь",
"backups.foundLabel": "Найдено бэкапов",
"backups.cache.none": "Нет доступных бэкапов кеша",
"backups.cache.restore": "Восстановить кеш из бэкапа",
"backups.cache.available": "Доступно бэкапов:",
"backups.cache.selectPlaceholder": "-- Выберите бэкап --",
"common.add": "Добавить",
"common.refresh": "Обновить",
"common.refreshing": "Обновление...",
"common.processing": "Обработка...",
"common.clearCache": "Очистить кэш",
"common.refreshCache": "Обновить кэш",
"common.clearGhosts": "Очистить призраки",
"common.clear": "Очистить",
"common.clearing": "Очистка...",
"common.cancel": "Отмена",
"common.close": "Закрыть",
"units.kb": "КБ",
"instructions.usageTitle": "Использование:",
"instructions.notesTitle": "Примечания:",
"instructions.notes.saved": "Сжатые файлы сохраняются в папку",
"instructions.notes.originalUnchanged": "Оригинальные файлы не изменяются",
"instructions.notes.recompressionSkipped": "Повторное сжатие пропускается благодаря кэшу"
,"progress.start": "Начинаем обработку..."
,"progress.processing": "Обработка"
,"progress.skippedAlready": "Пропущен (уже сжат)"
,"progress.skipped": "Пропущен"
,"progress.compressed": "Сжат"
,"progress.error": "Ошибка"
,"progress.cancelling": "Отмена..."
,"progress.cancelled": "Отменено"
,"status.loading": "Загрузка..."
,"status.indexing": "Индексация изображений..."
,"progress.completed": "Завершено! Сжато"
,"folders.noneInVault": "Во vault нет папок"
,"folderSelect.title": "Выберите папку для сжатия изображений"
,"folderSelect.selectLabel": "Папка"
,"folderSelect.root": "Корневая папка"
,"folderSelect.select": "Выбрать"
,"folderSelect.cancel": "Отмена"
,"instructions.action.rightClick": "Правый клик по изображению →"
,"instructions.action.commandPalette": "Палитра команд →"
,"savings.original": "Оригинал"
,"savings.current": "Текущий"
,"savings.saved": "Сэкономлено"
,"tooltip.savings.header": "Детали экономии места"
,"tooltip.savings.original": "Исходный размер:"
,"tooltip.savings.current": "Текущий размер:"
,"tooltip.savings.saved": "Экономия места:"
,"tooltip.savings.filesProcessed": "Обработано файлов:"
,"tooltip.savings.estimated": "оценено"
},
uk: {
"settings.title": "Налаштування",
"settings.loadFailed": "Не вдалося завантажити налаштування; використано типові значення",
"init.failed": "Не вдалося ініціалізувати плагін. Перезавантажте плагін після виправлення помилки.",
"migration.partialFailure": "Перенесення даних старої версії завершилося з помилками. Перевірте консоль розробника.",
"i18n.externalLoadFailed": "Не вдалося завантажити зовнішній мовний файл",
"warning.wasmInitFailed": "Не вдалося ініціалізувати WebAssembly модулі. Перезавантажте плагін або повідомте про проблему.",
"command.compressInNote": "Стиснути всі зображення в нотатці",
"command.compressInFolder": "Стиснути всі зображення в папці",
"command.compressAll": "Стиснути всі зображення у vault",
"command.moveCompressed": "Перемістити стиснені файли",
"context.compressImage": "Стиснути зображення",
"context.compressImagesInFolder": "Стиснути зображення в папці",
"notice.cacheUpdated": "Кеш оновлено",
"notice.cacheCleared": "Кеш очищено",
"notice.compressionDeferredDueToMove": "Стиснення відкладено, доки триває перенесення файлів",
"notice.operationFailed": "Не вдалося виконати операцію. Перевірте консоль розробника.",
"validation.pathNotAllowed": "Шлях не дозволено в налаштуваннях",
"validation.outputFolder": "Файл розташовано в папці для стиснених файлів",
"validation.alreadyCompressed": "Файл уже стиснено",
"validation.tooSmall": "Файл занадто малий",
"validation.bytes": "байт",
"compress.error.fileAccess": "Неможливо отримати доступ до файлу",
"compress.error.unknown": "невідома помилка",
"compress.error.tooLarge": "Зображення завелике для безпечного стиснення",
"compress.error.unsupportedFormat": "Непідтримуваний формат файлу",
"compress.error.copyCompressed": "Не вдалося скопіювати стиснений файл",
"compress.error.copyCompressedJpeg": "Не вдалося скопіювати стиснений JPEG файл",
"compress.error.pngQuality": "PNG-кодек не зміг забезпечити заданий діапазон якості",
"section.quality": "Якість стиснення",
"section.paths": "Шляхи",
"section.automation": "Автоматизація",
"section.stats": "Статистика та кеш",
"section.move": "Переміщення стиснених файлів",
"section.cacheBackups": "Бекапи кешу",
"section.instructions": "Інструкції",
"quality.png.name": "Якість PNG (мін-макс)",
"quality.png.desc": "Діапазон якості для стиснення PNG (65-80 за замовчуванням)",
"quality.jpeg.name": "Якість JPEG",
"quality.jpeg.desc": "Якість стиснення JPEG (1-95)",
"paths.allowedRoots.name": "Дозволені корені",
"paths.allowedRoots.desc": "Виберіть папки, де дозволено стиснення (порожньо = всі шляхи)",
"paths.allowedRoots.empty": "Не вибрано (стискаємо всюди)",
"paths.allowedRoots.pill.remove": "Натисніть, щоб видалити",
"paths.allowedRoots.modal.placeholder": "Виберіть папку...",
"paths.allowedRoots.cannotAddRoot": "Залиште список порожнім, щоб дозволити всі папки",
"paths.allowedRoots.clear": "Очистити список",
"paths.output.name": "Вихідна папка",
"paths.output.desc": "Папка для збереження стиснених файлів",
"auto.newFiles.name": "Автостиснення нових файлів",
"auto.newFiles.desc": "Автоматично стискати нові зображення при додаванні до vault",
"auto.bg.name": "Автоматичне фонове стиснення",
"auto.bg.desc": "Автоматично стискати у фоні, коли ви неактивні",
"auto.bg.threshold.name": "Поріг для фонового стиснення",
"auto.bg.threshold.desc": "Кількість нестиснених зображень для автозапуску",
"guard.disabled": "{id} тимчасово вимкнено під час стиснення",
"guard.restored": "{id} відновлено після стиснення",
"auto.retention.toggle.name": "Автоочищення бекапів зображень",
"auto.retention.toggle.desc": "Видаляти бекапи зображень за строком зберігання",
"auto.retention.days.name": "Строк зберігання бекапів (днів)",
"auto.retention.days.desc": "Видаляти бекапи, старші за вказану кількість днів",
"auto.move.toggle.name": "Увімкнути автопереміщення стиснених файлів",
"auto.move.toggle.desc": "Автоматично переміщувати стиснені файли при досягненні порогу",
"auto.move.threshold.name": "Поріг автопереміщення (шт.)",
"auto.move.threshold.desc": "Скільки файлів у 'Compressed' потрібно для автопереміщення",
"auto.queueFull": "Чергу автостиснення заповнено ({max}); нові файли пропущено",
"background.starting": "Фонове стиснення запущено для зображень: {count}",
"background.finished": "Фонове стиснення завершено, стиснено зображень: {count}",
"auto.bg.inactivity.name": "Поріг неактивності (хвилини)",
"auto.bg.inactivity.desc": "Скільки хвилин без вводу чекати перед запуском фонового стиснення",
"auto.cleanupGhosts.name": "Автоочищення 'привидів' при старті",
"auto.cleanupGhosts.desc": "Автоматично видаляти записи кешу, що вказують на видалені файли, при запуску Obsidian",
"stats.uncompressed.name": "Нестиснених зображень",
"stats.uncompressed.ready": "зображень готові до стиснення",
"stats.cache.name": "Записів у кеші",
"stats.cache.entries": "записів",
"stats.cache.size": "розмір",
"stats.cache.retention.name": "Зберігання кешу (місяці)",
"stats.cache.retention.desc": "Видаляти записи кешу, які не використовувалися вибрану кількість місяців",
"cache.corruptSaved": "Кеш не вдалося прочитати. Копію для відновлення збережено:",
"stats.ghosts.name": "Привидні записи",
"stats.ghosts.pointToMissing": "записів у кеші вказують на видалені файли",
"stats.ghosts.clearedCount": "Очищено привидних записів: {count}",
"move.title": "Перемістити стиснені файли",
"move.ready": "стиснені файли готові до переміщення",
"move.button": "Перемістити",
"move.noCompressedFolder": "Папку Compressed не знайдено",
"move.noneToMove": "Немає стиснених файлів для переміщення",
"move.noneWithOriginals": "Немає стиснених файлів з оригіналами у дозволених коренях",
"move.backupCreated": "Створено бекап оригінальних і стиснених файлів",
"move.backup.createdCount": "Створено резервну копію {count} оригінальних файлів",
"move.skip.ambiguousOriginal": "Неоднозначна назва оригіналу",
"move.skip.originalMissingBeforeBackup": "Оригінал відсутній перед бекапом",
"move.skip.compressedMissingBeforeBackup": "Стиснений файл відсутній перед бекапом",
"move.skip.originalModifiedDuringBackup": "Оригінал змінився під час бекапу",
"move.skip.compressedModifiedDuringBackup": "Стиснений файл змінився під час бекапу",
"move.skip.originalContentChangedDuringBackup": "Вміст оригіналу змінився під час бекапу",
"move.skip.compressedContentChangedDuringBackup": "Вміст стисненого файлу змінився під час бекапу",
"move.skip.contentChangedDuringCopy": "Вміст змінився під час копіювання бекапу",
"move.skip.originalNotFoundAtMoveTime": "Оригінал не знайдено під час переміщення",
"move.skip.selfMove": "Шлях стиснутого файлу збігається з оригіналом",
"move.skip.externalModification": "Зовнішня зміна під час переміщення",
"move.skip.invalidBackupTask": "Некоректне завдання бекапу",
"move.skip.noOriginalCandidate": "Кандидат оригіналу не знайдено",
"move.skip.unloading": "Плагін вивантажується",
"move.warning.externalModification": "Виявлено зовнішню зміну під час переміщення: {name}",
"backups.imagesFolder.name": "Папка з бекапами зображень",
"backups.imagesFolder.desc": "Відкрити папку з бекапами оригінальних/стиснених зображень",
"backups.imagesFolder.openButton": "Відкрити папку бекапів зображень",
"backups.imagesFolder.openError": "Не вдалося відкрити папку бекапів зображень",
"backups.imagesFolder.clearName": "Очистити бекапи зображень",
"backups.imagesFolder.clearDesc": "Видалити бекапи переміщених оригінальних/стиснених зображень",
"backups.imagesFolder.clearButton": "Очистити бекапи зображень",
"backups.imagesFolder.notFound": "Папку бекапів не знайдено",
"backups.imagesFolder.noneToDelete": "Немає бекапів для видалення",
"backups.imagesFolder.deletedCount": "Видалено бекапів оригінальних файлів: {count}",
"backups.imagesFolder.clearError": "Помилка під час очищення бекапів",
"backups.cache.title": "Бекапи кешу",
"backups.cache.folder.name": "Папка бекапів кешу",
"backups.cache.folder.desc": "Відкрити папку з файлами бекапів кешу",
"backups.cache.folder.openButton": "Відкрити папку бекапів кешу",
"backups.pathLabel": "Шлях",
"backups.foundLabel": "Знайдено бекапів",
"backups.cache.none": "Немає доступних бекапів кешу",
"backups.cache.restore": "Відновити кеш із бекапу",
"backups.cache.available": "Доступно бекапів:",
"backups.cache.selectPlaceholder": "-- Оберіть бекап --",
"common.add": "Додати",
"common.refresh": "Оновити",
"common.refreshing": "Оновлення...",
"common.processing": "Обробка...",
"common.clearCache": "Очистити кеш",
"common.refreshCache": "Оновити кеш",
"common.clearGhosts": "Очистити привиди",
"common.clear": "Очистити",
"common.clearing": "Очищення...",
"common.cancel": "Скасувати",
"common.close": "Закрити",
"units.kb": "КБ",
"instructions.usageTitle": "Використання:",
"instructions.notesTitle": "Примітки:",
"instructions.notes.saved": "Стиснені файли зберігаються в папку",
"instructions.notes.originalUnchanged": "Оригінальні файли не змінюються",
"instructions.notes.recompressionSkipped": "Повторне стиснення пропускається завдяки кешу"
,"progress.start": "Починаємо обробку..."
,"progress.processing": "Обробка"
,"progress.skippedAlready": "Пропущено (вже стиснено)"
,"progress.skipped": "Пропущено"
,"progress.compressed": "Стиснено"
,"progress.error": "Помилка"
,"progress.cancelling": "Скасування..."
,"progress.cancelled": "Скасовано"
,"status.loading": "Завантаження..."
,"status.indexing": "Індексація зображень..."
,"progress.completed": "Завершено! Стиснено"
,"folders.noneInVault": "У сховищі (vault) немає папок"
,"folderSelect.title": "Виберіть папку для стиснення зображень"
,"folderSelect.selectLabel": "Папка"
,"folderSelect.root": "Коренева папка"
,"folderSelect.select": "Вибрати"
,"folderSelect.cancel": "Скасувати"
,"instructions.action.rightClick": "Клацніть правою кнопкою по зображенню →"
,"instructions.action.commandPalette": "Палітра команд →"
,"savings.original": "Оригінал"
,"savings.current": "Поточний"
,"savings.saved": "Заощаджено"
,"tooltip.savings.header": "Деталі заощадження місця"
,"tooltip.savings.original": "Початковий розмір:"
,"tooltip.savings.current": "Поточний розмір:"
,"tooltip.savings.saved": "Заощаджено місця:"
,"tooltip.savings.filesProcessed": "Опрацьовано файлів:"
,"tooltip.savings.estimated": "оцінено"
}
};
// Optional external translations loader (lang/*.json). Preloaded async; t() stays sync and memory-only.
type TranslationParams = Record<string, string | number>;
type LoadedLangCache = {
dict: Record<string, string>;
loadedAt: number;
};
const LOADED_LANGS: Record<string, LoadedLangCache> = {};
const WARNED_LANG_LOAD_ERRORS = new Set<string>();
export function resolvePluginDirFromApp(app: LocaleApp | null | undefined): string | null {
try {
const configDir = app?.vault?.configDir;
if (!configDir) {
return null;
}
const basePath = getVaultBasePath(app);
return path.join(basePath, configDir, "plugins", "local-image-compress");
} catch {
return null;
}
}
function normalizeLanguageTag(lang: string | null | undefined): string {
return String(lang || "en").toLowerCase();
}
function getPrimaryLanguage(lang: string): string {
const fullLang = String(lang || "en").toLowerCase();
return fullLang.split(/[_.-]/)[0] || "en";
}
function getBuiltinLanguage(lang: string): "en" | "ru" | "uk" {
const primary = getPrimaryLanguage(lang);
if (primary === "ru" || primary === "be" || primary === "by") return "ru";
if (primary === "uk" || primary === "ua") return "uk";
return "en";
}
function getExternalLanguageCandidates(lang: string): string[] {
const fullLang = normalizeLanguageTag(lang);
const primary = getPrimaryLanguage(fullLang);
return Array.from(new Set([fullLang, primary].filter(Boolean)));
}
function getExternalCacheKey(pluginDir: string, lang: string): string {
return `${normalizeVaultPathForComparison(pluginDir)}\0${normalizeLanguageTag(lang)}`;
}
function normalizeTranslationDict(raw: unknown): Record<string, string> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
return {};
}
const normalized: Record<string, string> = {};
for (const [key, value] of Object.entries(raw)) {
if (typeof value === "string") {
normalized[key] = value;
}
}
return normalized;
}
function warnExternalLanguageLoadFailure(_app: LocaleApp | null | undefined, filePath: string, error: unknown) {
const warningKey = normalizeVaultPathForComparison(filePath);
if (WARNED_LANG_LOAD_ERRORS.has(warningKey)) {
return;
}
WARNED_LANG_LOAD_ERRORS.add(warningKey);
console.warn(getLogTag({ manifest: { name: 'Local Image Compress' } }), "i18n: failed to load external lang file", filePath, error);
try {
new Notice(`${I18N["en"]?.["i18n.externalLoadFailed"] || "External language file could not be loaded"}: ${path.basename(filePath)}`, 10000);
} catch (noticeError) {
console.debug(getLogTag({ manifest: { name: 'Local Image Compress' } }), "i18n: failed to show external lang warning", noticeError);
}
}
export async function preloadExternalLanguages(app: LocaleApp | null | undefined, lang: string = getCurrentLang(app)): Promise<Record<string, string>> {
const pluginDir = resolvePluginDirFromApp(app);
if (!pluginDir) {
return {};
}
const cacheKey = getExternalCacheKey(pluginDir, lang);
const externalDict: Record<string, string> = {};
for (const candidate of getExternalLanguageCandidates(lang)) {
const langFile = path.join(pluginDir, "lang", `${candidate}.json`);
try {
const raw = await fs.promises.readFile(langFile, "utf8");
Object.assign(externalDict, normalizeTranslationDict(JSON.parse(raw)));
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
warnExternalLanguageLoadFailure(app, langFile, error);
}
}
}
LOADED_LANGS[cacheKey] = { dict: externalDict, loadedAt: Date.now() };
return externalDict;
}
export function getMergedDict(app: LocaleApp | null | undefined, lang: string): Record<string, string> {
const pluginDir = resolvePluginDirFromApp(app);
const builtinLang = getBuiltinLanguage(lang);
const merged = Object.assign({}, I18N["en"] || {}, I18N[builtinLang] || {});
const external = pluginDir ? LOADED_LANGS[getExternalCacheKey(pluginDir, lang)]?.dict : null;
if (external) {
Object.assign(merged, external);
}
return merged;
}
export function getUserLang(app: LocaleApp | null | undefined): string {
try {
const detected = typeof app?.getLanguage === "function" ? app.getLanguage() : null;
const raw = detected && detected !== "system" ? detected : null;
const l = normalizeLanguageTag(raw || "en");
const primary = getPrimaryLanguage(l);
if (primary === "ru" || primary === "be" || primary === "by") return "ru";
if (primary === "uk" || primary === "ua") return "uk";
return "en";
} catch (error) {
console.debug(getLogTag({ manifest: { name: 'Local Image Compress' } }), "i18n: failed to detect user language", error);
}
return "en";
}
export function getCurrentLang(app: LocaleApp | null | undefined): string {
return getUserLang(app);
}
function interpolateTranslation(value: string, params: TranslationParams): string {
let translated = value;
for (const [paramKey, paramValue] of Object.entries(params)) {
translated = translated.replace(new RegExp(`\\{${paramKey}\\}`, "g"), String(paramValue));
}
return translated;
}
export function t(app: LocaleApp | null | undefined, key: string, params: TranslationParams = {}): string {
if (!key) {
return "[missing translation key]";
}
const lang = getCurrentLang(app);
const dict = getMergedDict(app, lang);
const value = (dict && dict[key]) || (I18N["en"] && I18N["en"][key]) || `[${key}]`;
return interpolateTranslation(value, params);
}

232
src-ts/image-index.ts Normal file
View file

@ -0,0 +1,232 @@
import { isAllowedByRoots, isInsideOutputFolder } from "./utils";
import type { CachePathEntries, FreshCacheEntry } from "./types";
import type { App, TFile } from "obsidian";
export type ImageIndexFile = TFile;
export type ImageIndexRecord = {
path: string;
file: ImageIndexFile;
extension: string;
size: number;
mtime: number;
allowed: boolean;
processed: boolean;
};
export type ImageIndexSnapshot = {
totalImages: number;
uncompressedImages: number;
};
type ImageIndexOptions = {
getOutputFolder: () => string;
getAllowedRoots: () => string[];
getSupportedExtensions: () => string[];
yieldToUi: () => Promise<void>;
batchSize?: number;
};
type ImageIndexCache = {
isFileAlreadyProcessed(file: ImageIndexFile): Promise<boolean>;
getEntriesByPathMap?: () => Map<string, CachePathEntries>;
getEntriesForPathFromMap?: (filePath: string, entriesByPath: Map<string, CachePathEntries>) => CachePathEntries;
getFreshEntryForFileFromEntries?: (file: ImageIndexFile, entries?: CachePathEntries) => Promise<FreshCacheEntry | null>;
};
export class ImageIndex {
private records = new Map<string, ImageIndexRecord>();
private pendingRebuildMutations = new Map<string, ImageIndexRecord | null>();
private ready = false;
private generation = 0;
private rebuildingGeneration: number | null = null;
private snapshot: ImageIndexSnapshot = {
totalImages: 0,
uncompressedImages: 0
};
constructor(private app: App, private options: ImageIndexOptions) {}
isReady() {
return this.ready;
}
getSnapshot() {
return this.snapshot;
}
getAllFiles() {
return Array.from(this.records.values())
.filter((record) => record.allowed)
.map((record) => record.file);
}
getUncompressedFiles() {
return Array.from(this.records.values())
.filter((record) => record.allowed && !record.processed)
.map((record) => record.file);
}
async rebuild(cache: ImageIndexCache) {
const generation = ++this.generation;
this.rebuildingGeneration = generation;
const wasReady = this.ready;
this.ready = false;
this.pendingRebuildMutations.clear();
const nextRecords = new Map<string, ImageIndexRecord>();
try {
const files = this.app.vault.getFiles();
const batchSize = this.options.batchSize || 150;
for (let i = 0; i < files.length; i += batchSize) {
if (generation !== this.generation) {
return;
}
for (const file of files.slice(i, i + batchSize)) {
const record = this.createRecord(file);
if (record) {
nextRecords.set(record.path, record);
}
}
if (i + batchSize < files.length) {
await this.options.yieldToUi();
}
}
if (files.length > 0) {
await this.options.yieldToUi();
}
await this.refreshProcessedStatesForRecords(nextRecords, cache, generation);
if (generation === this.generation) {
for (const [path, record] of this.pendingRebuildMutations) {
if (record) {
nextRecords.set(path, record);
} else {
nextRecords.delete(path);
}
}
this.records = nextRecords;
this.ready = true;
this.rebuildingGeneration = null;
this.pendingRebuildMutations.clear();
this.recalculateSnapshot();
}
} catch (error) {
// PPP2-B-2: an exception during rebuild must not leave the index permanently
// unready. nextRecords is built separately, so this.records still holds the
// prior snapshot — restore the previous ready state for the current generation.
if (generation === this.generation) {
this.ready = wasReady;
this.rebuildingGeneration = null;
}
throw error;
}
}
async upsert(file: ImageIndexFile, cache: ImageIndexCache) {
const record = this.createRecord(file);
if (!record) {
this.remove(file?.path);
return;
}
record.processed = await cache.isFileAlreadyProcessed(file);
this.records.set(record.path, record);
this.trackRebuildMutation(record.path, record);
this.recalculateSnapshot();
}
async rename(file: ImageIndexFile, oldPath: string, cache: ImageIndexCache) {
this.remove(oldPath);
await this.upsert(file, cache);
}
remove(filePath: string) {
if (filePath) {
this.records.delete(filePath);
this.trackRebuildMutation(filePath, null);
this.recalculateSnapshot();
}
}
async refreshFile(file: ImageIndexFile, cache: ImageIndexCache) {
await this.upsert(file, cache);
}
async refreshProcessedStates(cache: ImageIndexCache, generation = this.generation) {
await this.refreshProcessedStatesForRecords(this.records, cache, generation);
if (generation === this.generation) {
this.recalculateSnapshot();
}
}
private async refreshProcessedStatesForRecords(recordsByPath: Map<string, ImageIndexRecord>, cache: ImageIndexCache, generation: number) {
const batchSize = this.options.batchSize || 150;
const entriesByPath = cache.getEntriesByPathMap ? cache.getEntriesByPathMap() : null;
const recordPaths = Array.from(recordsByPath.keys());
for (let i = 0; i < recordPaths.length; i += batchSize) {
if (generation !== this.generation) {
return;
}
for (const recordPath of recordPaths.slice(i, i + batchSize)) {
const record = recordsByPath.get(recordPath);
if (!record) {
continue;
}
if (entriesByPath && cache.getEntriesForPathFromMap && cache.getFreshEntryForFileFromEntries) {
record.processed = !!await cache.getFreshEntryForFileFromEntries(record.file, cache.getEntriesForPathFromMap(record.path, entriesByPath));
} else {
record.processed = await cache.isFileAlreadyProcessed(record.file);
}
}
}
}
private createRecord(file: ImageIndexFile): ImageIndexRecord | null {
if (!file?.path || !file?.extension || !file.stat) {
return null;
}
const extension = file.extension.toLowerCase();
if (!this.options.getSupportedExtensions().includes(extension)) {
return null;
}
if (isInsideOutputFolder(file.path, this.options.getOutputFolder())) {
return null;
}
const allowedRoots = this.options.getAllowedRoots();
const allowed = isAllowedByRoots(file.path, allowedRoots);
return {
path: file.path,
file,
extension,
size: file.stat.size,
mtime: file.stat.mtime,
allowed,
processed: false
};
}
private trackRebuildMutation(path: string, record: ImageIndexRecord | null) {
if (this.rebuildingGeneration === null) {
return;
}
this.pendingRebuildMutations.set(path, record);
}
private recalculateSnapshot() {
let uncompressedImages = 0;
let totalImages = 0;
for (const record of this.records.values()) {
if (!record.allowed) {
continue;
}
totalImages++;
if (!record.processed) {
uncompressedImages++;
}
}
this.snapshot = {
totalImages,
uncompressedImages
};
}
}

289
src-ts/image-scanner.ts Normal file
View file

@ -0,0 +1,289 @@
import * as obsidian from "obsidian";
import * as path from "path";
import { getLogTag, getVaultFileByPath, normalizeVaultPath } from "./utils";
import type LocalImageCompressPlugin from "./plugin";
type ImageLookup = {
imageFiles: obsidian.TFile[];
byPath: Map<string, obsidian.TFile>;
byName: Map<string, obsidian.TFile[]>;
};
const MARKDOWN_IMAGE_TARGET_MAX_PAREN_DEPTH = 100;
const MARKDOWN_IMAGE_TARGET_MAX_LENGTH = 4096;
export class ImageScanner {
private readonly plugin: LocalImageCompressPlugin;
private imageLookupCache: { source: obsidian.TFile[]; lookup: ImageLookup } | null;
constructor(plugin: LocalImageCompressPlugin) {
this.plugin = plugin;
this.imageLookupCache = null;
}
isCompressibleImageTarget(imagePath: string | null | undefined) {
const extension = path.extname(imagePath || "").slice(1).toLowerCase();
return ["png", "jpg", "jpeg"].includes(extension);
}
normalizeEmbeddedImageTarget(rawTarget: unknown): string | null {
let target = typeof rawTarget === "string" ? rawTarget.trim() : "";
if (!target) {
return null;
}
if (/^(https?:|data:)/i.test(target)) {
return null;
}
if (target.startsWith("<")) {
const closingIndex = target.indexOf(">");
if (closingIndex === -1) {
return null;
}
target = target.slice(1, closingIndex);
} else {
target = target.replace(/\s+(['"]).*\1\s*$/, "").trim();
}
if (/^(https?:|data:)/i.test(target)) {
return null;
}
const targetBeforeHash = target.split("#")[0] || "";
target = (targetBeforeHash.split("?")[0] || "").trim();
target = target.replace(/^\.\/+/, "");
try {
target = decodeURIComponent(target);
} catch (error) {
console.debug(getLogTag(this.plugin), "Failed to decode embedded image target:", error);
}
target = target.replace(/\\([() |])/g, "$1");
return this.isCompressibleImageTarget(target) ? target : null;
}
stripMarkdownCode(content: string): string {
return String(content || "")
.replace(/(^|\n)(```|~~~)[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g, "$1")
.replace(/`[^`\n]*`/g, "");
}
getWikiTargetBeforeAlias(rawTarget: string): string {
let escaped = false;
for (let index = 0; index < rawTarget.length; index++) {
const char = rawTarget[index];
if (escaped) {
escaped = false;
continue;
}
if (char === "\\") {
escaped = true;
continue;
}
if (char === "|") {
return rawTarget.slice(0, index);
}
}
return rawTarget;
}
buildImageLookup(allFiles: obsidian.TFile[]): ImageLookup {
if (this.imageLookupCache?.source === allFiles) {
return this.imageLookupCache.lookup;
}
const imageFiles = allFiles.filter((file) => this.plugin.isImageFile(file));
const byPath = new Map<string, obsidian.TFile>();
const byName = new Map<string, obsidian.TFile[]>();
for (const file of imageFiles) {
byPath.set(file.path, file);
const namedFiles = byName.get(file.name) || [];
namedFiles.push(file);
byName.set(file.name, namedFiles);
}
const lookup = { imageFiles, byPath, byName };
this.imageLookupCache = { source: allFiles, lookup };
return lookup;
}
invalidateImageLookupCache() {
this.imageLookupCache = null;
}
resolveNoteRelativeTarget(target: string, notePath: string): string | null {
const normalizedTarget = String(target || "").replace(/\\/g, "/");
if (!normalizedTarget || normalizedTarget.startsWith("/") || /^[a-zA-Z]:/.test(normalizedTarget)) {
return null;
}
const normalizedNotePath = String(notePath || "").replace(/\\/g, "/");
const noteDir = normalizedNotePath.includes("/") ? path.posix.dirname(normalizedNotePath) : "";
const resolved = path.posix.normalize(noteDir ? `${noteDir}/${normalizedTarget}` : normalizedTarget).replace(/^\/+/, "");
if (!resolved || resolved === "." || resolved === ".." || resolved.startsWith("../")) {
return null;
}
return resolved;
}
resolveImageTarget(target: string, lookupOrAllFiles: ImageLookup | obsidian.TFile[], notePath = "", preferNoteRelative = false): obsidian.TFile | null {
const lookup = Array.isArray(lookupOrAllFiles) ? this.buildImageLookup(lookupOrAllFiles) : lookupOrAllFiles;
const normalizedTarget = normalizeVaultPath(target);
const candidatePaths: string[] = [];
if (preferNoteRelative) {
const relativeTarget = this.resolveNoteRelativeTarget(normalizedTarget, notePath);
if (relativeTarget) {
candidatePaths.push(relativeTarget);
}
}
candidatePaths.push(normalizedTarget);
for (const candidatePath of candidatePaths) {
const indexedFile = lookup.byPath.get(candidatePath);
if (indexedFile) {
return indexedFile;
}
const directFile = getVaultFileByPath(this.plugin.app.vault, candidatePath);
if (directFile && this.plugin.isImageFile(directFile)) {
return directFile;
}
}
if (!normalizedTarget) {
return null;
}
const directFile = getVaultFileByPath(this.plugin.app.vault, normalizedTarget);
if (directFile && this.plugin.isImageFile(directFile)) {
return directFile;
}
const hasFolder = normalizedTarget.includes("/");
const candidates = hasFolder
? lookup.imageFiles.filter((file) => file.path === normalizedTarget || file.path.endsWith(`/${normalizedTarget}`))
: lookup.byName.get(normalizedTarget) || [];
if (candidates.length === 1) {
return candidates[0] ?? null;
}
if (candidates.length > 1) {
console.warn(getLogTag(this.plugin), "Ambiguous image embed target skipped:", normalizedTarget, candidates.map((file) => file.path));
}
return null;
}
extractMarkdownImageTargets(content: string): string[] {
const targets: string[] = [];
let searchIndex = 0;
while (searchIndex < content.length) {
const imageStart = content.indexOf("![", searchIndex);
if (imageStart === -1) {
break;
}
const destinationStart = content.indexOf("](", imageStart + 2);
if (destinationStart === -1) {
searchIndex = imageStart + 2;
continue;
}
let index = destinationStart + 2;
let depth = 0;
let targetLength = 0;
const targetParts: string[] = [];
let closed = false;
let aborted = false;
const appendTargetPart = (part: string) => {
if (targetLength + part.length > MARKDOWN_IMAGE_TARGET_MAX_LENGTH) {
aborted = true;
return false;
}
targetParts.push(part);
targetLength += part.length;
return true;
};
while (index < content.length) {
const char = content[index];
if (char === undefined) {
break;
}
if (char === "\\") {
if (!appendTargetPart(char)) {
break;
}
const escapedChar = content[index + 1];
if (escapedChar !== undefined) {
if (!appendTargetPart(escapedChar)) {
break;
}
index += 2;
continue;
}
index++;
continue;
}
if (char === "(") {
depth++;
if (depth > MARKDOWN_IMAGE_TARGET_MAX_PAREN_DEPTH || !appendTargetPart(char)) {
aborted = true;
break;
}
} else if (char === ")") {
if (depth === 0) {
closed = true;
index++;
break;
}
depth--;
if (!appendTargetPart(char)) {
break;
}
} else {
if (!appendTargetPart(char)) {
break;
}
}
index++;
}
if (closed && !aborted) {
targets.push(targetParts.join(""));
searchIndex = index;
} else {
searchIndex = destinationStart + 2;
}
}
return targets;
}
async getImagesInNote(file: obsidian.TFile): Promise<obsidian.TFile[]> {
try {
const content = await this.plugin.app.vault.cachedRead(file);
if (this.plugin.isUnloading) {
return [];
}
const searchableContent = this.stripMarkdownCode(content);
const targets: Array<{ target: string; preferNoteRelative: boolean }> = [];
let match: RegExpExecArray | null;
const wikiImageRegex = /!\[\[([^\]]+)\]\]/g;
while ((match = wikiImageRegex.exec(searchableContent)) !== null) {
const rawWikiTarget = match[1];
if (!rawWikiTarget) {
continue;
}
const wikiTarget = this.normalizeEmbeddedImageTarget(this.getWikiTargetBeforeAlias(rawWikiTarget));
if (wikiTarget) {
targets.push({ target: wikiTarget, preferNoteRelative: false });
}
}
for (const markdownRawTarget of this.extractMarkdownImageTargets(searchableContent)) {
const markdownTarget = this.normalizeEmbeddedImageTarget(markdownRawTarget);
if (markdownTarget) {
targets.push({ target: markdownTarget, preferNoteRelative: true });
}
}
if (targets.length === 0) {
return [];
}
const imageFiles: obsidian.TFile[] = [];
const seenPaths = new Set<string>();
const allFiles = this.plugin.app.vault.getFiles();
const lookup = this.buildImageLookup(allFiles);
for (const { target, preferNoteRelative } of targets) {
const foundFile = this.resolveImageTarget(target, lookup, file?.path || "", preferNoteRelative);
if (foundFile && !seenPaths.has(foundFile.path)) {
seenPaths.add(foundFile.path);
imageFiles.push(foundFile);
}
}
return imageFiles;
} catch {
return [];
}
}
}

1
src-ts/main.ts Normal file
View file

@ -0,0 +1 @@
export { default } from "./plugin";

1026
src-ts/move-service.ts Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,346 @@
import * as obsidian from "obsidian";
import { t } from "./i18n";
import { INTERNAL_PLUGIN_GUARD_TIMEOUT_MS } from "./settings";
import { getLogTag, getPluginName } from "./utils";
import type LocalImageCompressPlugin from "./plugin";
import type { TimerHandle } from "./types";
interface PluginDisableGuard {
count: number;
wasEnabled: boolean;
disabledByGuard: boolean;
observedEnabledAfterGuardDisable: boolean;
monitorTimer: TimerHandle | null;
releasing: boolean;
ready: Promise<void>;
}
type InternalPluginRegistry = {
enabledPlugins?: Set<string>;
disablePlugin?: (id: string) => Promise<void> | void;
enablePlugin?: (id: string) => Promise<void> | void;
};
type AppWithInternalPluginRegistry = obsidian.App & {
plugins?: InternalPluginRegistry;
};
/**
* Temporarily disables a small, explicit allow-list of third-party plugins for the
* duration of a compression or move operation, then restores them.
*
* Reviewer note - why this uses the undocumented app.plugins.enable/disablePlugin:
* The only guarded id is "obsidian-paste-image-rename" (see the plugin's
* pluginsToDisableDuringCompression allow-list). That plugin registers a
* vault.on("create") handler that fires for every image added to the vault within
* ~1s of creation - unconditionally for names starting with "Pasted image ", and for
* all images when its "Handle all attachments" option is enabled. While this plugin
* writes compressed outputs, those fresh files trip that handler:
* - with an active Markdown view it renames our just-written output (which breaks the
* compressed -> original mapping the move step relies on) or opens a rename modal
* per file;
* - with no active Markdown view it shows an "Error: No active file found" notice for
* every created file, spamming the UI during batch runs.
* Obsidian exposes no public/typed API for one plugin to ask another to pause, so the
* only reliable mitigation is to disable that one plugin while the operation runs.
*
* The behavior is deliberately narrow and reversible:
* - it touches only ids in the plugin's pluginsToDisableDuringCompression allow-list,
* and only while an operation is in flight;
* - the allow-list is always guarded during compression and move operations because
* the output mapping depends on those writes not being renamed by another plugin;
* - it always restores what it disabled (with retries) and skips restore ownership if
* the plugin's enabled state changed externally during the operation.
* The app.plugins access is feature-detected and every call degrades gracefully on
* failure.
*/
export class PluginGuardService {
private readonly plugin: LocalImageCompressPlugin;
private readonly guards = new Map<string, PluginDisableGuard>();
private readonly enableRetryTimers = new Map<string, TimerHandle>();
operationTimeoutMs: number;
constructor(plugin: LocalImageCompressPlugin) {
this.plugin = plugin;
this.operationTimeoutMs = INTERNAL_PLUGIN_GUARD_TIMEOUT_MS;
}
private getPluginRegistry(): InternalPluginRegistry | undefined {
return (this.plugin.app as AppWithInternalPluginRegistry).plugins;
}
async acquire(id: string): Promise<void> {
while (true) {
const existingGuard = this.guards.get(id);
if (!existingGuard) {
const wasEnabled = !!this.getPluginRegistry()?.enabledPlugins?.has(id);
const guard: PluginDisableGuard = {
count: 1,
wasEnabled,
disabledByGuard: false,
observedEnabledAfterGuardDisable: false,
monitorTimer: null,
releasing: false,
ready: Promise.resolve()
};
guard.ready = (async () => {
if (wasEnabled) {
const disabled = await this.runPluginOperation(id, "disable", () => this.getPluginRegistry()?.disablePlugin?.(id));
if (disabled && !this.isPluginEnabled(id)) {
guard.disabledByGuard = true;
this.startGuardStateMonitor(id, guard);
this.showGuardNotice("guard.disabled", id);
} else if (disabled) {
console.debug(getLogTag(this.plugin), `Plugin ${id} was still enabled after guard disable; skipping restore ownership.`);
}
}
})();
this.guards.set(id, guard);
try {
await guard.ready;
} catch (error) {
this.guards.delete(id);
throw error;
}
return;
}
if (existingGuard.releasing) {
try {
await existingGuard.ready;
} catch (error) {
console.warn(getLogTag(this.plugin), `Previous plugin guard release failed for ${id}:`, error);
}
continue;
}
existingGuard.count++;
try {
await existingGuard.ready;
} catch (error) {
existingGuard.count = Math.max(0, existingGuard.count - 1);
throw error;
}
return;
}
}
async release(id: string): Promise<void> {
const guard = this.guards.get(id);
if (!guard) {
return;
}
guard.count = Math.max(0, guard.count - 1);
if (guard.count > 0) {
return;
}
guard.releasing = true;
const disableReady = guard.ready;
guard.ready = (async () => {
await disableReady;
if (this.shouldRestoreGuardedPlugin(id, guard)) {
const restored = await this.runPluginOperation(id, "enable", () => this.getPluginRegistry()?.enablePlugin?.(id));
if (restored) {
this.showGuardNotice("guard.restored", id);
}
}
})();
try {
await guard.ready;
} catch (error) {
console.error(getLogTag(this.plugin), `Error enabling plugin ${id}:`, error);
} finally {
if (guard.count === 0) {
this.stopGuardStateMonitor(guard);
this.guards.delete(id);
}
}
}
async releaseAllGuards(): Promise<void> {
const guards = Array.from(this.guards.entries());
await Promise.all(guards.map(async ([id, guard]) => {
guard.count = 0;
guard.releasing = true;
try {
await guard.ready;
} catch (error) {
console.warn(getLogTag(this.plugin), `Plugin guard was not ready during unload for ${id}:`, error);
}
try {
if (this.shouldRestoreGuardedPlugin(id, guard)) {
const restored = await this.runPluginOperation(id, "enable", () => this.getPluginRegistry()?.enablePlugin?.(id));
if (restored) {
this.showGuardNotice("guard.restored", id);
}
}
} catch (error) {
console.warn(getLogTag(this.plugin), `Failed to restore guarded plugin ${id} during unload:`, error);
} finally {
this.stopGuardStateMonitor(guard);
this.guards.delete(id);
}
}));
}
private isPluginEnabled(id: string) {
return !!this.getPluginRegistry()?.enabledPlugins?.has(id);
}
private shouldRestoreGuardedPlugin(id: string, guard: PluginDisableGuard) {
if (!guard.wasEnabled || !guard.disabledByGuard) {
return false;
}
if (this.isPluginEnabled(id)) {
return false;
}
if (guard.observedEnabledAfterGuardDisable) {
console.debug(getLogTag(this.plugin), `Skipping restore for ${id}; plugin state changed during guard.`);
return false;
}
return true;
}
private startGuardStateMonitor(id: string, guard: PluginDisableGuard) {
this.stopGuardStateMonitor(guard);
const poll = () => {
if (!this.guards.has(id) || guard.releasing) {
guard.monitorTimer = null;
return;
}
if (guard.disabledByGuard && this.isPluginEnabled(id)) {
guard.observedEnabledAfterGuardDisable = true;
}
guard.monitorTimer = typeof this.plugin.setWindowTimeout === "function"
? this.plugin.setWindowTimeout(poll, 250)
: window.setTimeout(poll, 250);
};
guard.monitorTimer = typeof this.plugin.setWindowTimeout === "function"
? this.plugin.setWindowTimeout(poll, 250)
: window.setTimeout(poll, 250);
}
private stopGuardStateMonitor(guard: PluginDisableGuard) {
if (!guard.monitorTimer) {
return;
}
this.plugin.clearWindowTimeout(guard.monitorTimer);
guard.monitorTimer = null;
}
showGuardNotice(key: "guard.disabled" | "guard.restored", id: string) {
new obsidian.Notice(`${getPluginName(this.plugin)}: ${t(this.plugin.app, key, { id })}`, 5000);
}
async runPluginOperation(id: string, action: "disable" | "enable", operation: () => Promise<void> | void, allowEnableRetry = true): Promise<boolean> {
let timer: TimerHandle | null = null;
let operationSucceeded = false;
let operationTimedOut = false;
const operationCompleted = Promise.resolve()
.then(operation)
.then(async () => {
operationSucceeded = true;
if (operationTimedOut && action === "disable") {
await this.restoreAfterLateDisable(id);
}
return true;
}, (error) => {
console.warn(getLogTag(this.plugin), `Could not ${action} plugin ${id}:`, error);
return false;
});
const timeout = new Promise<void>((resolve) => {
const callback = () => {
console.warn(getLogTag(this.plugin), `Timed out while trying to ${action} plugin ${id}; continuing without waiting for that plugin.`);
resolve();
};
timer = typeof this.plugin.setWindowTimeout === "function"
? this.plugin.setWindowTimeout(callback, this.operationTimeoutMs)
: window.setTimeout(callback, this.operationTimeoutMs);
});
const timedOut = await Promise.race([
operationCompleted.then(() => false),
timeout.then(() => true)
]);
if (timer) {
if (typeof this.plugin.clearWindowTimeout === "function") {
this.plugin.clearWindowTimeout(timer);
} else {
window.clearTimeout(timer);
}
}
if (timedOut && action === "disable") {
operationTimedOut = true;
} else if (timedOut && action === "enable" && allowEnableRetry) {
this.scheduleEnableRetry(id);
}
return !timedOut && operationSucceeded;
}
scheduleEnableRetry(id: string): void {
if (this.enableRetryTimers.has(id)) {
return;
}
const retryDelayMs = Math.max(this.operationTimeoutMs * 2, 10_000);
const retry = async () => {
this.enableRetryTimers.delete(id);
if (this.guards.has(id) || this.isPluginEnabled(id)) {
return;
}
try {
const restored = await this.runPluginOperation(id, "enable", () => this.getPluginRegistry()?.enablePlugin?.(id), false);
if (restored) {
this.showGuardNotice("guard.restored", id);
}
} catch (error) {
console.warn(getLogTag(this.plugin), `Could not retry restore for plugin ${id}:`, error);
}
};
const runRetry = () => {
retry().catch((error: unknown) => {
console.warn(getLogTag(this.plugin), `Unexpected retry failure for plugin ${id}:`, error);
});
};
const timer = typeof this.plugin.setWindowTimeout === "function"
? this.plugin.setWindowTimeout(runRetry, retryDelayMs)
: window.setTimeout(runRetry, retryDelayMs);
this.enableRetryTimers.set(id, timer);
}
async restoreAfterLateDisable(id: string): Promise<void> {
try {
if (this.guards.has(id)) {
return;
}
if (this.getPluginRegistry()?.enabledPlugins?.has(id)) {
return;
}
const restored = await this.runPluginOperation(id, "enable", () => this.getPluginRegistry()?.enablePlugin?.(id));
if (restored) {
this.showGuardNotice("guard.restored", id);
}
} catch (error) {
console.warn(getLogTag(this.plugin), `Could not restore plugin ${id} after a late disable:`, error);
}
}
async withDisabled<T>(pluginIds: string[], task: () => Promise<T> | T): Promise<T> {
const acquired: string[] = [];
try {
for (const id of pluginIds) {
await this.acquire(id);
acquired.push(id);
}
return await task();
} finally {
await this.releaseGuardsInParallel(acquired.reverse());
}
}
private async releaseGuardsInParallel(ids: string[]): Promise<void> {
const results = await Promise.allSettled(ids.map((id) => this.release(id)));
for (let index = 0; index < results.length; index++) {
const result = results[index];
if (result?.status === "rejected") {
console.warn(getLogTag(this.plugin), `Failed to release plugin guard for ${ids[index] || "unknown plugin"}:`, result.reason);
}
}
}
}

1541
src-ts/plugin.ts Normal file

File diff suppressed because it is too large Load diff

249
src-ts/progress-modal.ts Normal file
View file

@ -0,0 +1,249 @@
import * as obsidian from "obsidian";
import { t } from "./i18n";
import type LocalImageCompressPlugin from "./plugin";
import type { AnimationHandle, TimerHandle } from "./types";
import { getActiveWindowForApp } from "./utils";
type TextElement = HTMLElement & { setText(text: string): void };
type PendingProgressUpdate = {
current: number;
total: number;
status: string;
percentage: number;
};
export class ProgressModal extends obsidian.Modal {
private readonly plugin: LocalImageCompressPlugin;
private readonly progressLabel: string;
statusElement: TextElement | null;
progressContainer: HTMLElement | null;
progressElement: HTMLElement | null;
cancelButton: HTMLButtonElement | null;
private abortController: AbortController | null;
private cancelRequested: boolean;
private isClosed: boolean;
private closeTimer: TimerHandle | null;
private animationHandle: AnimationHandle | null;
private focusTimer: TimerHandle | null;
private pendingProgressUpdate: PendingProgressUpdate | null;
private cancelButtonCleanup: (() => void) | null;
private readonly returnFocusTo: HTMLElement | null;
constructor(plugin: LocalImageCompressPlugin, title: string) {
super(plugin.app);
this.plugin = plugin;
this.progressLabel = title;
this.statusElement = null;
this.progressContainer = null;
this.progressElement = null;
this.cancelButton = null;
this.abortController = null;
this.cancelRequested = false;
this.isClosed = true;
this.closeTimer = null;
this.animationHandle = null;
this.focusTimer = null;
this.pendingProgressUpdate = null;
this.cancelButtonCleanup = null;
this.returnFocusTo = plugin.captureModalFocusTarget();
this.titleEl.setText(title);
}
getActiveWindow() {
return getActiveWindowForApp(this.app) || window;
}
setModalTimeout(callback: () => void, delay: number) {
return (this.contentEl?.win || this.getActiveWindow()).setTimeout(callback, delay);
}
clearModalTimeout(timer: TimerHandle | null | undefined) {
if (timer === null || timer === undefined) {
return;
}
(this.contentEl?.win || this.getActiveWindow()).clearTimeout(timer as number);
}
requestModalAnimationFrame(callback: () => void) {
const ownerWindow = this.contentEl?.win || this.getActiveWindow();
if (ownerWindow.requestAnimationFrame) {
return ownerWindow.requestAnimationFrame(callback);
}
return this.setModalTimeout(callback, 0);
}
cancelModalAnimationFrame(handle: AnimationHandle | null | undefined) {
if (handle === null || handle === undefined) {
return;
}
const ownerWindow = this.contentEl?.win || this.getActiveWindow();
if (ownerWindow.cancelAnimationFrame) {
return ownerWindow.cancelAnimationFrame(handle as number);
}
return this.clearModalTimeout(handle);
}
override onOpen() {
const { contentEl } = this;
this.cancelRequested = false;
this.isClosed = false;
contentEl.empty();
contentEl.createDiv({ text: t(this.app, "progress.processing"), cls: "tiny-local-progress-title" });
this.statusElement = contentEl.createDiv({
text: t(this.app, "progress.start"),
cls: "tiny-local-progress-status"
});
this.statusElement.setAttribute("role", "status");
this.statusElement.setAttribute("aria-live", "polite");
this.statusElement.setAttribute("aria-atomic", "true");
const progressContainer = contentEl.createDiv({ cls: "tiny-local-progress-container" });
progressContainer.setAttribute("role", "progressbar");
progressContainer.setAttribute("aria-label", this.progressLabel);
progressContainer.setAttribute("aria-valuemin", "0");
progressContainer.setAttribute("aria-valuemax", "100");
progressContainer.setAttribute("aria-valuenow", "0");
progressContainer.setAttribute("aria-valuetext", t(this.app, "progress.start"));
this.progressContainer = progressContainer;
const progressBar = progressContainer.createDiv({ cls: "tiny-local-progress-bar" });
this.progressElement = progressBar.createDiv({ cls: "tiny-local-progress-fill" });
const actionsEl = contentEl.createDiv({ cls: "tiny-local-progress-actions" });
const cancelButton = actionsEl.createEl("button", {
text: t(this.app, "common.cancel"),
cls: "mod-warning tiny-local-progress-cancel"
});
cancelButton.type = "button";
cancelButton.setAttribute("aria-label", t(this.app, "common.cancel"));
const onCancelClick = () => this.requestCancel();
// modal-scoped: cleaned in onClose() via cancelButtonCleanup — registerDomEvent unavailable on Modal
cancelButton.addEventListener("click", onCancelClick);
this.cancelButtonCleanup = () => cancelButton.removeEventListener("click", onCancelClick);
this.cancelButton = cancelButton;
this.focusTimer = this.setModalTimeout(() => {
this.focusTimer = null;
if (!this.isClosed) {
cancelButton.focus();
}
}, 0);
// Use adaptive CSS classes instead of inline styles
contentEl.addClass("tiny-local-progress-modal");
}
setAbortController(controller: AbortController | null) {
this.abortController = controller;
}
requestCancel() {
if (this.isClosed || this.cancelRequested) {
return;
}
this.cancelRequested = true;
this.abortController?.abort();
if (this.cancelButton) {
this.cancelButton.disabled = true;
this.cancelButton.textContent = t(this.app, "progress.cancelling");
}
this.setStatus(t(this.app, "progress.cancelling"));
this.scheduleClose(1000);
}
updateProgress(current: number, total: number, status: string) {
if (this.isClosed || !this.statusElement || !this.progressElement) {
return;
}
const percentage = total > 0 ? Math.min(100, Math.max(0, current / total * 100)) : 0;
this.pendingProgressUpdate = { current, total, status, percentage };
if (this.animationHandle) {
return;
}
this.animationHandle = this.requestModalAnimationFrame(() => {
this.animationHandle = null;
const pendingUpdate = this.pendingProgressUpdate;
this.pendingProgressUpdate = null;
if (this.isClosed || !this.statusElement || !this.progressElement || !pendingUpdate) {
return;
}
this.statusElement.setText(`${pendingUpdate.status} (${pendingUpdate.current}/${pendingUpdate.total})`);
this.progressContainer?.setAttribute("aria-valuemax", String(Math.max(0, pendingUpdate.total)));
this.progressContainer?.setAttribute("aria-valuenow", String(Math.max(0, Math.min(pendingUpdate.current, pendingUpdate.total))));
this.progressContainer?.setAttribute("aria-valuetext", `${pendingUpdate.status} (${pendingUpdate.current}/${pendingUpdate.total})`);
this.progressElement.setCssProps({
"--local-image-compress-progress-width": `${pendingUpdate.percentage}%`
});
});
}
setStatus(status: string) {
if (this.isClosed || !this.statusElement) {
return;
}
this.statusElement.setText(status);
this.progressContainer?.setAttribute("aria-valuetext", status);
}
setCompleted(message: string) {
if (this.isClosed || !this.statusElement || !this.progressElement) {
return;
}
this.statusElement.setText(message);
const maximum = this.progressContainer?.getAttribute("aria-valuemax") || "100";
this.progressContainer?.setAttribute("aria-valuenow", maximum);
this.progressContainer?.setAttribute("aria-valuetext", message);
this.progressElement.setCssProps({
"--local-image-compress-progress-width": "100%"
});
this.progressElement.classList.add("tiny-local-progress-completed");
this.scheduleClose(2e3);
}
setCancelled(message: string) {
if (this.isClosed || !this.statusElement || !this.progressElement) {
return;
}
this.statusElement.setText(message);
this.progressContainer?.setAttribute("aria-valuetext", message);
this.progressElement.classList.add("tiny-local-progress-cancelled");
this.scheduleClose(1000);
}
setError(message: string) {
if (this.isClosed || !this.statusElement || !this.progressElement) {
return;
}
this.statusElement.setText(message);
this.progressContainer?.setAttribute("aria-valuetext", message);
this.progressElement.classList.add("tiny-local-progress-error");
this.scheduleClose(3e3);
}
private scheduleClose(delay: number) {
if (this.isClosed) {
return;
}
if (this.closeTimer) {
this.clearModalTimeout(this.closeTimer);
}
this.closeTimer = this.setModalTimeout(() => {
this.closeTimer = null;
if (!this.isClosed) {
this.close();
}
}, delay);
}
override onClose() {
this.isClosed = true;
if (this.closeTimer) {
this.clearModalTimeout(this.closeTimer);
this.closeTimer = null;
}
if (this.animationHandle) {
this.cancelModalAnimationFrame(this.animationHandle);
this.animationHandle = null;
}
if (this.focusTimer) {
this.clearModalTimeout(this.focusTimer);
this.focusTimer = null;
}
this.pendingProgressUpdate = null;
if (this.cancelButtonCleanup) {
this.cancelButtonCleanup();
this.cancelButtonCleanup = null;
}
// Remove classes on close
if (this.progressElement) {
this.progressElement.classList.remove("tiny-local-progress-completed", "tiny-local-progress-cancelled", "tiny-local-progress-error");
}
this.cancelButton = null;
this.abortController = null;
this.statusElement = null;
this.progressContainer = null;
this.progressElement = null;
this.plugin.untrackManagedModal(this);
this.plugin.restoreModalFocus(this.returnFocusTo);
}
}

View file

@ -0,0 +1,355 @@
import { t } from "./i18n";
import { getErrorCode, getLogTag, getVaultBasePath, toVaultRelativePath } from "./utils";
import * as fs from "fs";
import * as path from "path";
import { ConcurrencyLimiter } from "./concurrency-limiter";
import type LocalImageCompressPlugin from "./plugin";
import type { SavingsSnapshot } from "./types";
import type { TFile } from "obsidian";
export const FILE_SIZE_THRESHOLDS = {
KB_100: 100 * 1024,
KB_500: 500 * 1024,
MB_1: 1024 * 1024
};
// Conservative UI estimates used only when exact cache originalSize is unavailable.
export const COMPRESSION_RATIOS = {
PNG_SMALL: 2.5,
PNG_MEDIUM: 2.0,
PNG_LARGE: 1.8,
JPEG_SMALL: 1.4,
JPEG_LARGE: 1.3,
DEFAULT: 1.5
};
export const MAX_ESTIMATED_COMPRESSION_RATIO = 30;
export const SAVINGS_STATS_IO_CONCURRENCY = 8;
type SavingsFileLike = {
extension?: string;
stat?: {
size?: unknown;
};
};
export class SavingsCalculator {
private readonly plugin: LocalImageCompressPlugin;
constructor(plugin: LocalImageCompressPlugin) {
this.plugin = plugin;
}
async calculateSpaceSavings() {
const stats = await this.collectImageStats(this.plugin.getAllImageFiles());
return stats.savings;
}
getSavingsPercentage(savedSize: number, originalSize: number) {
if (!Number.isFinite(savedSize) || savedSize <= 0 || !Number.isFinite(originalSize) || originalSize <= 0) {
return 0;
}
return Math.max(0, Math.min(100, Math.round((savedSize / originalSize) * 100)));
}
async collectImageStats(allFiles: TFile[]) {
try {
if (allFiles.length === 0) {
return {
totalImages: 0,
uncompressedImages: 0,
savings: this.getEmptySavingsResult()
};
}
let originalSize = 0;
let currentSize = 0;
let processedFiles = 0;
let filesWithExactData = 0;
let estimatedFiles = 0;
let uncompressedImages = 0;
const entriesByPath = this.plugin.cache.getEntriesByPathMap();
const cacheLookupLimiter = new ConcurrencyLimiter(SAVINGS_STATS_IO_CONCURRENCY);
const compressedSizeLimiter = new ConcurrencyLimiter(SAVINGS_STATS_IO_CONCURRENCY);
const batchSize = 50;
for (let i = 0; i < allFiles.length; i += batchSize) {
if (this.plugin.isUnloading) {
return this.getInterruptedSavingsResult(allFiles.length, uncompressedImages);
}
const batch = allFiles.slice(i, i + batchSize);
const phaseData = await Promise.all(batch.map((file, index) => cacheLookupLimiter.run(async () => {
const freshCache = await this.plugin.cache.getFreshEntryForFileFromEntries(
file,
this.plugin.cache.getEntriesForPathFromMap(file.path, entriesByPath)
);
const cachedOutputSize = freshCache?.entry?.outputSize;
const needsSizeFetch = !!freshCache && (typeof cachedOutputSize !== "number" || cachedOutputSize <= 0);
return {
file,
index,
freshCache,
compressedPath: needsSizeFetch ? this.getCompressedFilePath(file.path) : null
};
})));
const fetchTasks = phaseData.filter((item) => item.compressedPath);
const fetchedSizes = await Promise.all(fetchTasks.map((item) =>
compressedSizeLimiter.run(() => this.getCompressedFileSize(item.compressedPath as string).catch(() => null))
));
const fetchedSizeByIndex = new Map<number, number>();
fetchTasks.forEach((item, index) => {
const fetchedSize = fetchedSizes[index];
fetchedSizeByIndex.set(item.index, typeof fetchedSize === "number" ? fetchedSize : 0);
});
for (const item of phaseData) {
const file = item.file;
const fileSize = file.stat.size;
const freshCache = item.freshCache;
if (freshCache) {
const entry = freshCache.entry;
const cachedOriginalSize = entry?.originalSize;
let compressedSize = typeof entry?.outputSize === "number" ? entry.outputSize : 0;
if (compressedSize <= 0) {
compressedSize = fetchedSizeByIndex.get(item.index) || 0;
}
const current = compressedSize > 0 ? compressedSize : fileSize;
if (cachedOriginalSize && cachedOriginalSize > 0) {
originalSize += cachedOriginalSize;
currentSize += current;
filesWithExactData++;
} else {
const estimatedOriginalSize = compressedSize > 0
? this.estimateOriginalSizeFromCurrent({ stat: { size: compressedSize }, extension: file.extension })
: this.estimateOriginalSizeFromCurrent(file);
originalSize += estimatedOriginalSize;
currentSize += current;
estimatedFiles++;
}
processedFiles++;
} else {
originalSize += fileSize;
currentSize += fileSize;
uncompressedImages++;
}
}
if (i + batchSize < allFiles.length && typeof this.plugin.yieldToUi === "function") {
await this.plugin.yieldToUi();
if (this.plugin.isUnloading) {
return this.getInterruptedSavingsResult(allFiles.length, uncompressedImages);
}
}
}
if (filesWithExactData === 0 && estimatedFiles === 0) {
return {
totalImages: allFiles.length,
uncompressedImages,
savings: this.getEmptySavingsResult(allFiles.length)
};
}
const savedSize = Math.max(0, originalSize - currentSize);
const savedPercentage = this.getSavingsPercentage(savedSize, originalSize);
return {
totalFiles: allFiles.length,
totalImages: allFiles.length,
uncompressedImages,
savings: {
originalSize,
currentSize,
savedSize,
savedPercentage,
processedFiles,
totalFiles: allFiles.length,
estimatedFiles
}
};
} catch (error) {
console.error(getLogTag(this.plugin), "Space savings calculation error:", error);
return {
totalImages: 0,
uncompressedImages: 0,
savings: this.getEmptySavingsResult()
};
}
}
getEmptySavingsResult(totalFiles = 0) {
return {
originalSize: 0,
currentSize: 0,
savedSize: 0,
savedPercentage: 0,
processedFiles: 0,
totalFiles,
estimatedFiles: 0
};
}
getInterruptedSavingsResult(totalFiles = 0, uncompressedImages = 0) {
return {
totalFiles,
totalImages: totalFiles,
uncompressedImages,
savings: this.getEmptySavingsResult(totalFiles)
};
}
validateSavingsData(savings: unknown): savings is SavingsSnapshot {
if (!savings) {
return false;
}
const candidate = savings as Partial<Record<keyof SavingsSnapshot, unknown>>;
const numericFields = [
"processedFiles",
"savedSize",
"originalSize",
"currentSize",
"savedPercentage",
"totalFiles",
"estimatedFiles"
];
if (!numericFields.every((field) => typeof candidate[field as keyof SavingsSnapshot] === "number" && Number.isFinite(candidate[field as keyof SavingsSnapshot]))) {
return false;
}
const typedSavings = savings as SavingsSnapshot;
const hasActivity = typedSavings.totalFiles > 0 || typedSavings.processedFiles > 0 || typedSavings.estimatedFiles > 0;
return hasActivity &&
typedSavings.savedSize >= 0 &&
typedSavings.originalSize >= 0 &&
typedSavings.currentSize >= 0 &&
typedSavings.savedPercentage >= 0 &&
typedSavings.savedPercentage <= 100 &&
typedSavings.savedSize <= typedSavings.originalSize &&
typedSavings.totalFiles >= 0 &&
typedSavings.estimatedFiles >= 0;
}
estimateOriginalSizeFromCurrent(file: SavingsFileLike): number {
try {
if (!file || !file.stat || typeof file.stat.size !== "number" || !Number.isFinite(file.stat.size) || file.stat.size <= 0) {
return 0;
}
const currentSize = file.stat.size;
const extension = (file.extension || "").toLowerCase();
const compressionRatio = this.getCompressionRatio(extension, currentSize, FILE_SIZE_THRESHOLDS);
if (!Number.isFinite(compressionRatio) || compressionRatio <= 0) {
return currentSize;
}
const estimatedSize = Math.round(currentSize * compressionRatio);
if (!Number.isFinite(estimatedSize) || estimatedSize <= 0 || estimatedSize > currentSize * MAX_ESTIMATED_COMPRESSION_RATIO) {
return currentSize;
}
return estimatedSize;
} catch (error) {
console.error(getLogTag(this.plugin), "Original size estimation error:", error);
return 0;
}
}
getCompressionRatio(extension: string, currentSize: number, sizes = FILE_SIZE_THRESHOLDS) {
const { KB_100, KB_500, MB_1 } = sizes;
const ratios = COMPRESSION_RATIOS;
switch (extension) {
case "png":
if (currentSize < KB_100) return ratios.PNG_SMALL;
if (currentSize < MB_1) return ratios.PNG_MEDIUM;
return ratios.PNG_LARGE;
case "jpg":
case "jpeg":
if (currentSize < KB_500) return ratios.JPEG_SMALL;
return ratios.JPEG_LARGE;
default:
return ratios.DEFAULT;
}
}
formatTooltipData(savings: SavingsSnapshot | null | undefined) {
if (!savings) {
return {
originalFormatted: "0 B",
currentFormatted: "0 B",
savedFormatted: "0 B",
estimatedIndicator: "",
estimatedText: ""
};
}
const originalFormatted = this.formatFileSize(savings.originalSize || 0);
const currentFormatted = this.formatFileSize(savings.currentSize || 0);
const savedFormatted = this.formatFileSize(savings.savedSize || 0);
const estimatedIndicator = (savings.estimatedFiles || 0) > 0 ? " ~" : "";
const estimatedText = (savings.estimatedFiles || 0) > 0 ? ` (${savings.estimatedFiles} ${t(this.plugin.app, "tooltip.savings.estimated")})` : "";
return {
originalFormatted,
currentFormatted,
savedFormatted,
estimatedIndicator,
estimatedText
};
}
async getCachedOriginalSize(filePath: string) {
try {
if (!filePath || !this.plugin.cache || !this.plugin.cache.cacheData || !this.plugin.cache.cacheData.entries) {
return null;
}
const entriesByPath = this.plugin.cache.getEntriesByPathMap();
const pathEntries = this.plugin.cache.getEntriesForPathFromMap(filePath, entriesByPath);
for (const [, entry] of pathEntries) {
if (entry && entry.originalSize && typeof entry.originalSize === "number" && entry.originalSize > 0) {
return entry.originalSize;
}
}
return null;
} catch (error) {
console.error(getLogTag(this.plugin), "Error getting original size from cache:", error);
return null;
}
}
formatFileSize(bytes: number) {
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
const i = Math.min(sizes.length - 1, Math.max(0, Math.floor(Math.log(bytes) / Math.log(k))));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}
async getCompressedFileSize(compressedFilePath: string): Promise<number | null> {
try {
const stats = await fs.promises.stat(compressedFilePath);
return stats.size;
} catch (error) {
if (getErrorCode(error) === "ENOENT") {
return 0;
}
console.warn(getLogTag(this.plugin), `Cannot read compressed file size: ${compressedFilePath}`, error);
return null;
}
}
getDisplaySavingsPercentage(value: unknown) {
const numeric = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) {
return 0;
}
return Math.max(0, Math.min(100, Math.round(numeric)));
}
getCompressedFilePath(originalPathOrVaultRelative: string) {
const basePath = getVaultBasePath(this.plugin.app);
const vaultRelativePath = toVaultRelativePath(originalPathOrVaultRelative, basePath);
return path.join(basePath, this.plugin.getOutputFolder(), vaultRelativePath);
}
}

View file

@ -0,0 +1,114 @@
import * as obsidian from "obsidian";
import * as fs from "fs";
import * as path from "path";
import type { default as LocalImageCompressPlugin } from "../plugin";
import { ConcurrencyLimiter } from "../concurrency-limiter";
import { getUserLang, t } from "../i18n";
import { getLogTag, getPluginName, openFilesystemPath } from "../utils";
// Lists cache backups (bounded stat fan-out) and renders the read-only backup modal.
export class CacheBackupsView {
constructor(private readonly plugin: LocalImageCompressPlugin) {}
async showCacheBackupsList() {
try {
const backupDir = this.plugin.getBackupStoragePaths().cacheBackups;
try {
await fs.promises.access(backupDir);
} catch {
await fs.promises.mkdir(backupDir, { recursive: true });
new obsidian.Notice(`${this.plugin.manifest?.name || "Local Image Compress"}: ${t(this.plugin.app, "backups.cache.title")}`);
return;
}
const backups = await this.plugin.cache.getAvailableBackups();
if (backups.length === 0) {
new obsidian.Notice(`${this.plugin.manifest?.name || "Local Image Compress"}: ${t(this.plugin.app, "backups.cache.none")}`);
return;
}
const locale = getUserLang(this.plugin.app);
const backupInfoLimiter = new ConcurrencyLimiter(8);
const infoItems = await Promise.all(backups.map((backup) => backupInfoLimiter.run(async () => {
try {
const backupPath = path.join(backupDir, backup);
const stats = await fs.promises.stat(backupPath);
const sizeKb = (stats.size / 1024).toFixed(1);
const date = stats.mtime.toLocaleString(locale);
return `${backup} ${sizeKb} ${t(this.plugin.app, "units.kb")}, ${date}`;
} catch {
return `${backup}`;
}
})));
const backupInfo = infoItems.join("\n");
this.showBackupModal(backupDir, backups, backupInfo);
} catch {
new obsidian.Notice(`${this.plugin.manifest?.name || "Local Image Compress"}: ${t(this.plugin.app, "backups.imagesFolder.openError")}`);
}
}
private showBackupModal(backupDir: string, backups: string[], backupInfo: string) {
const pluginName = getPluginName(this.plugin);
const owner = this.plugin;
const modal = new class extends obsidian.Modal {
listenerCleanups: Array<() => void>;
returnFocusTo: HTMLElement | null;
constructor(app: obsidian.App) {
super(app);
this.listenerCleanups = [];
this.returnFocusTo = owner.captureModalFocusTarget();
this.titleEl.setText(`${pluginName}: ${t(this.app, "backups.cache.title")}`);
}
override onOpen() {
const { contentEl } = this;
contentEl.createEl("p", { text: `${t(this.app, "backups.pathLabel")}: ${backupDir}` });
contentEl.createEl("p", { text: `${t(this.app, "backups.foundLabel")}: ${backups.length}` });
const list = contentEl.createDiv({ cls: "tiny-local-backup-list" });
list.setAttribute("role", "list");
list.setAttribute("aria-label", t(this.app, "backups.cache.title"));
backupInfo.split("\n").forEach((line: string) => {
const item = list.createDiv({ text: line });
item.setAttribute("role", "listitem");
});
const openButton = contentEl.createEl("button", {
text: t(this.app, "backups.imagesFolder.openButton"),
cls: "mod-cta"
});
openButton.type = "button";
const openBackupFolder = async () => {
try {
const openError = await openFilesystemPath(backupDir);
if (openError) {
console.error(getLogTag(owner), "Error opening cache backups folder:", openError);
new obsidian.Notice(`${pluginName}: ${t(this.app, "backups.imagesFolder.openError")}`);
}
} catch (err) {
console.error(getLogTag(owner), "Error opening cache backups folder:", err);
new obsidian.Notice(`${pluginName}: ${t(this.app, "backups.imagesFolder.openError")}`);
}
};
const onOpenButtonClick = () => {
openBackupFolder().catch((error: unknown) => {
console.error(getLogTag(owner), "Error opening cache backups folder:", error);
});
};
// modal-scoped: cleaned in onClose() — registerDomEvent unavailable on Modal
openButton.addEventListener("click", onOpenButtonClick);
this.listenerCleanups.push(() => openButton.removeEventListener("click", onOpenButtonClick));
owner.scheduleElementFocus(openButton);
}
override onClose() {
const { contentEl } = this;
for (const cleanup of this.listenerCleanups) {
cleanup();
}
this.listenerCleanups = [];
owner.untrackManagedModal(this);
contentEl.empty();
owner.restoreModalFocus(this.returnFocusTo);
}
}(this.plugin.app);
this.plugin.trackManagedModal(modal);
modal.open();
}
}

View file

@ -0,0 +1,32 @@
import type LocalImageCompressPlugin from "../plugin";
import { t } from "../i18n";
export class CommandRegistry {
constructor(private readonly plugin: LocalImageCompressPlugin) {}
registerAll() {
const commands = [
{
id: "compress-images-in-note",
name: t(this.plugin.app, "command.compressInNote"),
callback: () => this.plugin.compressImagesInNote()
},
{
id: "compress-images-in-folder",
name: t(this.plugin.app, "command.compressInFolder"),
callback: () => this.plugin.compressImagesInFolder()
},
{
id: "compress-all-images",
name: t(this.plugin.app, "command.compressAll"),
callback: () => this.plugin.compressAllImages()
},
{
id: "move-compressed-to-files",
name: t(this.plugin.app, "command.moveCompressed"),
callback: () => this.plugin.moveService.moveCompressedToFiles()
}
];
commands.forEach((cmd) => this.plugin.addCommand(cmd));
}
}

View file

@ -0,0 +1,44 @@
import type * as obsidian from "obsidian";
import { getLogTag } from "../utils";
import type LocalImageCompressPlugin from "../plugin";
type VaultWithOptionalConfigChange = obsidian.Vault & {
on(name: "config-changed", callback: () => void | Promise<void>): obsidian.EventRef;
};
export class EventRouter {
constructor(private readonly plugin: LocalImageCompressPlugin) {}
private registerConfigChange() {
try {
const vault = this.plugin.app.vault as VaultWithOptionalConfigChange;
const eventRef = vault.on("config-changed", () => this.plugin.handleLocaleConfigChanged());
if (eventRef) {
this.plugin.registerEvent(eventRef);
}
} catch (error) {
console.debug(getLogTag(this.plugin), "Vault config-change event is unavailable; locale will refresh on reload.", error);
}
}
registerAll() {
this.registerConfigChange();
this.plugin.registerEvent(
this.plugin.app.workspace.on("file-menu", (menu, file) => this.plugin.handleFileMenu(menu, file))
);
this.plugin.registerEvent(
this.plugin.app.vault.on("create", (file) => this.plugin.handleVaultCreate(file))
);
this.plugin.registerEvent(
this.plugin.app.vault.on("delete", (file) => this.plugin.handleVaultDelete(file))
);
this.plugin.registerEvent(
this.plugin.app.vault.on("rename", (file, oldPath) => this.plugin.handleVaultRename(file, oldPath))
);
this.plugin.registerEvent(
this.plugin.app.vault.on("modify", (file) => this.plugin.handleVaultModify(file))
);
this.plugin.backgroundCompressionService.setupUserActivityTracking();
this.plugin.backgroundCompressionService.startInactivityCheck();
}
}

View file

@ -0,0 +1,125 @@
import * as obsidian from "obsidian";
import type { default as LocalImageCompressPlugin } from "../plugin";
import type { TimerHandle } from "../types";
import { t } from "../i18n";
export class FolderSelectorModal extends obsidian.Modal {
private readonly plugin: LocalImageCompressPlugin;
private readonly folderPaths: string[];
private resolveSelection: ((value: string | null) => void) | null;
private settled = false;
private listenerCleanups: Array<() => void> = [];
private focusTimer: TimerHandle | null = null;
private readonly returnFocusTo: HTMLElement | null;
constructor(plugin: LocalImageCompressPlugin, folderPaths: string[], resolveSelection: (value: string | null) => void) {
super(plugin.app);
this.plugin = plugin;
this.folderPaths = folderPaths;
this.resolveSelection = resolveSelection;
this.returnFocusTo = plugin.captureModalFocusTarget();
this.titleEl.setText(t(this.plugin.app, "folderSelect.title"));
this.titleEl.id = "tiny-local-folder-select-title";
}
static show(plugin: LocalImageCompressPlugin, folderPaths: string[]): Promise<string | null> {
return new Promise<string | null>((resolveSelection) => {
const modal = new FolderSelectorModal(plugin, folderPaths, resolveSelection);
plugin.trackManagedModal(modal);
modal.open();
});
}
override onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("tiny-local-folder-select-modal");
contentEl.setAttribute("aria-labelledby", "tiny-local-folder-select-title");
const select = contentEl.createEl("select", { cls: "tiny-local-folder-select-control" });
select.setAttribute("aria-label", t(this.plugin.app, "folderSelect.selectLabel"));
for (const folderPath of this.folderPaths) {
const option = select.createEl("option", {
text: folderPath === "/" ? t(this.plugin.app, "folderSelect.root") : folderPath
});
option.value = folderPath;
}
select.value = this.folderPaths[0] ?? "";
const actionsEl = contentEl.createDiv({ cls: "modal-button-container" });
const okButton = actionsEl.createEl("button", {
text: t(this.plugin.app, "folderSelect.select"),
cls: "mod-cta"
});
okButton.id = "select-folder";
okButton.type = "button";
okButton.setAttribute("aria-label", t(this.plugin.app, "folderSelect.select"));
const cancelButton = actionsEl.createEl("button", {
text: t(this.plugin.app, "folderSelect.cancel")
});
cancelButton.id = "cancel-folder";
cancelButton.type = "button";
cancelButton.setAttribute("aria-label", t(this.plugin.app, "folderSelect.cancel"));
const onOkClick = () => this.settle(select.value);
const onCancelClick = () => this.settle(null);
const onContentKeydown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
this.settle(null);
} else if (event.key === "Enter") {
event.preventDefault();
this.settle(select.value);
}
};
okButton.addEventListener("click", onOkClick);
cancelButton.addEventListener("click", onCancelClick);
contentEl.addEventListener("keydown", onContentKeydown);
this.listenerCleanups.push(
() => okButton.removeEventListener("click", onOkClick),
() => cancelButton.removeEventListener("click", onCancelClick),
() => contentEl.removeEventListener("keydown", onContentKeydown)
);
this.focusTimer = this.plugin.setWindowTimeout(() => {
this.focusTimer = null;
select.focus();
}, 0);
}
override onClose() {
if (this.focusTimer) {
this.plugin.clearWindowTimeout(this.focusTimer);
this.focusTimer = null;
}
for (const listenerCleanup of this.listenerCleanups) {
listenerCleanup();
}
this.listenerCleanups = [];
this.plugin.untrackManagedModal(this);
this.contentEl.empty();
this.resolveIfPending(null);
this.plugin.restoreModalFocus(this.returnFocusTo);
}
private settle(value: string | null) {
if (this.settled) {
return;
}
this.settled = true;
this.resolveSelection?.(value);
this.resolveSelection = null;
this.close();
}
private resolveIfPending(value: string | null) {
if (this.settled) {
return;
}
this.settled = true;
this.resolveSelection?.(value);
this.resolveSelection = null;
}
}

View file

@ -0,0 +1,159 @@
import * as fs from "fs";
import * as path from "path";
import * as obsidian from "obsidian";
import type { default as LocalImageCompressPlugin } from "../plugin";
import { getVaultBasePath, getLogTag, getPluginName } from "../utils";
import { t } from "../i18n";
export class MigrationRunner {
constructor(private readonly plugin: LocalImageCompressPlugin) {}
async filesystemPathExists(filePath: string) {
return await fs.promises.access(filePath).then(() => true, () => false);
}
async copyMigrationItem(src: string, dest: string): Promise<void> {
const stat = await fs.promises.lstat(src);
if (stat.isSymbolicLink()) {
throw new Error(`Migration source must not be a symbolic link: ${src}`);
}
if (!stat.isDirectory()) {
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
await fs.promises.copyFile(src, dest, fs.constants.COPYFILE_EXCL);
return;
}
await fs.promises.mkdir(dest, { recursive: true });
for (const entry of await fs.promises.readdir(src, { withFileTypes: true })) {
await this.copyMigrationItem(path.join(src, entry.name), path.join(dest, entry.name));
}
}
async verifyMigrationItem(src: string, dest: string): Promise<void> {
const [sourceStat, destinationStat] = await Promise.all([
fs.promises.lstat(src),
fs.promises.lstat(dest)
]);
if (sourceStat.isSymbolicLink() || destinationStat.isSymbolicLink()) {
throw new Error(`Migration verification rejected a symbolic link: ${src}`);
}
if (sourceStat.isDirectory() !== destinationStat.isDirectory()) {
throw new Error(`Migration source and destination types differ: ${src}`);
}
if (!sourceStat.isDirectory()) {
if (sourceStat.size !== destinationStat.size || !await this.plugin.moveService.filesHaveSameContent(src, dest)) {
throw new Error(`Migration copy verification failed: ${src}`);
}
return;
}
for (const entry of await fs.promises.readdir(src, { withFileTypes: true })) {
await this.verifyMigrationItem(path.join(src, entry.name), path.join(dest, entry.name));
}
}
async moveOrCopyMigrationItem(src: string, dest: string): Promise<void> {
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
const sourceStat = await fs.promises.lstat(src);
if (sourceStat.isSymbolicLink()) {
throw new Error(`Migration source must not be a symbolic link: ${src}`);
}
try {
await fs.promises.rename(src, dest);
return;
} catch (renameError) {
console.debug(getLogTag(this.plugin), "Migration rename failed; falling back to copy", renameError);
}
await this.copyMigrationItem(src, dest);
await this.verifyMigrationItem(src, dest);
await fs.promises.rm(src, { recursive: true, force: true });
}
async mergeMigrationItem(src: string, dest: string): Promise<void> {
if (!await this.filesystemPathExists(src)) {
return;
}
if (!await this.filesystemPathExists(dest)) {
await this.moveOrCopyMigrationItem(src, dest);
return;
}
const [sourceStat, destinationStat] = await Promise.all([
fs.promises.lstat(src),
fs.promises.lstat(dest)
]);
if (sourceStat.isSymbolicLink() || destinationStat.isSymbolicLink()) {
throw new Error(`Migration merge rejected a symbolic link: ${src}`);
}
if (sourceStat.isDirectory() && destinationStat.isDirectory()) {
for (const entry of await fs.promises.readdir(src, { withFileTypes: true })) {
await this.mergeMigrationItem(path.join(src, entry.name), path.join(dest, entry.name));
}
await fs.promises.rmdir(src);
return;
}
if (!sourceStat.isDirectory() && !destinationStat.isDirectory()) {
const sameContent = sourceStat.size === destinationStat.size
&& await this.plugin.moveService.filesHaveSameContent(src, dest);
if (!sameContent) {
throw new Error(`Migration destination already contains a different file: ${dest}`);
}
await fs.promises.unlink(src);
return;
}
throw new Error(`Migration source and destination types differ: ${src}`);
}
async migrateLegacyPluginData() {
try {
const configDir = this.plugin.app.vault.configDir;
const basePath = getVaultBasePath(this.plugin.app);
const oldDir = path.join(basePath, configDir, "plugins", "tiny-local");
const newDir = path.join(basePath, configDir, "plugins", "local-image-compress");
const backupPaths = this.plugin.getBackupStoragePaths();
const migrationItems = [
{
item: "legacy cache file",
src: path.join(oldDir, "tinyLocal-cache.json"),
dest: path.join(newDir, "tinyLocal-cache.json")
},
{
item: "legacy cache backups",
src: path.join(oldDir, "cache-backups"),
dest: backupPaths.cacheBackups
},
{
item: "legacy original-file backups",
src: path.join(oldDir, "original-files-backups"),
dest: backupPaths.originalFilesBackups
},
{
item: "cache backups",
src: path.join(newDir, "cache-backups"),
dest: backupPaths.cacheBackups
},
{
item: "original-file backups",
src: path.join(newDir, "original-files-backups"),
dest: backupPaths.originalFilesBackups
}
];
const migrationErrors: Array<{ item: string; error: unknown }> = [];
for (const { item, src, dest } of migrationItems) {
try {
await this.mergeMigrationItem(src, dest);
} catch (e) {
migrationErrors.push({ item, error: e });
}
}
if (migrationErrors.length > 0) {
new obsidian.Notice(`${getPluginName(this.plugin)}: ${t(this.plugin.app, "migration.partialFailure")} (${migrationErrors.length})`, 10000);
for (const { item, error } of migrationErrors) {
console.error(getLogTag(this.plugin), "Migration item error", item, error);
}
}
if (await this.filesystemPathExists(oldDir)) {
await fs.promises.rmdir(oldDir).catch(() => undefined);
}
} catch (e) {
console.error(getLogTag(this.plugin), 'Startup migration error:', e);
}
}
}

View file

@ -0,0 +1,186 @@
import * as obsidian from "obsidian";
import type { default as LocalImageCompressPlugin } from "../plugin";
import type { TimerHandle } from "../types";
import { getLogTag, getPluginName, getVaultFileByPath, normalizeVaultPath } from "../utils";
import { t } from "../i18n";
// Owns the new-file auto-compress queue: BOTH the state (timers/pending/in-flight
// sets, batch flags, limits) and the logic (debounce -> pending -> batch drain).
// The plugin only holds a reference plus thin delegators for its event handlers.
export class NewFileQueue {
readonly newFileCompressionTimers: Map<string, TimerHandle> = new Map();
readonly newFileCompressionInFlight: Set<string> = new Set();
readonly newFileCompressionPending: Set<string> = new Set();
newFileBatchFlushTimer: TimerHandle | null = null;
newFileBatchDrainInProgress = false;
newFileBatchDrainRescheduleRequested = false;
newFileBatchFirstQueuedAt: number | null = null;
newFilePendingOverflowWarned = false;
newFilePendingOverflowNoticeAt = 0;
readonly NEW_FILE_BATCH_DEBOUNCE_MS = 500;
readonly NEW_FILE_BATCH_MAX_WAIT_MS = 5e3;
NEW_FILE_PENDING_MAX = 10_000;
readonly NEW_FILE_OVERFLOW_NOTICE_COOLDOWN_MS = 60_000;
readonly AUTO_COMPRESS_DELAY = 3e3;
constructor(private readonly plugin: LocalImageCompressPlugin) {}
// Clears every timer and resets all queue state. Called from plugin onunload.
cleanup() {
for (const timer of this.newFileCompressionTimers.values()) {
this.plugin.clearWindowTimeout(timer);
}
this.newFileCompressionTimers.clear();
if (this.newFileBatchFlushTimer) {
this.plugin.clearWindowTimeout(this.newFileBatchFlushTimer);
this.newFileBatchFlushTimer = null;
}
this.newFileCompressionPending.clear();
this.newFileCompressionInFlight.clear();
this.newFileBatchDrainInProgress = false;
this.newFileBatchDrainRescheduleRequested = false;
this.newFileBatchFirstQueuedAt = null;
this.newFilePendingOverflowWarned = false;
this.newFilePendingOverflowNoticeAt = 0;
}
// True if a debounce timer or a pending entry exists for this path (used by the
// modify handler to re-arm auto-compression).
hasPendingOrTimer(filePath: string | null | undefined): boolean {
if (!filePath) {
return false;
}
const normalizedPath = normalizeVaultPath(filePath);
return this.newFileCompressionTimers?.has(normalizedPath) || this.newFileCompressionPending?.has(normalizedPath);
}
async handleNewFile(file: obsidian.TAbstractFile) {
if (!this.plugin.settings.autoCompressNewFiles || !(file instanceof obsidian.TFile) || !this.plugin.isImageFile(file) || this.plugin.isOutputFolderPath(file.path)) {
return;
}
const filePath = normalizeVaultPath(file.path);
const existingTimer = this.newFileCompressionTimers?.get(filePath);
if (existingTimer) {
this.plugin.clearWindowTimeout(existingTimer);
}
const timer = this.plugin.setWindowTimeout(() => {
this.newFileCompressionTimers?.delete(filePath);
if (this.plugin.isUnloading) {
return;
}
const freshFile = getVaultFileByPath(this.plugin.app.vault, filePath);
if (!freshFile || !this.plugin.isImageFile(freshFile) || this.plugin.isOutputFolderPath(freshFile.path)) {
return;
}
if (this.newFileCompressionInFlight.has(filePath)) {
return;
}
if (!this.newFileCompressionPending.has(filePath) && this.newFileCompressionPending.size >= this.NEW_FILE_PENDING_MAX) {
const now = Date.now();
const noticeDue = !this.newFilePendingOverflowWarned || now - this.newFilePendingOverflowNoticeAt >= this.NEW_FILE_OVERFLOW_NOTICE_COOLDOWN_MS;
if (noticeDue) {
this.newFilePendingOverflowWarned = true;
this.newFilePendingOverflowNoticeAt = now;
console.warn(getLogTag(this.plugin), `Auto-compress queue full (${this.NEW_FILE_PENDING_MAX}); dropping new files`);
new obsidian.Notice(`${getPluginName(this.plugin)}: ${t(this.plugin.app, "auto.queueFull", { max: this.NEW_FILE_PENDING_MAX })}`, 10000);
}
return;
}
this.newFileCompressionPending.add(filePath);
this.scheduleNewFileBatchDrain();
}, this.AUTO_COMPRESS_DELAY);
this.newFileCompressionTimers?.set(filePath, timer);
}
cancelPendingNewFileCompression(filePath: string | null | undefined) {
if (!filePath) {
return;
}
const normalizedPath = normalizeVaultPath(filePath);
const timer = this.newFileCompressionTimers?.get(normalizedPath);
if (timer) {
this.plugin.clearWindowTimeout(timer);
this.newFileCompressionTimers.delete(normalizedPath);
}
this.newFileCompressionPending?.delete(normalizedPath);
if (this.newFileCompressionPending?.size === 0 && this.newFileBatchFlushTimer) {
this.plugin.clearWindowTimeout(this.newFileBatchFlushTimer);
this.newFileBatchFlushTimer = null;
this.newFilePendingOverflowWarned = false;
}
}
scheduleNewFileBatchDrain() {
if (this.newFileBatchFlushTimer) {
return;
}
if (this.newFileBatchDrainInProgress) {
this.newFileBatchDrainRescheduleRequested = true;
return;
}
if (this.newFileBatchFirstQueuedAt === null) {
this.newFileBatchFirstQueuedAt = Date.now();
}
const elapsedMs = Date.now() - this.newFileBatchFirstQueuedAt;
const remainingMs = Math.max(0, this.NEW_FILE_BATCH_MAX_WAIT_MS - elapsedMs);
const delayMs = Math.min(this.NEW_FILE_BATCH_DEBOUNCE_MS, remainingMs);
this.newFileBatchFlushTimer = this.plugin.setWindowTimeout(() => {
this.newFileBatchFlushTimer = null;
this.drainNewFileCompressionBatch().catch((error) => {
if (!this.plugin.isUnloading) {
console.error(getLogTag(this.plugin), "Delayed new-file batch compression error:", error);
}
});
}, delayMs);
}
async drainNewFileCompressionBatch() {
if (this.newFileBatchDrainInProgress) {
this.newFileBatchDrainRescheduleRequested = true;
return;
}
if (this.plugin.isUnloading || this.newFileCompressionPending.size === 0) {
this.newFileBatchFirstQueuedAt = null;
return;
}
this.newFileBatchDrainInProgress = true;
this.newFileBatchDrainRescheduleRequested = false;
let files: obsidian.TFile[] = [];
try {
const paths = Array.from(this.newFileCompressionPending);
this.newFileCompressionPending.clear();
files = paths
.map((filePath) => getVaultFileByPath(this.plugin.app.vault, filePath))
.filter((freshFile): freshFile is obsidian.TFile =>
freshFile !== null &&
this.plugin.isImageFile(freshFile) &&
!this.plugin.isOutputFolderPath(freshFile.path) &&
!this.newFileCompressionInFlight.has(freshFile.path)
);
if (files.length === 0) {
return;
}
for (const freshFile of files) {
this.newFileCompressionInFlight.add(freshFile.path);
}
await this.plugin.processBatchCompressionBackground(files);
} catch (error) {
if (!this.plugin.isUnloading) {
console.error(getLogTag(this.plugin), "Delayed new-file batch compression error:", error);
}
} finally {
for (const freshFile of files) {
this.newFileCompressionInFlight.delete(freshFile.path);
}
this.newFileBatchDrainInProgress = false;
const shouldDrainAgain = this.newFileBatchDrainRescheduleRequested || this.newFileCompressionPending.size > 0;
this.newFileBatchDrainRescheduleRequested = false;
if (!this.plugin.isUnloading && shouldDrainAgain && this.newFileCompressionPending.size > 0) {
this.scheduleNewFileBatchDrain();
} else if (this.newFileCompressionPending.size === 0) {
this.newFileBatchFirstQueuedAt = null;
this.newFilePendingOverflowWarned = false;
}
}
}
}

957
src-ts/settings-tab.ts Normal file
View file

@ -0,0 +1,957 @@
import * as obsidian from "obsidian";
import * as fs from "fs";
import { t } from "./i18n";
import { getActiveDocumentForApp, getActiveWindowForApp, getLogTag, getPluginName, isValidOutputFolder, normalizeOutputFolder, openFilesystemPath } from "./utils";
import type LocalImageCompressPlugin from "./plugin";
import type { SavingsSnapshot, StatsSnapshot, TimerHandle } from "./types";
class AllowedRootsFolderSuggestModal extends obsidian.FuzzySuggestModal<string> {
private readonly plugin: LocalImageCompressPlugin;
private readonly items: string[];
private readonly appRef: obsidian.App;
private readonly onChooseCb: (item: string) => void | Promise<void>;
private readonly returnFocusTo: HTMLElement | null;
constructor(plugin: LocalImageCompressPlugin, items: string[], onChoose: (item: string) => void | Promise<void>) {
super(plugin.app);
this.plugin = plugin;
this.appRef = plugin.app;
this.items = items;
this.onChooseCb = onChoose;
this.returnFocusTo = plugin.captureModalFocusTarget();
this.setPlaceholder(t(plugin.app, "paths.allowedRoots.modal.placeholder"));
}
getItems() { return this.items; }
getItemText(item: string) {
return item === "" || item === "/" ? t(this.appRef, "folderSelect.root") : item;
}
onChooseItem(item: string) {
Promise.resolve(this.onChooseCb(item)).catch((error: unknown) => {
console.error(getLogTag(this), "Allowed-root selection failed:", error);
});
}
override onClose() {
this.plugin.untrackManagedModal(this);
super.onClose();
this.plugin.restoreModalFocus(this.returnFocusTo);
}
}
export class SettingsTab extends obsidian.PluginSettingTab {
plugin: LocalImageCompressPlugin;
private _isVisible: boolean;
private _isRendering: boolean;
private _pendingRerender: boolean;
_renderRootsCleanups: Array<() => void>;
_savingsTooltipCleanups: Array<() => void>;
_savingsTooltipDocuments: Set<Document>;
currentStatsSnapshot: StatsSnapshot | null;
cacheStatsElement: HTMLElement | null;
ghostStatsElement: HTMLElement | null;
uncompressedStatsElement: HTMLElement | null;
compressedFilesCountElement: HTMLElement | null;
savingsHostElement: HTMLElement | null;
saveSettingsDebounceTimer: TimerHandle | null;
updateStats!: () => Promise<void>;
constructor(app: obsidian.App, plugin: LocalImageCompressPlugin) {
super(app, plugin);
this.plugin = plugin;
this._isVisible = false;
this._isRendering = false;
this._pendingRerender = false;
this._renderRootsCleanups = [];
this._savingsTooltipCleanups = [];
this._savingsTooltipDocuments = new Set();
this.currentStatsSnapshot = null;
this.cacheStatsElement = null;
this.ghostStatsElement = null;
this.uncompressedStatsElement = null;
this.compressedFilesCountElement = null;
this.savingsHostElement = null;
this.saveSettingsDebounceTimer = null;
}
requestRerenderAfterCurrentRender() {
if (!this._isRendering) {
return false;
}
this._pendingRerender = true;
return true;
}
private focusRestorableElement(active: Element | null) {
const focusable = active as unknown as { focus?: () => void } | null;
if (typeof focusable?.focus === "function") {
focusable.focus();
}
}
private displayWithoutScrollRestore(errorContext: string) {
if (this.requestRerenderAfterCurrentRender()) {
return;
}
this.renderSettings().catch((displayError) => {
console.error(getLogTag(this), errorContext, displayError);
});
}
rerenderPreservingScroll() {
try {
const { containerEl } = this;
if (!containerEl) {
this.displayWithoutScrollRestore("Settings render without container failed:");
return;
}
const prevScroll = containerEl.scrollTop || 0;
const active = this.getActiveDocument().activeElement;
const restore = () => {
try {
containerEl.scrollTop = prevScroll;
this.focusRestorableElement(active);
} catch (error) {
console.debug(getLogTag(this), "settings scroll restore failed (non-critical)", error);
}
};
this.requestWindowAnimationFrame(() => {
this.renderSettings()
.then(() => this.requestWindowAnimationFrame(restore))
.catch((error) => {
console.error(getLogTag(this), "Settings re-render failed:", error);
this.requestWindowAnimationFrame(restore);
});
});
} catch (error) {
console.error(getLogTag(this), "Settings re-render setup failed:", error);
this.displayWithoutScrollRestore("Settings fallback render failed:");
}
}
getActiveDocument() {
return getActiveDocumentForApp(this.app)
|| this.getActiveWindow().document
|| window.document;
}
getActiveWindow() {
return getActiveWindowForApp(this.app) || window;
}
setWindowTimeout(callback: (...args: never[]) => unknown, delay: number) {
return window.setTimeout(callback, delay);
}
clearWindowTimeout(timer: TimerHandle | null | undefined) {
if (timer === null || timer === undefined) {
return;
}
window.clearTimeout(timer as number);
}
flushPendingSaveSettings() {
if (!this.saveSettingsDebounceTimer) {
return;
}
try {
this.clearWindowTimeout(this.saveSettingsDebounceTimer);
} catch (error) {
console.debug(getLogTag(this), "Settings debounce timer cleanup failed (non-critical)", error);
}
this.saveSettingsDebounceTimer = null;
this.plugin.saveSettings().catch((error: unknown) => {
console.error(getLogTag(this), "Settings save during close failed:", error);
});
}
debouncedSaveSettings(delayMs = 300, afterSave: (() => void) | null = null) {
if (this.saveSettingsDebounceTimer) {
this.clearWindowTimeout(this.saveSettingsDebounceTimer);
}
this.saveSettingsDebounceTimer = this.setWindowTimeout(() => {
this.saveSettingsDebounceTimer = null;
this.plugin.saveSettings()
.then(() => afterSave?.())
.catch((error) => {
console.error(getLogTag(this), "Settings save failed:", error);
});
}, delayMs);
}
showSettingsOperationError(error: unknown, context: string, noticeKey = "notice.operationFailed") {
console.error(getLogTag(this), context, error);
new obsidian.Notice(`${getPluginName(this.plugin)}: ${t(this.plugin.app, noticeKey)}`);
}
async runButtonTask(button: obsidian.ButtonComponent, idleKey: string, loadingKey: string, task: () => Promise<void>, errorContext = "Settings button action failed:", noticeKey = "notice.operationFailed") {
button.setDisabled(true);
button.setButtonText(t(this.plugin.app, loadingKey));
try {
await task();
} catch (error) {
this.showSettingsOperationError(error, errorContext, noticeKey);
} finally {
button.setButtonText(t(this.plugin.app, idleKey));
button.setDisabled(false);
}
}
applySubsettingVisibility(visible: boolean, ...rows: obsidian.Setting[]) {
for (const row of rows) {
row.settingEl.toggle(visible);
row.settingEl.addClass("tiny-local-subsetting");
}
}
formatCountMessage(key: string, count: number) {
return t(this.plugin.app, key, { count });
}
getSavingsBarWidths(savings: SavingsSnapshot) {
const originalSize = Number.isFinite(savings.originalSize) && savings.originalSize > 0 ? savings.originalSize : 0;
const savedSize = Number.isFinite(savings.savedSize) && savings.savedSize > 0 ? savings.savedSize : 0;
const savedWidth = originalSize > 0 ? Math.min(100, Math.max(0, (savedSize / originalSize) * 100)) : 0;
return {
savedWidth,
currentWidth: Math.max(0, 100 - savedWidth)
};
}
cleanupRenderRoots() {
for (const cleanup of this._renderRootsCleanups || []) {
try {
cleanup();
} catch (error) {
console.debug(getLogTag(this), "Allowed roots cleanup failed (non-critical)", error);
}
}
this._renderRootsCleanups = [];
}
requestWindowAnimationFrame(callback: FrameRequestCallback | (() => void)) {
const ownerWindow = this.containerEl?.win || this.getActiveWindow();
if (ownerWindow.requestAnimationFrame) {
return ownerWindow.requestAnimationFrame(callback);
}
return this.setWindowTimeout(callback, 0);
}
normalizeAllowedRootSelection(chosen: string) {
if (chosen === "" || chosen === "/") {
return null;
}
return chosen.endsWith("/") ? chosen : `${chosen}/`;
}
renderSection(containerEl: HTMLElement, key: string) {
new obsidian.Setting(containerEl)
.setName(t(this.plugin.app, key))
.setHeading();
}
private setDestructiveButton(button: obsidian.ButtonComponent) {
const compatibleButton = button as unknown as {
setDestructive?: () => unknown;
setWarning?: () => unknown;
};
if (typeof compatibleButton.setDestructive === "function") {
compatibleButton.setDestructive();
} else {
compatibleButton.setWarning?.();
}
return button;
}
renderInstructions(containerEl: HTMLElement) {
this.renderSection(containerEl, "section.instructions");
const instructions = containerEl.createDiv({ cls: "setting-item-description" });
const usageTitle = instructions.createEl("p");
usageTitle.createEl("strong", { text: t(this.plugin.app, "instructions.usageTitle") });
const usageList = instructions.createEl("ul");
const addUsageItem = (prefix: string, command: string) => {
usageList.createEl("li", { text: `${prefix} "${command}"` });
};
addUsageItem(t(this.plugin.app, "instructions.action.rightClick"), t(this.plugin.app, "context.compressImage"));
addUsageItem(t(this.plugin.app, "instructions.action.commandPalette"), t(this.plugin.app, "command.compressInNote"));
addUsageItem(t(this.plugin.app, "instructions.action.commandPalette"), t(this.plugin.app, "command.compressInFolder"));
addUsageItem(t(this.plugin.app, "instructions.action.commandPalette"), t(this.plugin.app, "command.compressAll"));
addUsageItem(t(this.plugin.app, "instructions.action.commandPalette"), t(this.plugin.app, "command.moveCompressed"));
const notesTitle = instructions.createEl("p");
notesTitle.createEl("strong", { text: t(this.plugin.app, "instructions.notesTitle") });
const notesList = instructions.createEl("ul");
notesList.createEl("li", { text: `${t(this.plugin.app, "instructions.notes.saved")} "${this.plugin.getOutputFolder()}"` });
notesList.createEl("li", { text: t(this.plugin.app, "instructions.notes.originalUnchanged") });
notesList.createEl("li", { text: t(this.plugin.app, "instructions.notes.recompressionSkipped") });
}
finishRender() {
this._isRendering = false;
if (this._pendingRerender) {
this._pendingRerender = false;
this.requestWindowAnimationFrame(() => {
this.renderSettings().catch((error) => {
console.error(getLogTag(this), "Settings pending re-render failed:", error);
});
});
}
}
cleanupSavingsTooltips() {
for (const cleanup of this._savingsTooltipCleanups || []) {
try {
cleanup();
} catch (error) {
console.debug(getLogTag(this), "Savings tooltip cleanup failed:", error);
}
}
this._savingsTooltipCleanups = [];
try {
const documents = new Set([this.getActiveDocument(), ...(this._savingsTooltipDocuments || [])]);
for (const activeDocument of documents) {
const wrappers = Array.from(activeDocument?.querySelectorAll?.(".tiny-local-savings-tooltip-wrapper") || []);
for (const wrapper of wrappers) {
wrapper.parentElement?.removeChild(wrapper);
}
const contents = Array.from(activeDocument?.querySelectorAll?.(".tiny-local-savings-tooltip") || []);
for (const content of contents) {
const parent = content.parentElement;
if (parent?.classList?.contains?.("tiny-local-savings-tooltip-wrapper")) {
parent.parentElement?.removeChild(parent);
} else {
parent?.removeChild(content);
}
}
}
this._savingsTooltipDocuments?.clear?.();
} catch (error) {
console.debug(getLogTag(this), "Savings tooltip DOM cleanup failed:", error);
}
}
dispose() {
this._isVisible = false;
this.flushPendingSaveSettings();
this.cleanupRenderRoots();
this.cleanupSavingsTooltips();
}
override hide() {
this.dispose();
super.hide();
}
async applyStatsSnapshot(stats: StatsSnapshot) {
this.currentStatsSnapshot = stats;
if (this.cacheStatsElement) {
const cacheStats = stats.cacheStats;
this.cacheStatsElement.setText(`${cacheStats.total} ${t(this.plugin.app, "stats.cache.entries")}, ${t(this.plugin.app, "stats.cache.size")}: ${Math.round(cacheStats.size / 1024)} ${t(this.plugin.app, "units.kb")}`);
}
if (this.ghostStatsElement) {
this.ghostStatsElement.setText(`${stats.ghostCount} ${t(this.plugin.app, "stats.ghosts.pointToMissing")}`);
}
if (this.uncompressedStatsElement) {
this.uncompressedStatsElement.setText(`${stats.uncompressedImages} ${t(this.plugin.app, "stats.uncompressed.ready")}`);
}
if (this.compressedFilesCountElement) {
this.compressedFilesCountElement.setText(`${stats.compressedFilesCount} ${t(this.plugin.app, "move.ready")}`);
}
if (this.savingsHostElement) {
this.cleanupSavingsTooltips();
this.savingsHostElement.empty();
await this.renderSavingsIndicator(this.savingsHostElement, stats.savings);
}
}
// Obsidian invokes this legacy hook synchronously; async work is exposed separately.
override display(): void {
this._isVisible = true;
this.renderSettings().catch((error) => {
console.warn(getLogTag(this), "Settings render failed:", error);
});
}
async refreshStatsIfVisible() {
if (!this._isVisible) {
return;
}
if (this.requestRerenderAfterCurrentRender()) {
return;
}
if (typeof this.updateStats === "function") {
await this.updateStats();
return;
}
await this.renderSettings();
}
async renderSettings() {
if (this._isRendering) {
// If already rendering, mark that a subsequent pass is required
this._pendingRerender = true;
return;
}
this._isRendering = true;
try {
const { containerEl } = this;
this.cleanupRenderRoots();
this.cleanupSavingsTooltips();
containerEl.empty();
containerEl.addClass("tiny-local-settings");
// Keep references to elements for updates
this.cacheStatsElement = null;
this.ghostStatsElement = null;
this.uncompressedStatsElement = null;
this.compressedFilesCountElement = null;
this.savingsHostElement = null;
const statsSnapshot = await this.plugin.getStatsSnapshot();
this.currentStatsSnapshot = statsSnapshot;
// Function to update statistics
this.updateStats = async () => {
const stats = await this.plugin.getStatsSnapshot();
await this.applyStatsSnapshot(stats);
};
// Global warning if WASM modules are not available
const wasmInitError = this.plugin.compressor.getWasmInitError?.();
if (wasmInitError) {
containerEl.createDiv({ text: t(this.plugin.app, "warning.wasmInitFailed"), cls: "tiny-local-notice tiny-local-warning-block" });
}
// Add space savings indicator
this.savingsHostElement = containerEl.createDiv({ cls: "tiny-local-savings-host" });
await this.renderSavingsIndicator(this.savingsHostElement, statsSnapshot.savings);
// ========================================================================
// COMPRESSION QUALITY
// ========================================================================
this.renderSection(containerEl, "section.quality");
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "quality.png.name")).setDesc(t(this.plugin.app, "quality.png.desc")).addText((text) => text.setPlaceholder("65-80").setValue(`${this.plugin.settings.pngQuality.min}-${this.plugin.settings.pngQuality.max}`).onChange((value) => {
const parts = value.split("-");
if (parts.length === 2) {
const minPart = parts[0];
const maxPart = parts[1];
if (minPart === undefined || maxPart === undefined) {
return;
}
const min = parseInt(minPart, 10);
const max = parseInt(maxPart, 10);
if (!isNaN(min) && !isNaN(max) && min >= 1 && max <= 100 && min <= max) {
this.plugin.settings.pngQuality.min = min;
this.plugin.settings.pngQuality.max = max;
this.debouncedSaveSettings();
}
}
}));
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "quality.jpeg.name")).setDesc(t(this.plugin.app, "quality.jpeg.desc")).addSlider((slider) => slider.setLimits(1, 95, 1).setValue(this.plugin.settings.jpegQuality).setDynamicTooltip().onChange((value) => {
this.plugin.settings.jpegQuality = value;
this.debouncedSaveSettings();
}));
// Button: open image backups folder
// Removed from "Cache backups" section — moved to "Move compressed files"
// ========================================================================
// PATH SETTINGS
// ========================================================================
this.renderSection(containerEl, "section.paths");
// Allowed roots: choose from folder list with autocomplete (modal)
const rootsSetting = new obsidian.Setting(containerEl)
.setName(t(this.plugin.app, "paths.allowedRoots.name"))
.setDesc(t(this.plugin.app, "paths.allowedRoots.desc"));
const rootsListEl = rootsSetting.controlEl.createDiv({ cls: "tiny-local-roots-list" });
const renderRoots = () => {
this.cleanupRenderRoots();
rootsListEl.empty();
if (!Array.isArray(this.plugin.settings.allowedRoots) || this.plugin.settings.allowedRoots.length === 0) {
rootsListEl.createDiv({ text: t(this.plugin.app, "paths.allowedRoots.empty"), cls: "setting-item-description" });
return;
}
const list = rootsListEl.createDiv();
this.plugin.settings.allowedRoots.forEach((root: string, idx: number) => {
const removeLabel = t(this.plugin.app, "paths.allowedRoots.pill.remove");
const pill = list.createEl("button", { text: root, cls: "badge tiny-local-roots-pill" });
pill.type = "button";
pill.title = removeLabel;
pill.setAttribute("aria-label", `${removeLabel}: ${root}`);
const removeRoot = () => {
this.plugin.settings.allowedRoots.splice(idx, 1);
this.plugin.saveSettings()
.then(() => renderRoots())
.catch((error: unknown) => {
console.error(getLogTag(this), "Allowed root removal failed:", error);
});
};
// transient: re-rendered per render, removed via _renderRootsCleanups (registerDomEvent would leak across renders)
pill.addEventListener("click", removeRoot);
this._renderRootsCleanups.push(() => pill.removeEventListener("click", removeRoot));
});
};
rootsSetting.addButton((btn) =>
btn.setButtonText(t(this.plugin.app, "common.add")).onClick(async () => {
const folders = this.app.vault.getAllLoadedFiles()
.filter((f) => f instanceof obsidian.TFolder)
.map((f) => f.path);
const modal = this.plugin.trackManagedModal(new AllowedRootsFolderSuggestModal(this.plugin, folders, async (chosen) => {
const normalized = this.normalizeAllowedRootSelection(chosen);
if (normalized === null) {
new obsidian.Notice(`${getPluginName(this.plugin)}: ${t(this.plugin.app, "paths.allowedRoots.cannotAddRoot")}`);
return;
}
if (!this.plugin.settings.allowedRoots.includes(normalized)) {
this.plugin.settings.allowedRoots.push(normalized);
await this.plugin.saveSettings();
renderRoots();
}
}));
modal.open();
})
).addExtraButton((btn) =>
btn.setIcon("trash").setTooltip(t(this.plugin.app, "paths.allowedRoots.clear")).onClick(async () => {
this.plugin.settings.allowedRoots = [];
await this.plugin.saveSettings();
renderRoots();
})
);
// Mark the trash icon with a class for styling (red hover)
try {
const icons = rootsSetting.controlEl.querySelectorAll('.clickable-icon');
const lastIcon = icons[icons.length - 1];
if (lastIcon) lastIcon.classList.add('tiny-local-roots-clear');
} catch (error) {
console.debug(getLogTag(this), "allowed roots clear icon styling failed (non-critical)", error);
}
renderRoots();
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "paths.output.name")).setDesc(t(this.plugin.app, "paths.output.desc")).addText((text) => text.setPlaceholder("Compressed").setValue(this.plugin.getOutputFolder()).onChange((value) => {
const rawValue = value.trim();
if (rawValue && !isValidOutputFolder(rawValue)) {
text.setValue(this.plugin.getOutputFolder());
new obsidian.Notice(`${getPluginName(this.plugin)}: ${t(this.plugin.app, "validation.pathNotAllowed")}`);
return;
}
this.plugin.settings.outputFolder = normalizeOutputFolder(rawValue || "Compressed");
this.debouncedSaveSettings();
}));
// ========================================================================
// AUTOMATION
// ========================================================================
this.renderSection(containerEl, "section.automation");
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.newFiles.name")).setDesc(t(this.plugin.app, "auto.newFiles.desc")).addToggle((toggle) => toggle.setValue(this.plugin.settings.autoCompressNewFiles).onChange(async (value) => {
this.plugin.settings.autoCompressNewFiles = value;
await this.plugin.saveSettings();
}));
// Background compression + conditional threshold slider (without full re-render)
const bgSetting = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.bg.name")).setDesc(t(this.plugin.app, "auto.bg.desc"));
bgSetting.addToggle((toggle) => toggle.setValue(this.plugin.settings.autoBackgroundCompression).onChange(async (value) => {
this.plugin.settings.autoBackgroundCompression = value;
await this.plugin.saveSettings();
this.applySubsettingVisibility(value, thresholdRow, inactivityRow);
}));
const thresholdRow = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.bg.threshold.name")).setDesc(t(this.plugin.app, "auto.bg.threshold.desc"));
thresholdRow.addSlider((slider) => slider
.setLimits(10, 1000, 5)
.setValue(this.plugin.settings.autoBackgroundThreshold)
.setDynamicTooltip()
.onChange((value) => {
this.plugin.settings.autoBackgroundThreshold = value;
this.plugin.backgroundCompressionService.AUTO_BACKGROUND_THRESHOLD = value;
this.debouncedSaveSettings();
})
);
this.applySubsettingVisibility(this.plugin.settings.autoBackgroundCompression, thresholdRow);
const inactivityRow = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.bg.inactivity.name")).setDesc(t(this.plugin.app, "auto.bg.inactivity.desc"));
inactivityRow.addSlider((slider) => slider
.setLimits(1, 60, 1)
.setValue(this.plugin.settings.inactivityThresholdMinutes)
.setDynamicTooltip()
.onChange((value) => {
this.plugin.settings.inactivityThresholdMinutes = value;
this.plugin.backgroundCompressionService.USER_INACTIVITY_THRESHOLD = value * 60 * 1000;
this.debouncedSaveSettings();
})
);
this.applySubsettingVisibility(this.plugin.settings.autoBackgroundCompression, inactivityRow);
// Backups retention: toggle + slider
const retentionToggle = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.retention.toggle.name")).setDesc(t(this.plugin.app, "auto.retention.toggle.desc"));
retentionToggle.addToggle((toggle) => toggle.setValue(this.plugin.settings.autoBackupsRetentionEnabled).onChange(async (value) => {
this.plugin.settings.autoBackupsRetentionEnabled = value;
await this.plugin.saveSettings();
this.applySubsettingVisibility(value, retentionRow);
}));
const retentionRow = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.retention.days.name")).setDesc(t(this.plugin.app, "auto.retention.days.desc"));
retentionRow.addSlider((slider) => slider
.setLimits(1, 365, 1)
.setValue(this.plugin.settings.autoBackupsRetentionDays)
.setDynamicTooltip()
.onChange((value) => {
this.plugin.settings.autoBackupsRetentionDays = value;
this.debouncedSaveSettings();
})
);
this.applySubsettingVisibility(this.plugin.settings.autoBackupsRetentionEnabled, retentionRow);
// Auto-move compressed files: toggle + count slider
const autoMoveToggle = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.move.toggle.name")).setDesc(t(this.plugin.app, "auto.move.toggle.desc"));
autoMoveToggle.addToggle((toggle) => toggle.setValue(this.plugin.settings.autoMoveCompressedEnabled).onChange(async (value) => {
this.plugin.settings.autoMoveCompressedEnabled = value;
await this.plugin.saveSettings();
this.applySubsettingVisibility(value, autoMoveRow);
}));
const autoMoveRow = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.move.threshold.name")).setDesc(t(this.plugin.app, "auto.move.threshold.desc"));
autoMoveRow.addSlider((slider) => slider
.setLimits(1, 1000, 1)
.setValue(this.plugin.settings.autoMoveCompressedThreshold)
.setDynamicTooltip()
.onChange((value) => {
this.plugin.settings.autoMoveCompressedThreshold = value;
this.debouncedSaveSettings();
})
);
this.applySubsettingVisibility(this.plugin.settings.autoMoveCompressedEnabled, autoMoveRow);
// Add at the end of Automation section
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "auto.cleanupGhosts.name")).setDesc(t(this.plugin.app, "auto.cleanupGhosts.desc")).addToggle((toggle) => toggle.setValue(this.plugin.settings.autoCleanupGhostsOnStart).onChange(async (value) => {
this.plugin.settings.autoCleanupGhostsOnStart = value;
await this.plugin.saveSettings();
}));
// ========================================================================
// STATISTICS & CACHE
// ========================================================================
this.renderSection(containerEl, "section.stats");
const uncompressedSetting = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "stats.uncompressed.name")).setDesc(`${statsSnapshot.uncompressedImages} ${t(this.plugin.app, "stats.uncompressed.ready")}`);
this.uncompressedStatsElement = uncompressedSetting.descEl;
uncompressedSetting.addButton((button) => button.setButtonText(t(this.plugin.app, "common.refresh")).onClick(async () => {
await this.runButtonTask(button, "common.refresh", "common.refreshing", async () => {
await this.plugin.forceRefreshCache();
await this.updateStats();
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "notice.cacheUpdated")}`);
});
}));
const cacheStats = statsSnapshot.cacheStats;
const cacheSetting = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "stats.cache.name")).setDesc(`${cacheStats.total} ${t(this.plugin.app, "stats.cache.entries")}, ${t(this.plugin.app, "stats.cache.size")}: ${Math.round(cacheStats.size / 1024)} ${t(this.plugin.app, "units.kb")}`);
this.cacheStatsElement = cacheSetting.descEl;
cacheSetting.addButton((button) => this.setDestructiveButton(button).setButtonText(t(this.plugin.app, "common.clearCache")).onClick(async () => {
await this.runButtonTask(button, "common.clearCache", "common.clearing", async () => {
await this.plugin.cache.clearCache();
await this.plugin.rebuildImageIndex("cache-clear");
await this.plugin.statusBarController.update();
await this.updateStats();
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "notice.cacheCleared")}`);
});
})).addButton((button) => button.setButtonText(t(this.plugin.app, "common.refreshCache")).onClick(async () => {
await this.runButtonTask(button, "common.refreshCache", "common.refreshing", async () => {
await this.plugin.forceRefreshCache();
await this.updateStats();
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "notice.cacheUpdated")}`);
});
}));
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "stats.cache.retention.name")).setDesc(t(this.plugin.app, "stats.cache.retention.desc")).addSlider((slider) => slider
.setLimits(1, 60, 1)
.setValue(this.plugin.settings.cacheRetentionMonths)
.setDynamicTooltip()
.onChange((value) => {
this.plugin.settings.cacheRetentionMonths = value;
this.debouncedSaveSettings();
})
);
const ghostSetting = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "stats.ghosts.name")).setDesc(`${statsSnapshot.ghostCount} ${t(this.plugin.app, "stats.ghosts.pointToMissing")}`);
this.ghostStatsElement = ghostSetting.descEl;
ghostSetting.addButton((button) => this.setDestructiveButton(button).setButtonText(t(this.plugin.app, "common.clearGhosts")).onClick(async () => {
await this.runButtonTask(button, "common.clearGhosts", "common.clearing", async () => {
const removedCount = await this.plugin.cleanupGhostEntries();
await this.updateStats();
new obsidian.Notice(`${getPluginName(this)}: ${this.formatCountMessage("stats.ghosts.clearedCount", removedCount)}`);
});
}));
// ========================================================================
// AUTO MOVE
// ========================================================================
this.renderSection(containerEl, "section.move");
// Button: move compressed files
const moveSetting = new obsidian.Setting(containerEl).setName(t(this.plugin.app, "move.title")).setDesc(`${statsSnapshot.compressedFilesCount} ${t(this.plugin.app, "move.ready")}`);
this.compressedFilesCountElement = moveSetting.descEl;
moveSetting.addButton((button) => this.setDestructiveButton(button).setButtonText(t(this.plugin.app, "move.button")).onClick(async () => {
await this.runButtonTask(button, "move.button", "common.processing", async () => {
await this.plugin.moveService.moveCompressedToFiles();
// Update all stats after operation
await this.updateStats();
}, "Move compressed files action failed:");
}));
// Button: clear backups of moved files
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "backups.imagesFolder.clearName")).setDesc(t(this.plugin.app, "backups.imagesFolder.clearDesc")).addButton((button) => this.setDestructiveButton(button).setButtonText(t(this.plugin.app, "backups.imagesFolder.clearButton")).onClick(async () => {
await this.runButtonTask(button, "backups.imagesFolder.clearButton", "common.clearing", async () => {
await this.plugin.clearOriginalFilesBackups();
}, "Clear image backups action failed:", "backups.imagesFolder.clearError");
}));
// Button: open image backups folder
new obsidian.Setting(containerEl)
.setName(t(this.plugin.app, "backups.imagesFolder.name"))
.setDesc(t(this.plugin.app, "backups.imagesFolder.desc"))
.addButton((button) => button
.setButtonText(t(this.plugin.app, "backups.imagesFolder.openButton"))
.onClick(async () => {
try {
const dir = this.plugin.getBackupStoragePaths().originalFilesBackups;
await fs.promises.mkdir(dir, { recursive: true });
const err = await openFilesystemPath(dir);
if (err) {
console.error(getLogTag(this), 'Error opening image backups folder:', err);
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "backups.imagesFolder.openError")}`);
}
} catch (e) {
console.error(getLogTag(this), 'Error opening image backups folder:', e);
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "backups.imagesFolder.openError")}`);
}
})
);
// ========================================================================
// BACKUPS
// ========================================================================
this.renderSection(containerEl, "backups.cache.title");
const backups = await this.plugin.cache.getAvailableBackups();
if (backups.length === 0) {
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "backups.cache.restore")).setDesc(t(this.plugin.app, "backups.cache.none")).setDisabled(true);
} else {
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "backups.cache.restore")).setDesc(`${t(this.plugin.app, "backups.cache.available")} ${backups.length}`).addDropdown((dropdown) => {
dropdown.addOption("", t(this.plugin.app, "backups.cache.selectPlaceholder"));
backups.forEach((backup) => {
const date = backup.replace("tinyLocal-cache-backup-", "").replace(".json", "").replace(/-/g, ":").replace(/T/, " ");
dropdown.addOption(backup, date);
});
dropdown.onChange(async (value) => {
if (value) {
try {
const success = await this.plugin.cache.restoreFromBackup(value);
if (success) {
await this.plugin.rebuildImageIndex("cache-restore");
await this.plugin.statusBarController.update();
await this.updateStats();
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "notice.cacheUpdated")}`);
} else {
new obsidian.Notice(`${getPluginName(this)}: ${t(this.plugin.app, "notice.cacheCleared")}`);
}
} catch (error) {
this.showSettingsOperationError(error, "Cache restore action failed:");
}
}
});
});
}
new obsidian.Setting(containerEl).setName(t(this.plugin.app, "backups.cache.folder.name")).setDesc(t(this.plugin.app, "backups.cache.folder.desc")).addButton((button) => button.setButtonText(t(this.plugin.app, "backups.cache.folder.openButton")).onClick(async () => {
await this.plugin.showCacheBackupsList();
}));
// (Moved to "Move compressed files" section)
// ========================================================================
// INSTRUCTIONS
// ========================================================================
this.renderInstructions(containerEl);
} finally {
this.finishRender();
}
}
async renderSavingsIndicator(containerEl: HTMLElement, savings: SavingsSnapshot | null = null) {
try {
savings = savings || await this.plugin.savingsCalculator.calculateSpaceSavings();
if (!this.plugin.savingsCalculator.validateSavingsData(savings)) {
return; // Do not render if data is not valid
}
// Create container for indicator
const indicatorContainer = containerEl.createDiv({
cls: "tiny-local-savings-indicator"
});
// Create textual summary
const textInfo = indicatorContainer.createDiv({
cls: "tiny-local-savings-text"
});
const { originalFormatted, currentFormatted, savedFormatted, estimatedIndicator } = this.plugin.savingsCalculator.formatTooltipData(savings);
textInfo.createEl("strong", { text: `${t(this.plugin.app, "savings.original")}:` });
textInfo.createSpan({ text: ` ${originalFormatted}${estimatedIndicator} \u2192 ` });
textInfo.createEl("strong", { text: `${t(this.plugin.app, "savings.current")}:` });
textInfo.createSpan({ text: ` ${currentFormatted} \u2192 ` });
textInfo.createEl("strong", { text: `${t(this.plugin.app, "savings.saved")}:` });
textInfo.createSpan({ text: ` ${savedFormatted} (${savings.savedPercentage}%)${estimatedIndicator}` });
// Create progress bar
const barContainer = indicatorContainer.createDiv({
cls: "tiny-local-savings-bar"
});
barContainer.setAttribute("aria-hidden", "true");
// Compute bar proportions with divide-by-zero/NaN protection
const { savedWidth, currentWidth } = this.getSavingsBarWidths(savings);
// Create saved space segment
if (savedWidth > 0) {
const savedBlock = barContainer.createDiv({
cls: "tiny-local-savings-saved"
});
// dynamic: required at runtime
savedBlock.setCssProps({
"--local-image-compress-savings-width": `${savedWidth}%`
});
}
// Create current size segment (always create, even if 0%)
const currentBlock = barContainer.createDiv({
cls: "tiny-local-savings-current"
});
// dynamic: required at runtime
currentBlock.setCssProps({
"--local-image-compress-savings-width": `${currentWidth}%`
});
// Fallback: if both are 0, render empty block for visibility
if (savedWidth === 0 && currentWidth === 0) {
barContainer.createDiv({
cls: "tiny-local-savings-current tiny-local-savings-fallback"
});
}
// Attach tooltip
this.createSavingsTooltip(indicatorContainer, savings);
} catch (error) {
console.error(getLogTag(this), "Savings indicator render error:", error);
}
}
createSavingsTooltip(container: HTMLElement, savings: SavingsSnapshot) {
try {
const { originalFormatted, currentFormatted, savedFormatted, estimatedIndicator, estimatedText } = this.plugin.savingsCalculator.formatTooltipData(savings);
const accessibleSummary = [
`${t(this.plugin.app, "tooltip.savings.original")} ${originalFormatted}${estimatedIndicator}`,
`${t(this.plugin.app, "tooltip.savings.current")} ${currentFormatted}`,
`${t(this.plugin.app, "tooltip.savings.saved")} ${savedFormatted} (${savings.savedPercentage}%)${estimatedIndicator}`,
`${t(this.plugin.app, "tooltip.savings.filesProcessed")} ${savings.processedFiles} / ${savings.totalFiles}${estimatedText}`
].join(". ");
// Create custom tooltip
let tooltip: HTMLElement | null = null;
let isTooltipActive = false;
let showTimer: TimerHandle | null = null;
let hideTimer: TimerHandle | null = null;
const ownerWindow = container.win || this.getActiveWindow();
const activeDocument = container.doc || ownerWindow.document || this.getActiveDocument();
const tooltipRoot = activeDocument?.body;
if (!tooltipRoot) {
return;
}
this._savingsTooltipDocuments?.add?.(activeDocument);
const clearTooltipTimeout = ownerWindow.clearTimeout.bind(ownerWindow);
const setTooltipTimeout = ownerWindow.setTimeout.bind(ownerWindow);
const clearTooltipTimer = (timer: TimerHandle | null) => {
if (timer) {
clearTooltipTimeout(timer as number);
}
};
const clearShowTimer = () => {
clearTooltipTimer(showTimer);
showTimer = null;
};
const clearHideTimer = () => {
clearTooltipTimer(hideTimer);
hideTimer = null;
};
const addTooltipItem = (parent: HTMLElement, label: string, value: string) => {
const item = parent.createDiv({ cls: "tooltip-item" });
item.createSpan({ text: label, cls: "tooltip-label" });
item.createSpan({ text: value, cls: "tooltip-value" });
};
const showTooltip = () => {
if (tooltip || !isTooltipActive) return;
tooltip = tooltipRoot.createDiv();
tooltip.classList.add("tiny-local-savings-tooltip-wrapper");
const tooltipContent = tooltip.createDiv({ cls: "tiny-local-savings-tooltip" });
tooltipContent.id = "tiny-local-savings-tooltip";
tooltipContent.setAttribute("role", "tooltip");
container.setAttribute("aria-describedby", tooltipContent.id);
tooltipContent.createDiv({ text: t(this.plugin.app, "tooltip.savings.header"), cls: "tooltip-header" });
addTooltipItem(tooltipContent, t(this.plugin.app, "tooltip.savings.original"), `${originalFormatted}${estimatedIndicator}`);
addTooltipItem(tooltipContent, t(this.plugin.app, "tooltip.savings.current"), currentFormatted);
addTooltipItem(tooltipContent, t(this.plugin.app, "tooltip.savings.saved"), `${savedFormatted} (${savings.savedPercentage}%)${estimatedIndicator}`);
addTooltipItem(tooltipContent, t(this.plugin.app, "tooltip.savings.filesProcessed"), `${savings.processedFiles} / ${savings.totalFiles}${estimatedText}`);
tooltipRoot.appendChild(tooltip);
// Position tooltip after a frame to ensure proper sizes
this.requestWindowAnimationFrame(() => {
if (!tooltip || !tooltipRoot.contains(tooltip)) return;
const rect = container.getBoundingClientRect();
const tooltipRect = tooltip.getBoundingClientRect();
let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
let top = rect.top - tooltipRect.height - 10;
// Ensure on-screen positioning
const margin = 10;
const maxLeft = ownerWindow.innerWidth - tooltipRect.width - margin;
const maxTop = ownerWindow.innerHeight - tooltipRect.height - margin;
left = Math.max(margin, Math.min(left, maxLeft));
if (top < margin) {
top = rect.bottom + margin;
}
top = Math.max(margin, Math.min(top, maxTop));
// dynamic position via CSS custom properties (static styles live in CSS)
tooltip.setCssProps({
"--local-image-compress-savings-tooltip-left": `${left}px`,
"--local-image-compress-savings-tooltip-top": `${top}px`
});
});
};
const hideTooltip = () => {
if (tooltip && tooltipRoot.contains(tooltip)) {
tooltipRoot.removeChild(tooltip);
}
tooltip = null;
container.removeAttribute("aria-describedby");
};
const activateTooltip = (delay: number) => {
isTooltipActive = true;
clearShowTimer();
clearHideTimer();
showTimer = setTooltipTimeout(showTooltip, delay);
};
const deactivateTooltip = () => {
isTooltipActive = false;
clearShowTimer();
clearHideTimer();
hideTimer = setTooltipTimeout(hideTooltip, 100);
};
container.addClass("tiny-local-savings-tooltip-target");
container.setAttribute("role", "group");
container.setAttribute("tabindex", "0");
container.setAttribute("aria-label", accessibleSummary);
const onMouseEnter = () => activateTooltip(200);
const onMouseLeave = () => deactivateTooltip();
const onFocus = () => activateTooltip(0);
const onBlur = () => deactivateTooltip();
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
isTooltipActive = false;
clearShowTimer();
clearHideTimer();
hideTooltip();
}
};
this.plugin.registerDomEvent(container, 'mouseenter', onMouseEnter);
this.plugin.registerDomEvent(container, 'mouseleave', onMouseLeave);
this.plugin.registerDomEvent(container, 'focus', onFocus);
this.plugin.registerDomEvent(container, 'blur', onBlur);
this.plugin.registerDomEvent(container, 'keydown', onKeyDown);
this._savingsTooltipCleanups.push(() => {
container.removeEventListener('mouseenter', onMouseEnter);
container.removeEventListener('mouseleave', onMouseLeave);
container.removeEventListener('focus', onFocus);
container.removeEventListener('blur', onBlur);
container.removeEventListener('keydown', onKeyDown);
clearShowTimer();
clearHideTimer();
isTooltipActive = false;
hideTooltip();
});
} catch (error) {
console.error(getLogTag(this), "Tooltip creation error:", error);
}
}
}

128
src-ts/settings.ts Normal file
View file

@ -0,0 +1,128 @@
import { normalizeOutputFolder, normalizeVaultPathRoot } from "./utils";
export interface PngQualitySettings {
min: number;
max: number;
}
export interface LocalImageCompressSettings {
pngQuality: PngQualitySettings;
jpegQuality: number;
allowedRoots: string[];
outputFolder: string;
autoCompressNewFiles: boolean;
autoBackgroundCompression: boolean;
autoBackgroundThreshold: number;
inactivityThresholdMinutes: number;
cacheRetentionMonths: number;
autoCleanupGhostsOnStart: boolean;
autoBackupsRetentionEnabled: boolean;
autoBackupsRetentionDays: number;
autoMoveCompressedEnabled: boolean;
autoMoveCompressedThreshold: number;
}
export const DEFAULT_SETTINGS: LocalImageCompressSettings = {
pngQuality: {
min: 65,
max: 80
},
jpegQuality: 85,
allowedRoots: [],
outputFolder: "Compressed",
autoCompressNewFiles: false,
autoBackgroundCompression: true,
autoBackgroundThreshold: 50,
inactivityThresholdMinutes: 2,
cacheRetentionMonths: 12,
autoCleanupGhostsOnStart: false,
autoBackupsRetentionEnabled: false,
autoBackupsRetentionDays: 30,
autoMoveCompressedEnabled: false,
autoMoveCompressedThreshold: 50
};
const REMOVED_PASTE_RENAME_GUARD_SETTING = "disablePasteImageRename" + "DuringCompression";
const REMOVED_TECHNICAL_SETTING_KEYS = [
"pngquantPath",
"mozjpegPath",
"pluginGuard" + "TimeoutMs",
"worker" + "PoolSize",
"compression" + "TimeoutSeconds",
"wasmInit" + "TimeoutSeconds",
"maxInput" + "SizeMB",
"maxImagePixels" + "Millions",
REMOVED_PASTE_RENAME_GUARD_SETTING
];
export const INTERNAL_PLUGIN_GUARD_TIMEOUT_MS = 8_000;
export const INTERNAL_COMPRESSION_TIMEOUT_SECONDS = 120;
export const INTERNAL_WASM_INIT_TIMEOUT_SECONDS = 60;
export const INTERNAL_MAX_INPUT_SIZE_MB = 100;
export const INTERNAL_MAX_IMAGE_PIXELS_MILLIONS = 100;
const INTERNAL_DEFAULT_WORKER_POOL_SIZE = 2;
export const INTERNAL_MAX_WORKER_POOL_SIZE = 4;
export function getInternalWorkerPoolSize(hardwareConcurrency?: unknown) {
const numeric = typeof hardwareConcurrency === "number" ? hardwareConcurrency : Number(hardwareConcurrency);
const halfCores = Number.isFinite(numeric) && numeric > 0
? Math.floor(numeric / 2)
: INTERNAL_DEFAULT_WORKER_POOL_SIZE;
return Math.max(1, Math.min(INTERNAL_MAX_WORKER_POOL_SIZE, halfCores || 1));
}
function clampInteger(value: unknown, fallback: number, min: number, max: number) {
const numeric = typeof value === "number" ? value : Number(value);
const integer = Number.isFinite(numeric) ? Math.trunc(numeric) : fallback;
return Math.max(min, Math.min(max, integer));
}
function normalizeBoolean(value: unknown, fallback: boolean) {
return typeof value === "boolean" ? value : fallback;
}
function normalizeAllowedRoots(value: unknown) {
if (!Array.isArray(value)) {
return [...DEFAULT_SETTINGS.allowedRoots];
}
return value
.filter((root): root is string => typeof root === "string")
.map((root) => normalizeVaultPathRoot(root))
.filter((root) => root.length > 0);
}
function normalizePngQuality(value: unknown): PngQualitySettings {
const source = value && typeof value === "object" ? value as Partial<PngQualitySettings> : {};
const min = clampInteger(source.min, DEFAULT_SETTINGS.pngQuality.min, 1, 100);
const max = Math.max(min, clampInteger(source.max, DEFAULT_SETTINGS.pngQuality.max, 1, 100));
return { min, max };
}
export function normalizeSettings(loadedData: unknown): LocalImageCompressSettings {
const rawSource = loadedData && typeof loadedData === "object" ? loadedData as Partial<LocalImageCompressSettings> & Record<string, unknown> : {};
const source = { ...rawSource };
for (const key of REMOVED_TECHNICAL_SETTING_KEYS) {
delete source[key];
}
return {
...DEFAULT_SETTINGS,
...source,
pngQuality: normalizePngQuality(source.pngQuality),
jpegQuality: clampInteger(source.jpegQuality, DEFAULT_SETTINGS.jpegQuality, 1, 95),
allowedRoots: normalizeAllowedRoots(source.allowedRoots),
outputFolder: normalizeOutputFolder(
typeof source.outputFolder === "string" ? source.outputFolder : DEFAULT_SETTINGS.outputFolder,
DEFAULT_SETTINGS.outputFolder
),
autoCompressNewFiles: normalizeBoolean(source.autoCompressNewFiles, DEFAULT_SETTINGS.autoCompressNewFiles),
autoBackgroundCompression: normalizeBoolean(source.autoBackgroundCompression, DEFAULT_SETTINGS.autoBackgroundCompression),
autoBackgroundThreshold: clampInteger(source.autoBackgroundThreshold, DEFAULT_SETTINGS.autoBackgroundThreshold, 10, 1000),
inactivityThresholdMinutes: clampInteger(source.inactivityThresholdMinutes, DEFAULT_SETTINGS.inactivityThresholdMinutes, 1, 60),
cacheRetentionMonths: clampInteger(source.cacheRetentionMonths, DEFAULT_SETTINGS.cacheRetentionMonths, 1, 60),
autoCleanupGhostsOnStart: normalizeBoolean(source.autoCleanupGhostsOnStart, DEFAULT_SETTINGS.autoCleanupGhostsOnStart),
autoBackupsRetentionEnabled: normalizeBoolean(source.autoBackupsRetentionEnabled, DEFAULT_SETTINGS.autoBackupsRetentionEnabled),
autoBackupsRetentionDays: clampInteger(source.autoBackupsRetentionDays, DEFAULT_SETTINGS.autoBackupsRetentionDays, 1, 365),
autoMoveCompressedEnabled: normalizeBoolean(source.autoMoveCompressedEnabled, DEFAULT_SETTINGS.autoMoveCompressedEnabled),
autoMoveCompressedThreshold: clampInteger(source.autoMoveCompressedThreshold, DEFAULT_SETTINGS.autoMoveCompressedThreshold, 1, 1000)
};
}

View file

@ -0,0 +1,377 @@
import { t } from "./i18n";
import { getLogTag, getPluginName } from "./utils";
import type LocalImageCompressPlugin from "./plugin";
import type { TimerHandle } from "./types";
type StatusMenuAction = {
action: () => unknown;
text: string;
};
type StatusMenuOpenEvent = {
keyboard?: boolean;
preventDefault?: () => void;
returnFocusTo?: { focus?: () => void } | null;
target?: EventTarget | null;
};
const STATUS_MENU_VIEWPORT_MARGIN = 10;
const STATUS_MENU_FALLBACK_WIDTH = 360;
const STATUS_MENU_FALLBACK_HEIGHT = 160;
export class StatusBarController {
private readonly plugin: LocalImageCompressPlugin;
private openStatusMenu: HTMLElement | null = null;
private openStatusMenuDocument: Document | null = null;
private teardownStatusMenuListeners: (() => void) | null = null;
private deferredClickTimer: TimerHandle | null = null;
private statusMenuFocusTarget: { focus?: () => void } | null = null;
constructor(plugin: LocalImageCompressPlugin) {
this.plugin = plugin;
}
closeMenu(restoreFocus = false): void {
this.clearDeferredClickTimer();
if (typeof this.teardownStatusMenuListeners === "function") {
try {
const focusTarget = this.statusMenuFocusTarget;
this.teardownStatusMenuListeners();
if (restoreFocus) {
this.restoreStatusMenuFocus(focusTarget);
}
} catch (error) {
this.ignoreNonCriticalError(error);
}
return;
}
const activeDocument = this.openStatusMenuDocument || this.plugin.getActiveDocument();
if (this.openStatusMenu && activeDocument.body.contains(this.openStatusMenu)) {
try {
activeDocument.body.removeChild(this.openStatusMenu);
} catch (error) {
this.ignoreNonCriticalError(error);
}
}
this.openStatusMenu = null;
this.openStatusMenuDocument = null;
this.statusMenuFocusTarget = null;
this.setStatusMenuExpanded(false);
}
async update(): Promise<void> {
if (!this.plugin.statusBarItem) {
return;
}
const { uncompressedImages: uncompressedCount, totalImages: totalCount } = await this.plugin.getImageCompressionCounts();
if (totalCount > 0) {
const backlogThreshold = this.plugin.settings.autoBackgroundThreshold || this.plugin.backgroundCompressionService.AUTO_BACKGROUND_THRESHOLD || 50;
const hasBacklog = uncompressedCount >= backlogThreshold;
const statusText = this.plugin.backgroundCompressionService.isBackgroundCompressionRunning
? `\u27F3 ${uncompressedCount} / ${totalCount}`
: hasBacklog
? `\u25CF ${uncompressedCount} / ${totalCount}`
: `${uncompressedCount} / ${totalCount}`;
const accessibleStatusText = `${getPluginName(this.plugin)}: ${statusText}`;
this.plugin.statusBarItem.setText(statusText);
this.plugin.statusBarItem.setAttribute?.("aria-label", accessibleStatusText);
this.plugin.statusBarItem.setAttribute?.("title", accessibleStatusText);
this.plugin.statusBarItem.show();
this.plugin.statusBarItem.removeClass("tiny-local-compressing");
this.plugin.statusBarItem.removeClass("tiny-local-status-attention");
if (this.plugin.backgroundCompressionService.isBackgroundCompressionRunning) {
this.plugin.statusBarItem.addClass("tiny-local-compressing");
} else if (hasBacklog) {
this.plugin.statusBarItem.addClass("tiny-local-status-attention");
} else {
this.plugin.statusBarItem.removeClass("tiny-local-compressing");
}
} else {
this.plugin.statusBarItem.hide();
}
}
async showMenu(event: StatusMenuOpenEvent): Promise<void> {
const activeDocument = this.plugin.getActiveDocument();
const activeWindow = this.plugin.getActiveWindow();
// Close a previously opened menu before rendering the new one.
this.closeMenu();
const [
{ uncompressedImages: uncompressedCount, totalImages: totalCount },
movableCompressedCount
] = await Promise.all([
this.plugin.getImageCompressionCounts(),
this.plugin.moveService.getCompressedFilesCount()
]);
const menu = this.createMenu(event, uncompressedCount, totalCount, movableCompressedCount, activeDocument);
if (!menu) {
this.setStatusMenuExpanded(false);
return;
}
activeDocument.body.appendChild(menu);
this.positionMenu(menu, event, activeWindow);
this.setStatusMenuExpanded(true);
this.statusMenuFocusTarget = event?.returnFocusTo ?? (event?.keyboard ? event?.target as { focus?: () => void } ?? null : null);
// Attach listeners with centralized teardown
const teardown = (() => {
const onDocClick = (e: MouseEvent) => {
const target = e.target as Node | null;
if (!target || !menu.contains(target)) {
cleanup(false);
}
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault?.();
e.stopPropagation();
e.stopImmediatePropagation();
cleanup(true);
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
this.focusAdjacentMenuItem(menu, e, e.key === "ArrowDown" ? 1 : -1);
} else if (e.key === "Home" || e.key === "End") {
this.focusBoundaryMenuItem(menu, e, e.key === "Home" ? 0 : -1);
}
};
const onBlur = () => cleanup(false);
let clickListenerAttached = false;
const cleanup = (restoreFocus = false) => {
const focusTarget = this.statusMenuFocusTarget;
this.clearDeferredClickTimer();
if (clickListenerAttached) {
activeDocument.removeEventListener('click', onDocClick);
clickListenerAttached = false;
}
activeDocument.removeEventListener('keydown', onKeyDown);
activeWindow.removeEventListener('blur', onBlur);
if (activeDocument.body.contains(menu)) {
try {
activeDocument.body.removeChild(menu);
} catch (error) {
this.ignoreNonCriticalError(error);
}
}
if (this.openStatusMenu === menu) this.openStatusMenu = null;
if (this.openStatusMenuDocument === activeDocument) this.openStatusMenuDocument = null;
if (this.teardownStatusMenuListeners === cleanup) this.teardownStatusMenuListeners = null;
if (this.statusMenuFocusTarget === focusTarget) this.statusMenuFocusTarget = null;
this.setStatusMenuExpanded(false);
if (restoreFocus) {
this.restoreStatusMenuFocus(focusTarget);
}
};
// Defer click binding to avoid immediate close due to the opening click
this.deferredClickTimer = this.plugin.setWindowTimeout(() => {
this.deferredClickTimer = null;
if (this.plugin.isUnloading || this.openStatusMenu !== menu || this.teardownStatusMenuListeners !== cleanup) {
return;
}
// transient: menu-scoped, removed on close via cleanup() (registerDomEvent would leak across opens)
activeDocument.addEventListener('click', onDocClick);
clickListenerAttached = true;
}, 0);
activeDocument.addEventListener('keydown', onKeyDown);
activeWindow.addEventListener('blur', onBlur);
return cleanup;
})();
this.openStatusMenu = menu;
this.openStatusMenuDocument = activeDocument;
this.teardownStatusMenuListeners = teardown;
if (event?.keyboard) {
this.focusFirstMenuItem(menu);
}
}
private clearDeferredClickTimer(): void {
if (!this.deferredClickTimer) {
return;
}
try {
this.plugin.clearWindowTimeout(this.deferredClickTimer);
} catch (error) {
this.ignoreNonCriticalError(error);
}
this.deferredClickTimer = null;
}
private ignoreNonCriticalError(_error: unknown): void {
void _error;
}
private setStatusMenuExpanded(expanded: boolean): void {
this.plugin.statusBarItem?.setAttribute?.("aria-expanded", expanded ? "true" : "false");
}
private restoreStatusMenuFocus(focusTarget: { focus?: () => void } | null): void {
try {
focusTarget?.focus?.();
this.plugin.requestWindowAnimationFrame(() => {
if (this.plugin.isUnloading || !focusTarget?.focus) {
return;
}
const activeElement = this.plugin.getActiveDocument().activeElement;
if (activeElement !== focusTarget) {
focusTarget.focus();
}
});
this.plugin.setWindowTimeout(() => {
if (!this.plugin.isUnloading) {
focusTarget?.focus?.();
}
}, 0);
} catch (error) {
this.ignoreNonCriticalError(error);
}
}
private getMenuItems(menu: HTMLElement): HTMLElement[] {
return Array.from(menu.querySelectorAll(".tiny-local-status-menu-item"));
}
private focusFirstMenuItem(menu: HTMLElement): void {
const firstItem = this.getMenuItems(menu)[0];
try {
firstItem?.focus?.();
} catch (error) {
this.ignoreNonCriticalError(error);
}
}
private focusAdjacentMenuItem(menu: HTMLElement, event: KeyboardEvent, direction: 1 | -1): void {
const menuItems = this.getMenuItems(menu);
if (menuItems.length === 0) {
return;
}
event.preventDefault?.();
const activeDocument = this.openStatusMenuDocument || this.plugin.getActiveDocument();
const activeElement = activeDocument.activeElement as HTMLElement | null;
const currentTarget = event.target as HTMLElement | null || activeElement;
const currentIndex = Math.max(
currentTarget ? menuItems.indexOf(currentTarget) : -1,
activeElement ? menuItems.indexOf(activeElement) : -1
);
const nextIndex = currentIndex >= 0
? (currentIndex + direction + menuItems.length) % menuItems.length
: direction > 0
? 0
: menuItems.length - 1;
try {
menuItems[nextIndex]?.focus?.();
} catch (error) {
this.ignoreNonCriticalError(error);
}
}
private focusBoundaryMenuItem(menu: HTMLElement, event: KeyboardEvent, index: 0 | -1): void {
const menuItems = this.getMenuItems(menu);
if (menuItems.length === 0) {
return;
}
event.preventDefault?.();
try {
menuItems[index === 0 ? 0 : menuItems.length - 1]?.focus?.();
} catch (error) {
this.ignoreNonCriticalError(error);
}
}
private runMenuAction(action: StatusMenuAction["action"]): void {
this.closeMenu(true);
Promise.resolve(action()).catch((error) => {
console.error(getLogTag(this.plugin), "Status menu action failed:", error);
});
}
private getFiniteNumber(value: unknown, fallback: number): number {
const numeric = typeof value === "number" ? value : Number(value);
return Number.isFinite(numeric) ? numeric : fallback;
}
private getMenuTargetRect(event: StatusMenuOpenEvent): { bottom?: number; height: number; left: number; top: number; width: number } | null {
const target = event?.target as { getBoundingClientRect?: () => { bottom?: number; height: number; left: number; top: number; width: number } } | null | undefined;
const rect = target?.getBoundingClientRect?.();
if (!rect || (rect.width === 0 && rect.height === 0)) {
return null;
}
return rect;
}
private positionMenu(menu: HTMLElement, event: StatusMenuOpenEvent, activeWindow = this.plugin.getActiveWindow()): void {
const rect = this.getMenuTargetRect(event);
if (!rect) {
return;
}
const measuredRect = menu.getBoundingClientRect?.();
const measuredWidth = this.getFiniteNumber(measuredRect?.width, 0);
const measuredHeight = this.getFiniteNumber(measuredRect?.height, 0);
const menuWidth = measuredWidth > 0 ? measuredWidth : STATUS_MENU_FALLBACK_WIDTH;
const menuHeight = measuredHeight > 0 ? measuredHeight : STATUS_MENU_FALLBACK_HEIGHT;
const viewportWidth = Math.max(menuWidth + STATUS_MENU_VIEWPORT_MARGIN * 2, this.getFiniteNumber(activeWindow.innerWidth, menuWidth + STATUS_MENU_VIEWPORT_MARGIN * 2));
const viewportHeight = Math.max(menuHeight + STATUS_MENU_VIEWPORT_MARGIN * 2, this.getFiniteNumber(activeWindow.innerHeight, menuHeight + STATUS_MENU_VIEWPORT_MARGIN * 2));
const maxLeft = Math.max(STATUS_MENU_VIEWPORT_MARGIN, viewportWidth - menuWidth - STATUS_MENU_VIEWPORT_MARGIN);
const left = Math.max(STATUS_MENU_VIEWPORT_MARGIN, Math.min(rect.left, maxLeft));
const rectBottom = typeof rect.bottom === "number" ? rect.bottom : rect.top + rect.height;
const topAbove = rect.top - menuHeight - STATUS_MENU_VIEWPORT_MARGIN;
const topBelow = rectBottom + STATUS_MENU_VIEWPORT_MARGIN;
const topFitsAbove = topAbove >= STATUS_MENU_VIEWPORT_MARGIN;
const topFitsBelow = topBelow + menuHeight <= viewportHeight - STATUS_MENU_VIEWPORT_MARGIN;
const preferredTop = topFitsAbove || !topFitsBelow ? topAbove : topBelow;
const maxTop = Math.max(STATUS_MENU_VIEWPORT_MARGIN, viewportHeight - menuHeight - STATUS_MENU_VIEWPORT_MARGIN);
const top = Math.max(STATUS_MENU_VIEWPORT_MARGIN, Math.min(preferredTop, maxTop));
menu.setCssProps({
"--local-image-compress-status-menu-left": `${Math.round(left)}px`,
"--local-image-compress-status-menu-top": `${Math.round(top)}px`,
"--local-image-compress-status-menu-transform": "none"
});
}
createMenu(event: StatusMenuOpenEvent, uncompressedCount: number, totalCount: number, movableCompressedCount = 0, activeDocument = this.plugin.getActiveDocument()) {
const rect = this.getMenuTargetRect(event);
if (!rect) {
console.warn(getLogTag(this.plugin), "Status menu skipped because the status bar item is not visible");
return null;
}
const menu = activeDocument.body.createDiv();
menu.className = "tiny-local-status-menu";
menu.setAttribute("role", "menu");
menu.setAttribute("aria-label", getPluginName(this.plugin));
menu.createDiv({
text: `${t(this.plugin.app, "stats.uncompressed.name")}: ${uncompressedCount} / ${totalCount}`,
cls: "tiny-local-status-menu-header"
});
const menuItems: StatusMenuAction[] = [
{ text: t(this.plugin.app, "command.compressInNote"), action: () => this.plugin.compressImagesInNote() },
{ text: t(this.plugin.app, "command.compressAll"), action: () => this.plugin.compressAllImages() }
];
if (movableCompressedCount > 0) {
menuItems.push({
text: `${t(this.plugin.app, "command.moveCompressed")} (${movableCompressedCount})`,
action: () => this.plugin.moveService.moveCompressedToFiles()
});
}
menuItems.forEach((item) => {
const menuItem = menu.createEl("button", {
text: item.text,
cls: "tiny-local-status-menu-item"
});
menuItem.type = "button";
menuItem.setAttribute("role", "menuitem");
// transient: menu recreated per open; element removed on close
menuItem.addEventListener("click", () => {
this.runMenuAction(item.action);
});
menuItem.addEventListener("keydown", (event2: KeyboardEvent) => {
if (event2.key !== "Enter" && event2.key !== " ") {
return;
}
event2.preventDefault();
this.runMenuAction(item.action);
});
});
return menu;
}
}

103
src-ts/types.ts Normal file
View file

@ -0,0 +1,103 @@
import type { TFile } from "obsidian";
export type CacheEntryState = "processed" | "pending_move" | "moved" | "skipped" | "skipped_identical";
export type TimerHandle = number | ReturnType<typeof setTimeout>;
export type AnimationHandle = ReturnType<typeof requestAnimationFrame> | TimerHandle;
export type ImageFileLike = TFile;
export interface CacheEntry {
path?: string;
md5?: string;
mtime?: number;
timestamp?: number;
lastAccessMs?: number;
originalSize?: number | null;
sourceMtime?: number;
sourceSize?: number | null;
state?: CacheEntryState;
stateUpdatedAt?: number;
pendingSince?: number;
outputPath?: string;
outputMtime?: number;
outputSize?: number;
skipReason?: string;
compressionSettingsKey?: string;
processedMtime?: number;
processedSize?: number;
}
export interface CacheData {
version: string;
entries: Record<string, CacheEntry>;
}
export interface FreshCacheEntry {
cacheKey: string;
entry: CacheEntry;
}
export type CachePathEntries = Array<[string, CacheEntry]>;
export interface CacheStats {
total: number;
size: number;
}
export interface CompressionResult {
success: boolean;
savings?: number;
error?: string;
skipReason?: string;
}
export type CompressionValidationResult =
| { valid: true }
| { valid: false; error: string; skipped?: boolean };
export interface CompressionBatchResult {
compressed: number;
processed: number;
skippedAlreadyCompressed: number;
skippedValidation: number;
skippedErrors: number;
cancelled: boolean;
fatalError?: unknown;
}
export type CompressionBatchCallback<TPayload = unknown> = (
file: ImageFileLike,
processed: number,
total: number,
payload?: TPayload
) => void | Promise<void>;
export interface SavingsSnapshot {
originalSize: number;
currentSize: number;
savedSize: number;
savedPercentage: number;
processedFiles: number;
totalFiles: number;
estimatedFiles: number;
}
export interface ImageStatsSnapshot {
totalFiles?: number;
totalImages: number;
uncompressedImages: number;
savings: SavingsSnapshot;
}
export interface StatsSnapshot extends ImageStatsSnapshot {
cacheStats: CacheStats;
ghostCount: number;
compressedFilesCount: number;
}
export interface FileStatsLike {
size?: unknown;
mtime?: unknown;
mtimeMs?: unknown;
}

356
src-ts/utils.ts Normal file
View file

@ -0,0 +1,356 @@
import * as crypto from "crypto";
import * as fs from "fs";
import * as path from "path";
import * as obsidian from "obsidian";
import { promisify } from "util";
import { shell } from "electron";
const randomBytesAsync = promisify(crypto.randomBytes) as (size: number) => Promise<Buffer>;
const CASE_INSENSITIVE_PATH_PLATFORM = process.platform === "win32" || process.platform === "darwin";
const MAX_SANITIZED_PATH_LENGTH = 500;
const SENSITIVE_PATH_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "bmp", "heic", "heif", "avif", "json", "tmp", "bak", "log", "txt", "md"];
const SENSITIVE_UNIX_ROOTS = ["Users", "home", "var", "opt", "tmp", "usr", "etc", "private"];
type AppWithActiveWorkspaceDom = {
workspace?: {
activeWindow?: Window;
activeDocument?: Document;
};
};
export function getVaultFileByPath(vault: obsidian.Vault, filePath: string): obsidian.TFile | null {
const normalizedPath = normalizeVaultPath(filePath);
// Obsidian 1.4 fallback is retained below; feature-detect the 1.5.7+ direct API.
const modernLookup = Reflect.get(vault, "getFileByPath") as unknown;
if (typeof modernLookup === "function") {
return modernLookup.call(vault, normalizedPath) as obsidian.TFile | null;
}
const abstractFile = vault.getAbstractFileByPath(normalizedPath);
return abstractFile instanceof obsidian.TFile ? abstractFile : null;
}
export function getActiveWindowForApp(app: unknown): Window | undefined {
const workspaceWindow = (app as AppWithActiveWorkspaceDom | null | undefined)?.workspace?.activeWindow;
if (workspaceWindow) {
return workspaceWindow;
}
if (typeof activeWindow !== "undefined") {
return activeWindow;
}
return typeof window !== "undefined" ? window : undefined;
}
export function getActiveDocumentForApp(app: unknown): Document | undefined {
const workspaceDocument = (app as AppWithActiveWorkspaceDom | null | undefined)?.workspace?.activeDocument;
if (workspaceDocument) {
return workspaceDocument;
}
if (typeof activeDocument !== "undefined") {
return activeDocument;
}
return getActiveWindowForApp(app)?.document;
}
export function stripWindowsLongPathPrefix(filePath: string): string {
const value = String(filePath || "");
if (value.startsWith("\\\\?\\UNC\\")) {
return `\\\\${value.slice(8)}`;
}
if (value.startsWith("//?/UNC/")) {
return `//${value.slice(8)}`;
}
if (/^\\\\\?\\[A-Za-z]:[\\/]/.test(value) || /^\/\/\?\/[A-Za-z]:[\\/]/.test(value)) {
return value.slice(4);
}
return value;
}
export function isWindowsDriveFilesystemPath(filePath: string): boolean {
return /^[a-zA-Z]:[\\/]/.test(stripWindowsLongPathPrefix(filePath));
}
export function isUncFilesystemPath(filePath: string): boolean {
const value = stripWindowsLongPathPrefix(filePath);
return /^\\\\[^\\]+\\[^\\]+/.test(value) || /^\/\/[^/]+\/[^/]+/.test(value);
}
function getPathModuleForFilesystemPath(filePath: string, basePath = "") {
return isWindowsDriveFilesystemPath(filePath) || isWindowsDriveFilesystemPath(basePath) || isUncFilesystemPath(filePath) || isUncFilesystemPath(basePath)
? path.win32
: path;
}
// path & html helpers
export function normalizeVaultPath(p: string): string {
return stripWindowsLongPathPrefix(String(p || "")).normalize("NFC").replace(/\\/g, "/").replace(/\/+/g, "/");
}
export function normalizeVaultPathRoot(p: string): string {
return normalizeVaultPath(p).replace(/^\/+|\/+$/g, "");
}
export function normalizeVaultPathForComparison(p: string): string {
const normalized = normalizeVaultPathRoot(p);
return CASE_INSENSITIVE_PATH_PLATFORM ? normalized.toLowerCase() : normalized;
}
export function vaultPathsEqual(leftPath: string, rightPath: string): boolean {
return normalizeVaultPathForComparison(leftPath) === normalizeVaultPathForComparison(rightPath);
}
export function isSafeVaultRelativePath(p: string): boolean {
const rawPath = String(p || "").trim();
if (!rawPath) return false;
const normalizedPath = normalizeVaultPath(rawPath);
if (isAbsoluteFilesystemPath(rawPath)) return false;
if (normalizedPath.startsWith("/") || normalizedPath.startsWith("//")) return false;
const parts = normalizedPath.split("/");
return parts.every((part) => part !== "" && part !== "." && part !== "..");
}
export function normalizeOutputFolder(outputFolderName: string, fallback = "Compressed"): string {
const rawPath = String(outputFolderName || "").trim();
if (!isSafeVaultRelativePath(rawPath)) {
return fallback;
}
return normalizeVaultPath(rawPath).replace(/^\/+|\/+$/g, "");
}
export function isValidOutputFolder(outputFolderName: string): boolean {
return isSafeVaultRelativePath(outputFolderName);
}
export function isPathInsideRoot(targetPath: string, rootPath: string): boolean {
const safeRoot = normalizeVaultPathForComparison(rootPath);
if (!safeRoot) return true;
const safeTarget = normalizeVaultPathForComparison(targetPath);
return safeTarget === safeRoot || safeTarget.startsWith(`${safeRoot}/`);
}
export function isAllowedByRoots(targetPath: string, allowedRoots?: string[]): boolean {
if (!allowedRoots || allowedRoots.length === 0) return true;
return allowedRoots.some((root) => isPathInsideRoot(targetPath, root));
}
export function isAbsoluteFilesystemPath(filePath: string | null | undefined): boolean {
const value = stripWindowsLongPathPrefix(String(filePath || ""));
return path.isAbsolute(value) || isWindowsDriveFilesystemPath(value) || isUncFilesystemPath(value);
}
export type VaultBasePathAdapter = {
getBasePath?: () => string;
};
export type AppOrVaultWithAdapter = {
vault?: {
adapter?: unknown;
};
adapter?: unknown;
};
export type ManifestLike = {
manifest?: {
id?: string;
name?: string;
};
};
export function getErrorCode(error: unknown): string | undefined {
if (typeof error !== "object" || error === null || !("code" in error)) {
return undefined;
}
const code = (error as { code?: unknown }).code;
return typeof code === "string" || typeof code === "number" ? String(code) : undefined;
}
export function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return typeof error === "string" ? error : "";
}
export function getVaultBasePathFromAdapter(adapter: unknown, fallback?: string): string {
const candidate = adapter as VaultBasePathAdapter | null | undefined;
try {
const methodPath = typeof candidate?.getBasePath === "function" ? candidate.getBasePath() : "";
if (typeof methodPath === "string" && isAbsoluteFilesystemPath(methodPath)) {
return stripWindowsLongPathPrefix(methodPath);
}
} catch (error) {
void error;
}
if (typeof fallback === "string" && isAbsoluteFilesystemPath(fallback)) {
return stripWindowsLongPathPrefix(fallback);
}
throw new Error("Vault filesystem base path is unavailable; refusing filesystem access outside the vault.");
}
export function getVaultBasePath(appOrVault: AppOrVaultWithAdapter | null | undefined, fallback?: string): string {
const vault = appOrVault?.vault || appOrVault;
return getVaultBasePathFromAdapter(vault?.adapter, fallback);
}
export function toVaultRelativePath(filePath: string | null | undefined, basePath: string): string {
const rawPath = stripWindowsLongPathPrefix(String(filePath || ""));
if (!rawPath) {
return "";
}
const safeBasePath = stripWindowsLongPathPrefix(String(basePath || ""));
const pathModule = getPathModuleForFilesystemPath(rawPath, safeBasePath);
return normalizeVaultPath(isAbsoluteFilesystemPath(rawPath) ? pathModule.relative(safeBasePath, rawPath) : rawPath);
}
export function getVaultFolderPath(filePath: string): string {
const safePath = normalizeVaultPathRoot(filePath);
const slashIndex = safePath.lastIndexOf("/");
return slashIndex === -1 ? "" : safePath.slice(0, slashIndex);
}
export async function openFilesystemPath(targetPath: string): Promise<string> {
return await shell.openPath(targetPath);
}
export function isInsideOutputFolder(targetPath: string, outputFolderName: string): boolean {
const safeOutput = normalizeOutputFolder(outputFolderName);
if (!safeOutput) return false;
const safeTarget = normalizeVaultPath(targetPath).replace(/^\/+|\/+$/g, "");
return isPathInsideRoot(safeTarget, safeOutput);
}
export function getLogTag(self: unknown): string {
try {
const source = self as ManifestLike | null | undefined;
const name = source?.manifest?.name || "Local Image Compress";
return `[${name}]`;
} catch (error) {
void error;
return "[Local Image Compress]";
}
}
export function getPluginName(self: unknown): string {
try {
const source = self as ManifestLike | null | undefined;
return source?.manifest?.name || "Local Image Compress";
} catch (error) {
void error;
return "Local Image Compress";
}
}
export function getPluginId(self: unknown): string {
try {
const source = self as ManifestLike | null | undefined;
return source?.manifest?.id || 'local-image-compress';
} catch (error) {
void error;
return 'local-image-compress';
}
}
function startsWithIgnoreCase(value: string, index: number, prefix: string): boolean {
return value.slice(index, index + prefix.length).toLowerCase() === prefix.toLowerCase();
}
function isPathHardDelimiter(char: string): boolean {
return char === '"' || char === "'" || char === "<" || char === ">" || char === "\n" || char === "\r" || char === "\t";
}
function isPathTokenDelimiter(char: string): boolean {
return isPathHardDelimiter(char) || char === " " || char === ")" || char === "(" || char === "[" || char === "]" || char === "{" || char === "}";
}
function boundedWindowEnd(message: string, start: number): number {
const maxEnd = Math.min(message.length, start + MAX_SANITIZED_PATH_LENGTH);
for (let index = start; index < maxEnd; index++) {
if (isPathHardDelimiter(message[index] || "")) {
return index;
}
}
return maxEnd;
}
function tokenEnd(message: string, start: number): number {
for (let index = start; index < message.length; index++) {
if (isPathTokenDelimiter(message[index] || "")) {
return index;
}
}
return message.length;
}
function findSensitiveExtensionEnd(message: string, start: number, end: number): number | null {
for (let index = start; index < end; index++) {
if (message[index] !== ".") {
continue;
}
const extension = SENSITIVE_PATH_EXTENSIONS.find((candidate) => startsWithIgnoreCase(message, index + 1, candidate));
if (!extension) {
continue;
}
const afterExtension = index + 1 + extension.length;
const nextChar = message[afterExtension] || "";
if (!nextChar || !/[A-Za-z0-9_-]/.test(nextChar)) {
return afterExtension;
}
}
return null;
}
function startsSensitiveUnixPath(message: string, index: number): boolean {
if (message[index] !== "/") {
return false;
}
return SENSITIVE_UNIX_ROOTS.some((root) => startsWithIgnoreCase(message, index + 1, `${root}/`));
}
function startsLocalhostUrl(message: string, index: number): boolean {
return startsWithIgnoreCase(message, index, "http://localhost") ||
startsWithIgnoreCase(message, index, "https://localhost") ||
startsWithIgnoreCase(message, index, "http://127.0.0.1") ||
startsWithIgnoreCase(message, index, "https://127.0.0.1");
}
function getSensitivePathReplacement(message: string, index: number): { end: number; replacement: string } | null {
if (startsLocalhostUrl(message, index)) {
return { end: tokenEnd(message, index), replacement: "<url>" };
}
const startsFileUri = startsWithIgnoreCase(message, index, "file://");
const startsWindowsDrive = /^[A-Za-z]$/.test(message[index] || "") && message[index + 1] === ":" && (message[index + 2] === "\\" || message[index + 2] === "/");
const startsUncPath = message[index] === "\\" && message[index + 1] === "\\";
const startsHomePath = message[index] === "~" && message[index + 1] === "/";
const startsUnixPath = startsSensitiveUnixPath(message, index);
if (!startsFileUri && !startsWindowsDrive && !startsUncPath && !startsHomePath && !startsUnixPath) {
return null;
}
const windowEnd = boundedWindowEnd(message, index);
return {
end: findSensitiveExtensionEnd(message, index, windowEnd) ?? tokenEnd(message, index),
replacement: "<path>"
};
}
export function sanitizeErrorForUser(error: unknown): string {
const message = getErrorMessage(error);
let sanitized = "";
let index = 0;
while (index < message.length) {
const replacement = getSensitivePathReplacement(message, index);
if (replacement && replacement.end > index) {
sanitized += replacement.replacement;
index = replacement.end;
continue;
}
sanitized += message[index];
index++;
}
return sanitized;
}
export async function randomHexSuffix(byteCount = 16): Promise<string> {
return (await randomBytesAsync(byteCount)).toString("hex");
}
export function randomHexSuffixSync(): string {
return crypto.randomUUID().replace(/-/g, "");
}
export async function streamHashSha256(filePath: string): Promise<string> {
return await new Promise<string>((resolve, reject) => {
const hash = crypto.createHash("sha256");
const stream = fs.createReadStream(filePath, { highWaterMark: 256 * 1024 });
stream.on("data", (chunk) => {
hash.update(chunk);
});
stream.on("end", () => resolve(hash.digest("hex")));
stream.on("error", reject);
});
}

35
src-ts/wasm-modules.d.ts vendored Normal file
View file

@ -0,0 +1,35 @@
declare module "*.wasm" {
const bytes: Uint8Array;
export default bytes;
}
declare module "imagequant/imagequant_bg.js" {
export class Imagequant {
set_quality(min: number, max: number): void;
set_speed(speed: number): void;
process(image: ImagequantImage): Uint8Array;
free(): void;
}
export class ImagequantImage {
constructor(data: Uint8Array, width: number, height: number, gamma: number);
free(): void;
}
export function __wbg_set_wasm(exports: WebAssembly.Exports): void;
export function __wbindgen_error_new(ptr: number, len: number): unknown;
export function __wbindgen_throw(ptr: number, len: number): never;
}
declare module "@jsquash/jpeg/decode.js" {
export function init(module: WebAssembly.Module, moduleOptionOverrides?: Record<string, unknown>): Promise<void>;
export default function decode(buffer: ArrayBuffer, options?: Record<string, unknown>): Promise<ImageData>;
}
declare module "@jsquash/jpeg/encode.js" {
export function init(module: WebAssembly.Module, moduleOptionOverrides?: Record<string, unknown>): Promise<void>;
export default function encode(data: ImageData, options?: Record<string, unknown>): Promise<ArrayBuffer>;
}
declare module "virtual:compression-worker" {
const source: string;
export default source;
}

321
src-ts/worker-pool.ts Normal file
View file

@ -0,0 +1,321 @@
import type { LocalImageCompressSettings } from "./settings";
import { WorkerSlot, type WasmBytes, type WorkerFactory, type WorkerFormat, type WorkerHostApp } from "./worker-slot";
import type { TimerHandle } from "./types";
import { getActiveWindowForApp } from "./utils";
type SlotWaiter = {
resolve: (slot: WorkerSlot) => void;
reject: (reason?: unknown) => void;
};
function clampPoolSize(value: unknown) {
const numeric = typeof value === "number" ? value : Number(value);
const integer = Number.isFinite(numeric) ? Math.trunc(numeric) : 1;
return Math.max(1, Math.min(8, integer));
}
export class WorkerPool {
slots: WorkerSlot[];
waiters: SlotWaiter[];
destroyed: boolean;
private destroyError: Error | null;
private staggeredInitQueue: WorkerSlot[];
private staggeredInitActive: boolean;
private staggeredInitTimer: TimerHandle | null;
private readonly MAX_WAITERS = 5000;
constructor(
private readonly workerFactory: WorkerFactory | null,
private readonly getApp: () => WorkerHostApp,
private readonly getTimeoutMs: () => number,
private readonly getInitTimeoutMs: () => number,
private readonly workerSource: string,
private readonly wasmBytes: WasmBytes,
initialSize: number
) {
this.slots = [];
this.waiters = [];
this.destroyed = false;
this.destroyError = null;
this.staggeredInitQueue = [];
this.staggeredInitActive = false;
this.staggeredInitTimer = null;
this.resize(initialSize);
}
getReadyState() {
const anyReady = this.slots.some((slot) => slot.isReady());
return {
pngquant: anyReady,
mozjpeg: anyReady
};
}
getInitError() {
if (this.destroyed) {
return this.destroyError || new Error("Compressor worker stopped because the plugin was unloaded");
}
if (this.slots.length === 0 || this.slots.some((slot) => slot.isReady() || !slot.getInitError())) {
return null;
}
const firstError = this.slots[0]?.getInitError();
return firstError || new Error("All compression workers failed to initialize");
}
async ensureAnyReady(): Promise<void> {
if (this.destroyed) {
throw this.getInitError() ?? new Error("Compressor worker stopped");
}
if (this.slots.some((slot) => slot.isReady())) {
return;
}
if (this.slots.length === 0) {
throw new Error("Compression worker pool is empty");
}
const errors: Error[] = [];
while (!this.destroyed) {
const readySlot = this.slots.find((slot) => slot.isReady());
if (readySlot) {
return;
}
const initError = this.getInitError();
if (initError) {
throw errors[0] || initError;
}
const slot = this.findReadinessSlot();
if (!slot) {
throw errors[0] || new Error("No compression worker is available");
}
try {
await slot.init();
this.enableInitRetryForFailedSlots();
this.dispatchWaiters();
return;
} catch (error) {
errors.push(error instanceof Error ? error : new Error(String(error)));
this.enableInitRetryForFailedSlots();
this.dispatchWaiters();
}
}
throw this.getInitError() ?? new Error("Compressor worker stopped");
}
async runJob(format: WorkerFormat, buffer: ArrayBuffer, settings: LocalImageCompressSettings): Promise<ArrayBuffer> {
const slot = await this.acquireSlot();
try {
return await slot.runCompression(format, buffer, settings);
} finally {
this.enableInitRetryForFailedSlots();
this.dispatchWaiters();
}
}
async drainInFlight(timeoutMs = 5000) {
const startedAt = Date.now();
while (!this.destroyed && (this.waiters.length > 0 || this.slots.some((slot) => slot.isBusy()))) {
this.dispatchWaiters();
if (Date.now() - startedAt >= timeoutMs) {
return false;
}
await new Promise((resolve) => this.setWindowTimeout(() => resolve(undefined), 25));
}
return true;
}
resize(newSize: number) {
const size = clampPoolSize(newSize);
if (size > this.slots.length) {
while (this.slots.length < size) {
const slot = this.createSlot();
this.slots.push(slot);
this.queueSlotInit(slot);
}
return;
}
if (size < this.slots.length) {
const removed = this.slots.splice(size);
this.staggeredInitQueue = this.staggeredInitQueue.filter((slot) => !removed.includes(slot));
for (const slot of removed) {
slot.destroy(new Error("Compression worker pool was resized"));
}
}
this.dispatchWaiters();
}
destroy(error: Error) {
this.destroyed = true;
this.destroyError = error;
this.staggeredInitQueue = [];
if (this.staggeredInitTimer) {
this.clearWindowTimeout(this.staggeredInitTimer);
this.staggeredInitTimer = null;
}
for (const waiter of this.waiters.splice(0)) {
waiter.reject(error);
}
for (const slot of this.slots) {
slot.destroy(error);
}
}
private createSlot() {
return new WorkerSlot(
this.workerFactory,
this.getApp,
this.getTimeoutMs,
this.getInitTimeoutMs,
this.workerSource,
this.wasmBytes
);
}
private queueSlotInit(slot: WorkerSlot) {
this.staggeredInitQueue.push(slot);
this.startNextStaggeredSlotInit();
}
private startNextStaggeredSlotInit() {
if (this.destroyed || this.staggeredInitActive || this.staggeredInitTimer) {
return;
}
const slot = this.staggeredInitQueue.shift();
if (!slot) {
return;
}
if (slot.isReady() || slot.isBusy() || slot.getInitError()) {
this.scheduleNextStaggeredSlotInit();
return;
}
this.staggeredInitActive = true;
this.startSlotInit(slot)
.catch((error) => {
if (!this.destroyed) {
console.warn("[Local Image Compress]", "Staggered worker initialization failed:", error);
}
})
.finally(() => {
this.staggeredInitActive = false;
if (this.destroyed || this.staggeredInitQueue.length === 0) {
return;
}
this.scheduleNextStaggeredSlotInit();
});
}
private scheduleNextStaggeredSlotInit() {
if (this.destroyed || this.staggeredInitTimer || this.staggeredInitQueue.length === 0) {
return;
}
this.staggeredInitTimer = this.setWindowTimeout(() => {
this.staggeredInitTimer = null;
this.startNextStaggeredSlotInit();
}, 0);
}
private startSlotInit(slot: WorkerSlot) {
return slot.init().then(() => {
this.enableInitRetryForFailedSlots();
this.dispatchWaiters();
}).catch(() => {
this.enableInitRetryForFailedSlots();
this.dispatchWaiters();
});
}
private setWindowTimeout(callback: TimerHandler, delay: number) {
const windowRef = getActiveWindowForApp(this.getApp()) || window;
return windowRef.setTimeout(callback, delay);
}
private clearWindowTimeout(timer: TimerHandle | null | undefined) {
if (timer === null || timer === undefined) {
return;
}
const windowRef = getActiveWindowForApp(this.getApp()) || window;
windowRef.clearTimeout(timer as number);
}
private enableInitRetryForFailedSlots() {
if (!this.slots.some((slot) => slot.isReady())) {
return;
}
for (const slot of this.slots) {
if (slot.getInitError()) {
slot.allowInitRetry();
}
}
}
private findReadinessSlot() {
const initializingSlot = this.slots.find((slot) => slot.isInitializing());
if (initializingSlot) {
return initializingSlot;
}
const recreateSlot = this.slots.find((slot) => slot.shouldRecreateOnDemand());
if (recreateSlot) {
return recreateSlot;
}
return this.slots.find((slot) => slot.canAcceptJob()) || null;
}
private acquireSlot(): Promise<WorkerSlot> {
if (this.destroyed) {
return Promise.reject(this.getInitError() ?? new Error("Compressor worker stopped"));
}
const slot = this.findAndReserveSlot();
if (slot) {
return Promise.resolve(slot);
}
const initError = this.getInitError();
if (initError) {
return Promise.reject(initError);
}
if (this.waiters.length >= this.MAX_WAITERS) {
return Promise.reject(new Error(`Worker pool waiters queue full (${this.MAX_WAITERS})`));
}
return new Promise<WorkerSlot>((resolve, reject) => {
this.waiters.push({ resolve, reject });
});
}
private findAndReserveSlot() {
const readySlot = this.slots.find((slot) => slot.isReady() && slot.canAcceptJob());
if (readySlot?.tryReserve()) {
return readySlot;
}
const recreateSlot = this.slots.find((slot) => slot.shouldRecreateOnDemand());
if (recreateSlot?.tryReserve()) {
return recreateSlot;
}
const coldSlot = this.slots.find((slot) => slot.canAcceptJob());
if (coldSlot?.tryReserve()) {
return coldSlot;
}
return null;
}
private dispatchWaiters() {
while (this.waiters.length > 0) {
if (this.destroyed) {
const error = this.getInitError();
for (const waiter of this.waiters.splice(0)) {
waiter.reject(error);
}
return;
}
const slot = this.findAndReserveSlot();
if (!slot) {
const initError = this.getInitError();
if (initError) {
for (const waiter of this.waiters.splice(0)) {
waiter.reject(initError);
}
}
return;
}
const waiter = this.waiters.shift();
waiter?.resolve(slot);
}
}
}

465
src-ts/worker-slot.ts Normal file
View file

@ -0,0 +1,465 @@
import type { LocalImageCompressSettings } from "./settings";
import type { TimerHandle } from "./types";
import { clearTimeout as fallbackClearTimeout, setTimeout as fallbackSetTimeout } from "timers";
import { getActiveWindowForApp } from "./utils";
export type WorkerFormat = "png" | "jpeg";
export type WorkerFactory = (source: string) => Worker;
export type WorkerInputBuffer = ArrayBuffer | ArrayBufferView;
export type WasmBytes = {
jpegDecode: Uint8Array;
jpegEncode: Uint8Array;
png: Uint8Array;
imagequant: Uint8Array;
};
type WorkerErrorPayload = {
kind?: string;
message?: string;
skipReason?: string;
};
export type WorkerHostApp = unknown;
type WorkerMessageEnvelope = {
type?: unknown;
id?: unknown;
ok?: unknown;
output?: unknown;
error?: WorkerErrorPayload;
};
type ActiveWorkerJob = {
id: number;
timeoutHandle: TimerHandle;
resolve: (value: ArrayBuffer) => void;
reject: (reason?: unknown) => void;
};
type ActiveWorkerInit = {
id: number;
timeoutHandle: TimerHandle;
resolve: () => void;
reject: (reason?: unknown) => void;
};
export class WasmTimeoutError extends Error {
constructor(message: string) {
super(message);
this.name = "WasmTimeoutError";
}
}
export class WorkerCompressionError extends Error {
kind: string;
skipReason?: string;
constructor(payload: WorkerErrorPayload) {
super(payload.message || "Worker compression failed");
this.name = "WorkerCompressionError";
this.kind = payload.kind || "unknown";
if (payload.skipReason !== undefined) {
this.skipReason = payload.skipReason;
}
}
}
export class WorkerSlot {
worker: Worker | null;
objectUrl: string | null;
workerInit: ActiveWorkerInit | null;
activeJob: ActiveWorkerJob | null;
wasmReady: boolean;
wasmInitError: Error | null;
needsRecreate: boolean;
destroyed: boolean;
nextMessageId: number;
private initPromise: Promise<void> | null;
private reserved: boolean;
constructor(
private readonly workerFactory: WorkerFactory | null,
private readonly getApp: () => WorkerHostApp,
private readonly getTimeoutMs: () => number,
private readonly getInitTimeoutMs: () => number,
private readonly workerSource: string,
private readonly wasmBytes: WasmBytes
) {
this.worker = null;
this.objectUrl = null;
this.workerInit = null;
this.activeJob = null;
this.wasmReady = false;
this.wasmInitError = null;
this.needsRecreate = false;
this.destroyed = false;
this.nextMessageId = 1;
this.initPromise = null;
this.reserved = false;
}
init(): Promise<void> {
if (this.destroyed) {
const error = this.wasmInitError || new Error("Compressor has been destroyed");
this.wasmInitError = error;
return Promise.reject(error);
}
if (this.wasmReady) {
return Promise.resolve();
}
if (this.initPromise) {
return this.initPromise;
}
if (this.wasmInitError && !this.needsRecreate) {
return Promise.reject(this.wasmInitError);
}
this.needsRecreate = false;
this.wasmReady = false;
this.wasmInitError = null;
const id = this.nextMessageId++;
this.initPromise = new Promise<void>((resolve, reject) => {
const initTimeoutMs = this.getInitTimeoutMs();
const timeoutHandle = this.setWorkerTimeout(() => {
if (this.destroyed) {
return;
}
if (this.workerInit?.id !== id) {
return;
}
const error = new WasmTimeoutError(`WASM worker init timed out after ${initTimeoutMs}ms`);
this.failActiveWorkerState(error, true);
}, initTimeoutMs);
this.workerInit = { id, timeoutHandle, resolve, reject };
try {
const worker = this.createWorker();
// KKK2-A-5: attach error/message handlers BEFORE storing the reference so a
// worker that surfaces a creation error has a handler in place (Lesson #211).
worker.onmessage = (event) => this.handleWorkerMessage(event.data);
worker.onerror = (event) => this.handleWorkerError(event);
this.worker = worker;
const wasm = {
jpegDecode: this.cloneAsArrayBuffer(this.wasmBytes.jpegDecode),
jpegEncode: this.cloneAsArrayBuffer(this.wasmBytes.jpegEncode),
png: this.cloneAsArrayBuffer(this.wasmBytes.png),
imagequant: this.cloneAsArrayBuffer(this.wasmBytes.imagequant)
};
worker.postMessage({ id, type: "init", wasm }, [
wasm.jpegDecode,
wasm.jpegEncode,
wasm.png,
wasm.imagequant
]);
} catch (error) {
this.clearWorkerTimeout(timeoutHandle);
this.workerInit = null;
this.wasmReady = false;
this.wasmInitError = error instanceof Error ? error : new Error(String(error));
this.terminateWorker();
reject(this.wasmInitError);
}
}).finally(() => {
this.initPromise = null;
});
return this.initPromise;
}
isReady() {
return this.wasmReady && !!this.worker && !this.destroyed;
}
isBusy() {
return this.reserved || !!this.workerInit || !!this.activeJob;
}
isInitializing() {
return !!this.workerInit;
}
getInitError() {
return this.wasmInitError;
}
canAcceptJob() {
return !this.destroyed && !this.isBusy() && (!this.wasmInitError || this.needsRecreate);
}
shouldRecreateOnDemand() {
return this.needsRecreate && this.canAcceptJob();
}
allowInitRetry() {
if (this.wasmInitError && !this.destroyed) {
this.needsRecreate = true;
}
}
tryReserve() {
if (!this.canAcceptJob()) {
return false;
}
this.reserved = true;
return true;
}
async runCompression(format: WorkerFormat, buffer: WorkerInputBuffer, settings: LocalImageCompressSettings): Promise<ArrayBuffer> {
if (!this.reserved && !this.tryReserve()) {
throw new Error("Compression worker is already busy");
}
try {
const transferableBuffer = this.normalizeCompressionBuffer(buffer);
await this.init();
const worker = this.worker;
if (!worker) {
throw new Error("Compression worker is not available");
}
if (this.activeJob) {
throw new Error("Compression worker is already busy");
}
const id = this.nextMessageId++;
const timeoutMs = this.getTimeoutMs();
return await new Promise<ArrayBuffer>((resolve, reject) => {
const timeoutHandle = this.setWorkerTimeout(() => {
if (this.destroyed) {
return;
}
if (!this.activeJob || this.activeJob.id !== id) {
return;
}
const error = new WasmTimeoutError(`WASM worker timed out after ${timeoutMs}ms`);
this.failActiveWorkerState(error, true);
}, timeoutMs);
this.activeJob = { id, timeoutHandle, resolve, reject };
try {
if (this.destroyed || this.worker !== worker) {
throw new Error("Compression worker is not available");
}
worker.postMessage({
id,
type: "compress",
format,
buffer: transferableBuffer,
settings: {
pngQuality: {
min: settings.pngQuality.min,
max: settings.pngQuality.max
},
jpegQuality: settings.jpegQuality
},
}, [transferableBuffer]);
} catch (error) {
if (this.activeJob?.id === id) {
this.clearWorkerTimeout(timeoutHandle);
this.activeJob = null;
}
reject(error instanceof Error ? error : new Error(String(error)));
}
});
} finally {
this.reserved = false;
}
}
terminate(error = new Error("Compression worker stopped")) {
if (this.workerInit) {
const init = this.workerInit;
this.workerInit = null;
this.clearWorkerTimeout(init.timeoutHandle);
init.reject(error);
}
if (this.activeJob) {
const job = this.activeJob;
this.activeJob = null;
this.clearWorkerTimeout(job.timeoutHandle);
job.reject(error);
}
this.wasmReady = false;
this.terminateWorker();
}
destroy(error: Error) {
this.destroyed = true;
this.needsRecreate = false;
this.wasmInitError = error;
this.terminate(error);
}
private createWorker() {
if (this.workerFactory) {
return this.workerFactory(this.workerSource);
}
const blob = new Blob([this.workerSource], { type: "text/javascript" });
this.objectUrl = URL.createObjectURL(blob);
return new Worker(this.objectUrl);
}
private handleWorkerMessage(message: unknown) {
if (!message || typeof message !== "object") {
this.logUnhandledWorkerMessage(message);
return;
}
const workerMessage = message as WorkerMessageEnvelope;
if ((workerMessage.type === "ready" || workerMessage.type === "init-failed") && this.workerInit?.id === workerMessage.id) {
const init = this.workerInit!;
this.workerInit = null;
this.clearWorkerTimeout(init.timeoutHandle);
if (workerMessage.type === "ready") {
this.revokeObjectUrl();
this.wasmReady = true;
this.wasmInitError = null;
init.resolve();
} else {
this.wasmReady = false;
this.wasmInitError = new Error(workerMessage.error?.message || "Worker WASM initialization failed");
this.terminateWorker();
init.reject(this.wasmInitError);
}
return;
}
if (workerMessage.type === "result" && this.activeJob?.id === workerMessage.id) {
const job = this.activeJob!;
this.activeJob = null;
this.clearWorkerTimeout(job.timeoutHandle);
if (workerMessage.ok) {
job.resolve(this.toArrayBuffer(workerMessage.output as ArrayBuffer | Uint8Array));
} else {
job.reject(new WorkerCompressionError(workerMessage.error || {}));
}
return;
}
this.logUnhandledWorkerMessage(message);
}
private logUnhandledWorkerMessage(message: unknown) {
const envelope = message && typeof message === "object" ? message as WorkerMessageEnvelope : null;
console.debug("[Local Image Compress]", "Unhandled worker message:", {
type: envelope ? envelope.type : typeof message,
id: envelope ? envelope.id : undefined,
expecting: {
init: this.workerInit?.id ?? null,
job: this.activeJob?.id ?? null
},
wasmReady: this.wasmReady,
needsRecreate: this.needsRecreate,
destroyed: this.destroyed
});
}
private handleWorkerError(event: ErrorEvent | Event | { message?: unknown }) {
const message = "message" in event && typeof event.message === "string" ? event.message : "unknown error";
const error = new Error(`Worker crashed: ${message}`);
this.failActiveWorkerState(error, true);
}
private failActiveWorkerState(error: Error, recreate: boolean) {
this.wasmReady = false;
this.wasmInitError = error;
if (this.workerInit) {
const init = this.workerInit;
this.workerInit = null;
this.clearWorkerTimeout(init.timeoutHandle);
init.reject(error);
}
if (this.activeJob) {
const job = this.activeJob;
this.activeJob = null;
this.clearWorkerTimeout(job.timeoutHandle);
job.reject(error);
}
this.terminateWorker();
if (recreate && !this.destroyed) {
this.needsRecreate = true;
this.wasmInitError = null;
this.workerInit = null;
} else {
this.needsRecreate = false;
}
}
private terminateWorker() {
try {
this.worker?.terminate();
} catch (error) {
void error;
}
this.worker = null;
this.revokeObjectUrl();
}
private revokeObjectUrl() {
if (!this.objectUrl) {
return;
}
try {
URL.revokeObjectURL(this.objectUrl);
} catch (error) {
void error;
}
this.objectUrl = null;
}
private setWorkerTimeout(callback: () => void, delay: number) {
const windowRef = getActiveWindowForApp(this.getApp());
if (windowRef) {
return windowRef.setTimeout(callback, delay);
}
if (typeof window !== "undefined") {
return window.setTimeout(callback, delay);
}
return fallbackSetTimeout(callback, delay);
}
private clearWorkerTimeout(timeoutHandle: TimerHandle | null | undefined) {
if (timeoutHandle === null || timeoutHandle === undefined) {
return;
}
const windowRef = getActiveWindowForApp(this.getApp());
if (windowRef) {
windowRef.clearTimeout(timeoutHandle as number);
return;
}
if (typeof window !== "undefined") {
window.clearTimeout(timeoutHandle as number);
return;
}
fallbackClearTimeout(timeoutHandle);
}
private cloneAsArrayBuffer(input: Uint8Array) {
const copy = new Uint8Array(input.byteLength);
copy.set(input);
return copy.buffer;
}
private normalizeCompressionBuffer(input: unknown): ArrayBuffer {
if (input instanceof ArrayBuffer) {
if (input.byteLength === 0) {
throw new TypeError("Expected a non-empty ArrayBuffer; received an empty or detached buffer");
}
return input;
}
if (ArrayBuffer.isView(input)) {
if (input.byteLength === 0) {
throw new TypeError("Expected a non-empty ArrayBuffer view; received an empty view");
}
const bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
return copy.buffer;
}
const received = input === null ? "null" : typeof input;
throw new TypeError(`Expected ArrayBuffer or ArrayBuffer view, got ${received}`);
}
private toArrayBuffer(input: ArrayBuffer | Uint8Array): ArrayBuffer {
if (input instanceof ArrayBuffer) {
return input;
}
if (input.byteOffset === 0 && input.byteLength === input.buffer.byteLength) {
return input.buffer as ArrayBuffer;
}
return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength) as ArrayBuffer;
}
}

605
styles.css Normal file
View file

@ -0,0 +1,605 @@
/* TinyPNG (Local) - Адаптивные стили плагина */
/* ========================================================================
CSS-ПЕРЕМЕННЫЕ ДЛЯ ДИНАМИЧЕСКОЙ АДАПТАЦИИ
======================================================================== */
:root {
--local-image-compress-accent: var(--interactive-accent);
--local-image-compress-accent-hover: var(--interactive-accent-hover);
--local-image-compress-text-error: var(--text-error);
--local-image-compress-text-success: var(--text-success);
--local-image-compress-text-warning: var(--text-warning);
}
/* ========================================================================
БАЗОВЫЕ СТИЛИ ДЛЯ НАСТРОЕК
======================================================================== */
.tiny-local-settings .setting-item-description ul {
margin: 0.5em 0;
padding-left: 1.5em;
}
.tiny-local-settings .tiny-local-roots-list .badge {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
background: var(--background-modifier-hover);
border: 1px solid var(--background-modifier-border);
color: var(--text-normal);
margin: 4px 6px 0 0;
cursor: pointer;
}
.tiny-local-settings .tiny-local-warning-block {
color: var(--local-image-compress-text-error);
font-weight: 600;
margin-bottom: 8px;
}
.tiny-local-settings .tiny-local-roots-list .badge:hover {
background: transparent;
border-color: var(--text-error);
color: var(--text-error);
}
.tiny-local-settings .tiny-local-roots-pill {
border: 1px solid var(--background-modifier-border);
background: var(--background-secondary);
color: var(--text-normal);
cursor: pointer;
font: inherit;
}
.tiny-local-settings .tiny-local-roots-clear {
color: var(--text-muted);
background: transparent;
}
.tiny-local-settings .tiny-local-roots-clear:hover {
color: var(--text-error);
background: transparent;
}
/* Поднастройки без разделительной линии */
.tiny-local-settings .tiny-local-subsetting.setting-item {
border-top: none;
padding-top: 4px;
}
.tiny-local-settings .setting-item-description li {
margin: 0.25em 0;
}
/* Стили для уведомлений */
.tiny-local-notice {
font-weight: 500;
color: var(--text-normal);
}
/* ========================================================================
ПРОГРЕСС-БАР И МОДАЛЬНЫЕ ОКНА ДЛЯ ПЕРЕМЕЩЕНИЯ ФАЙЛОВ
======================================================================== */
/* Прогресс-бар */
.tiny-local-move-progress-modal .tiny-local-progress-bar {
width: 100%;
height: 8px;
background: var(--background-modifier-border);
border-radius: 4px;
overflow: hidden;
margin: 10px 0;
}
.tiny-local-move-progress-modal .tiny-local-progress-fill {
height: 100%;
width: var(--local-image-compress-progress-width, 0%);
background: var(--interactive-accent);
border-radius: 4px;
transition: width 0.3s ease;
}
/* Модальное окно прогресса */
.modal-content.tiny-local-move-progress-modal {
max-width: 500px;
padding: 20px;
}
.tiny-local-move-progress-modal h2 {
margin-bottom: 15px;
color: var(--text-normal);
}
.tiny-local-move-progress-modal p {
margin: 8px 0;
color: var(--text-muted);
}
/* Модальное окно результата */
.modal-content.tiny-local-move-result-modal {
max-width: 400px;
padding: 20px;
}
.tiny-local-move-result-modal h2 {
margin-bottom: 15px;
color: var(--text-normal);
}
.tiny-local-move-result-modal p {
margin: 10px 0;
padding: 8px 12px;
border-radius: 4px;
font-weight: 500;
}
.tiny-local-success {
background: var(--background-modifier-success);
color: var(--text-success);
border-left: 3px solid var(--text-success);
}
.tiny-local-error {
background: var(--background-modifier-error);
color: var(--text-error);
border-left: 3px solid var(--text-error);
}
.tiny-local-info {
background: var(--background-modifier-hover);
color: var(--text-accent);
border-left: 3px solid var(--interactive-accent);
}
/* ========================================================================
ИНДИКАТОР ЭКОНОМИИ МЕСТА - АДАПТИВНЫЙ
======================================================================== */
.tiny-local-savings-indicator {
background: var(--background-secondary);
border: 1px solid var(--background-modifier-border);
border-radius: 6px;
margin: 15px 0;
padding: 12px;
transition: background-color 0.2s ease, border-color 0.2s ease;
}
.tiny-local-savings-indicator:hover {
background: var(--background-secondary-alt);
border-color: var(--background-modifier-border-focus);
}
.tiny-local-savings-tooltip-target {
cursor: help;
}
.tiny-local-savings-bar {
height: 20px;
display: flex;
border-radius: 4px;
overflow: hidden;
margin-top: 8px;
border: 1px solid var(--background-modifier-border);
}
/* Сэкономленное место - адаптивный цвет */
.tiny-local-savings-saved {
width: var(--local-image-compress-savings-width, 0%);
background: var(--interactive-accent);
opacity: 0.8;
background-image: repeating-linear-gradient(
45deg,
transparent,
transparent 2px,
var(--background-modifier-hover) 2px,
var(--background-modifier-hover) 4px
);
transition: width 0.3s ease;
min-width: 1px;
}
/* Текущий размер - адаптивный цвет */
.tiny-local-savings-current {
width: var(--local-image-compress-savings-width, 0%);
background: var(--background-modifier-border);
transition: width 0.3s ease;
min-width: 1px;
}
/* Резервный сегмент, когда нет данных об экономии */
.tiny-local-savings-bar .tiny-local-savings-fallback {
width: 100%;
}
.tiny-local-savings-text {
color: var(--text-normal);
font-size: 13px;
line-height: 1.4;
}
.tiny-local-savings-text strong {
color: var(--text-accent);
font-weight: 600;
}
/* ========================================================================
TOOLTIP - АДАПТИВНЫЙ
======================================================================== */
.tiny-local-savings-tooltip-wrapper {
position: absolute;
top: var(--local-image-compress-savings-tooltip-top, auto);
left: var(--local-image-compress-savings-tooltip-left, auto);
z-index: 1000;
pointer-events: none;
}
.tiny-local-savings-tooltip {
background: var(--background-primary);
border: 1px solid var(--background-modifier-border);
color: var(--text-normal);
padding: 12px 16px;
border-radius: 6px;
font-size: 12px;
line-height: 1.5;
white-space: pre-line;
box-shadow: var(--shadow-s);
min-width: 320px;
max-width: 400px;
position: relative;
z-index: 1000;
}
.tiny-local-savings-tooltip::before {
content: '';
position: absolute;
top: -6px;
left: 20px;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid var(--background-primary);
}
.tiny-local-savings-tooltip::after {
content: '';
position: absolute;
top: -7px;
left: 20px;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid var(--background-modifier-border);
}
.tiny-local-savings-tooltip strong {
color: var(--text-accent);
font-weight: 600;
}
.tiny-local-savings-tooltip .tooltip-header {
color: var(--text-accent);
font-weight: 600;
font-size: 13px;
margin-bottom: 8px;
border-bottom: 1px solid var(--background-modifier-border);
padding-bottom: 6px;
}
.tiny-local-savings-tooltip .tooltip-item {
margin: 4px 0;
display: flex;
justify-content: flex-start;
gap: 8px;
}
.tiny-local-savings-tooltip .tooltip-label {
color: var(--text-normal);
font-weight: 700;
}
.tiny-local-savings-tooltip .tooltip-value {
color: var(--text-muted);
font-weight: 500;
}
/* ========================================================================
СТАТУС-БАР - АДАПТИВНЫЙ
======================================================================== */
.tiny-local-compressing {
color: var(--interactive-accent);
animation: tiny-local-pulse 2s infinite;
}
.tiny-local-status-attention {
color: var(--text-warning);
font-weight: 600;
}
@keyframes tiny-local-pulse {
0% { opacity: 1; }
50% { opacity: 0.6; }
100% { opacity: 1; }
}
/* ========================================================================
ПРОГРЕСС-БАР - АДАПТИВНЫЙ
======================================================================== */
.tiny-local-progress-container {
width: 100%;
height: 20px;
background-color: var(--background-modifier-border);
border-radius: 10px;
margin: 10px 0;
overflow: hidden;
}
.tiny-local-progress-container .tiny-local-progress-bar {
width: 100%;
height: 100%;
position: relative;
}
.tiny-local-progress-container .tiny-local-progress-fill {
height: 100%;
width: var(--local-image-compress-progress-width, 0%);
background-color: var(--interactive-accent);
transition: width 0.3s ease;
width: 0%;
}
.tiny-local-progress-title {
font-size: 16px;
font-weight: bold;
margin-bottom: 10px;
color: var(--text-normal);
}
.tiny-local-progress-status {
font-size: 14px;
color: var(--text-muted);
margin-bottom: 10px;
}
.tiny-local-progress-actions {
display: flex;
justify-content: flex-end;
gap: var(--size-2-2);
margin-top: 12px;
}
.tiny-local-progress-cancel {
min-width: 96px;
}
/* ========================================================================
МЕНЮ СТАТУС-БАРА - АДАПТИВНОЕ
======================================================================== */
.tiny-local-status-menu {
position: fixed;
left: var(--local-image-compress-status-menu-left, 0);
top: var(--local-image-compress-status-menu-top, 0);
transform: var(--local-image-compress-status-menu-transform, none);
z-index: 1000;
background: var(--background-primary);
border: 1px solid var(--background-modifier-border);
border-radius: 6px;
box-shadow: var(--shadow-s);
padding: 4px 0;
min-width: 220px;
max-width: min(360px, calc(100vw - 20px));
max-height: calc(100vh - 20px);
overflow-x: hidden;
overflow-y: auto;
font-size: 14px;
color: var(--text-normal);
}
.tiny-local-status-menu-header {
padding: 6px 12px;
font-size: 12px;
color: var(--text-muted);
border-bottom: 1px solid var(--background-modifier-border);
font-weight: 500;
}
.tiny-local-status-menu .tiny-local-status-menu-item {
display: block;
width: 100%;
box-sizing: border-box;
border: 0;
border-radius: 0;
box-shadow: none;
background-color: transparent;
color: var(--text-normal);
font: inherit;
text-align: left;
padding: 6px 12px;
margin: 0;
min-height: 32px;
cursor: pointer;
user-select: none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
transition: background-color 0.2s ease;
}
.tiny-local-status-menu .tiny-local-status-menu-item:hover,
.tiny-local-status-menu .tiny-local-status-menu-item:focus {
background-color: var(--background-modifier-hover);
}
.tiny-local-status-trigger:focus-visible,
.tiny-local-status-menu .tiny-local-status-menu-item:focus,
.tiny-local-status-menu .tiny-local-status-menu-item:focus-visible,
.tiny-local-savings-tooltip-target:focus-visible,
.tiny-local-folder-select-control:focus-visible,
.tiny-local-progress-cancel:focus-visible,
.tiny-local-move-result-modal button:focus-visible,
.tiny-local-backup-list button:focus-visible {
outline: 2px solid var(--interactive-accent);
outline-offset: 2px;
}
/* ========================================================================
ПОДДЕРЖКА ПОПУЛЯРНЫХ КАСТОМНЫХ ТЕМ
======================================================================== */
/* Minimal Theme */
.theme-minimal .tiny-local-savings-indicator {
border-radius: 8px;
box-shadow: var(--shadow-s);
}
.theme-minimal .tiny-local-savings-bar {
border-radius: 6px;
}
/* AnuPpuccin Theme */
.theme-anuppuccin .tiny-local-savings-saved {
background: var(--ctp-mocha-blue, var(--interactive-accent));
}
/* Dracula Theme */
.theme-dracula .tiny-local-savings-saved {
background: var(--dracula-purple, var(--interactive-accent));
}
/* Catppuccin Theme */
.theme-catppuccin .tiny-local-savings-saved {
background: var(--ctp-blue, var(--interactive-accent));
}
/* Tokyo Night Theme */
.theme-tokyo-night .tiny-local-savings-saved {
background: var(--tokyo-night-blue, var(--interactive-accent));
}
/* One Dark Theme */
.theme-one-dark .tiny-local-savings-saved {
background: var(--one-dark-blue, var(--interactive-accent));
}
/* ========================================================================
АДАПТАЦИЯ ДЛЯ УЗКИХ ОКОН
======================================================================== */
@media (max-width: 768px) {
.tiny-local-savings-indicator {
margin: 10px 0;
padding: 10px;
}
.tiny-local-savings-tooltip {
min-width: 280px;
max-width: 90vw;
font-size: 11px;
padding: 10px 12px;
}
}
/* ========================================================================
АНИМАЦИИ И ПЕРЕХОДЫ
======================================================================== */
.tiny-local-savings-indicator,
.tiny-local-savings-bar {
transition: background-color 0.2s ease, border-color 0.2s ease;
}
/* Плавное появление tooltip */
.tiny-local-savings-tooltip {
animation: tiny-local-fade-in 0.2s ease;
}
@keyframes tiny-local-fade-in {
from {
opacity: 0;
transform: translateY(-5px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* ========================================================================
ДОПОЛНИТЕЛЬНЫЕ КЛАССЫ ДЛЯ JAVASCRIPT
======================================================================== */
/* Состояния прогресс-бара */
.tiny-local-progress-completed {
background-color: var(--local-image-compress-text-success);
}
.tiny-local-progress-error {
background-color: var(--local-image-compress-text-error);
}
.tiny-local-progress-cancelled {
background-color: var(--text-warning);
}
/* Список бэкапов */
.tiny-local-backup-list {
max-height: 300px;
overflow-y: auto;
border: 1px solid var(--background-modifier-border);
padding: 10px;
border-radius: 4px;
font-family: monospace;
font-size: 12px;
background: var(--background-secondary);
}
.tiny-local-folder-select-control {
width: 100%;
padding: 8px;
margin: 10px 0;
}
/* ========================================================================
ДОСТУПНОСТЬ (ACCESSIBILITY)
======================================================================== */
/* Улучшенный фокус для клавиатурной навигации */
.tiny-local-settings .setting-item-control button:focus-visible,
.tiny-local-settings .tiny-local-roots-pill:focus-visible {
outline: 2px solid var(--interactive-accent);
outline-offset: 2px;
}
/* Высокий контраст для слабовидящих */
@media (prefers-contrast: high) {
.tiny-local-savings-indicator {
border-width: 2px;
}
.tiny-local-savings-text strong {
font-weight: 700;
}
}
/* Уменьшенное движение для пользователей с вестибулярными нарушениями */
@media (prefers-reduced-motion: reduce) {
.tiny-local-savings-indicator,
.tiny-local-savings-bar,
.tiny-local-savings-saved,
.tiny-local-savings-current,
.tiny-local-status-menu,
.tiny-local-savings-tooltip {
transition: none;
animation: none;
}
.tiny-local-compressing {
animation: none;
}
}

23
tsconfig.json Normal file
View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"lib": ["ES2020", "DOM"],
"types": ["node", "obsidian"],
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"noPropertyAccessFromIndexSignature": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": true,
"useUnknownInCatchVariables": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true
},
"include": ["src-ts/**/*.ts"]
}

3
versions.json Normal file
View file

@ -0,0 +1,3 @@
{
"1.0.0": "1.4.0"
}

30
wasm-hashes.json Normal file
View file

@ -0,0 +1,30 @@
{
"_comment": "Known-good SHA-256 of every WASM codec inlined into the bundle. Regenerate via `npm run validate:wasm -- --write` only after verifying a deliberate dependency change.",
"generatedAt": "2026-05-29T11:17:49.112Z",
"wasm": {
"jpeg-decode": {
"file": "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm",
"version": "1.6.0",
"bytes": 166470,
"sha256": "a7c4b12169817e779ff4af137981393ae924944e167ad1bd95747c9199162d3e"
},
"jpeg-encode": {
"file": "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm",
"version": "1.6.0",
"bytes": 251524,
"sha256": "24d4177f1c4963e2058b107189249651c61fdef125570e79b1dfb63c8bb49326"
},
"png": {
"file": "@jsquash/png/codec/pkg/squoosh_png_bg.wasm",
"version": "3.1.1",
"bytes": 181088,
"sha256": "263d6e658808a74b72a1a99c5cc1d619237e70c150db6e41d5d84d3d117ab9be"
},
"imagequant": {
"file": "imagequant/imagequant_bg.wasm",
"version": "0.1.2",
"bytes": 346579,
"sha256": "29aff33dc068eeb7b49bdef84cbcaea7f7e4edee49f2b15de0e299d27abb3193"
}
}
}