Runway 1.0.1
This commit is contained in:
1 parent
dcf819146b
commit
ce217fc952
259 files changed
+22226
-206
No files matched your search
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [2.1.0] — 2026-10-21
|
||||
|
||||
First public release of `blog`: blog entries as first-class virtual pages through the kernel's `ContentSource`
|
||||
seam — each with its own URL (under a configurable prefix, or a custom path), rendered in the site's own chrome, in
|
||||
every language the site serves, and listed in the sitemap and `llms.txt`. Requires SPI `1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for
|
||||
plugins (`LICENSE`, `LICENSE-EXCEPTION`).
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,44 @@
|
||||
Runway — additional permission for plugins
|
||||
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
|
||||
|
||||
Copyright (C) 2026 Quest ICT SAS de CV
|
||||
|
||||
Runway is free software: you can redistribute it and/or modify it under the terms of the
|
||||
GNU Affero General Public License as published by the Free Software Foundation, version 3
|
||||
(the file LICENSE), with the additional permission below. Runway 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 Affero General Public
|
||||
License for more details.
|
||||
|
||||
1. Definitions
|
||||
|
||||
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
|
||||
|
||||
"Published SPI" means the public classes and interfaces of the runway-spi artifact
|
||||
(the package mx.quest.runway.spi and its subpackages), together with the public classes
|
||||
and interfaces of any package named "spi" that a part of Runway publishes for other
|
||||
plugins to use (for example mx.quest.search.spi).
|
||||
|
||||
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
|
||||
Runway only through the Published SPI, and that is not based on any part of Runway other
|
||||
than the Published SPI.
|
||||
|
||||
2. Permission
|
||||
|
||||
As an additional permission, the copyright holder gives you permission to combine Runway
|
||||
with Plugins, and to convey and run the resulting combination, without the terms of the
|
||||
GNU Affero General Public License applying to those Plugins. You may license, convey and
|
||||
run your Plugins under terms of your choice, provided that you continue to meet the terms
|
||||
of the GNU Affero General Public License for Runway itself, including offering the
|
||||
Corresponding Source of Runway, and of any modification you make to it, as that license
|
||||
requires.
|
||||
|
||||
3. Testing
|
||||
|
||||
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
|
||||
not by itself make the Plugin subject to the GNU Affero General Public License.
|
||||
|
||||
4. Modified versions
|
||||
|
||||
If you modify Runway, you may extend this additional permission to your version, but you
|
||||
are not obliged to do so. If you do not wish to, delete this file from your version.
|
||||
@@ -0,0 +1,117 @@
|
||||
# blog — a blog for Runway sites
|
||||
|
||||
Blog entries as **first-class virtual pages**, built on the host's `ContentSource` seam: each entry has its own URL under a configurable prefix (default `/blog`) — or a per-entry
|
||||
**custom absolute path** — renders inside the **tenant's own master chrome** through this plugin's shipped
|
||||
entry templates, follows the site's full language dispatch (per-language slugs, `?lang=` switcher, canonical
|
||||
redirects), appears in **sitemap.xml / llms.txt** with `hreflang` + `<lastmod>`, and is linkable from any
|
||||
tenant page as `${urls['blog:<id>']}`. All of that is host-provided; this plugin only stores entries and
|
||||
answers the source contract.
|
||||
|
||||
**The plugin links only the Runway SPI** (service tier, SPI `1.0.0`) — no kernel-internal class. The full design
|
||||
and reference is [`docs/BLOG-PLUGIN.md`](docs/BLOG-PLUGIN.md); the release notes are in
|
||||
[`CHANGELOG.md`](CHANGELOG.md); `scripts/verify-against-host.sh` checks it end to end against a packaged kernel.
|
||||
|
||||
- **Storage** — entries live in the *tenant's* folder: `sites/<siteId>/plugins/blog/entries/<id>/entry.yml`
|
||||
(metadata) + `body-<lang>.md` (one Markdown body per language), through the kernel's `PluginSiteFiles` (confined
|
||||
to the plugin's subtree). Tenant backups carry the whole blog
|
||||
automatically; the metadata/body file split keeps enumeration body-free (the source contract).
|
||||
- **Authoring** — the tenant console gains a **Blog** screen (`/__admin/blog`, gated by the grantable
|
||||
`blog|manage` control point): list, create, edit (per-language title/description/slug/body), publish/
|
||||
unpublish, delete — each a CSRF-checked `POST`. Every mutation is announced with `ContentChanges`, so routing,
|
||||
sitemap and search follow on the next request; the editor warns when a published **page owns an entry's
|
||||
address** (the page wins — the platform's precedence rule), and refuses a custom path the kernel would not serve.
|
||||
- **Settings** (per tenant, applied immediately): `enabled`, `prefix`, `template`
|
||||
(`entry-classic` — title, date line, back link — or `entry-minimal` — title + body only).
|
||||
- **Search** — entries declare the kernel's `content.indexable-text` capability and serve their
|
||||
body through it (rendered Markdown→HTML, the same transform the page render uses, so the engines' HTML
|
||||
stripper yields clean prose — raw Markdown syntax would leak into index terms and snippets). A search engine
|
||||
that indexes the content catalog (the `search` and `search-lucene` plugins) finds entries by body text,
|
||||
title and description — first-class search citizens, no blog-specific code in any engine.
|
||||
- **Markdown** — rendered with [commonmark-java] (bundled in this plugin's `lib/`, private to this plugin).
|
||||
Entry Markdown is operator-authored trusted content: raw HTML passes through, exactly as a page author may
|
||||
write markup.
|
||||
|
||||
## Bylines and publication dates
|
||||
|
||||
Each entry carries its own **author** and **publication date**, and both travel across the SPI as that
|
||||
entry's own values — so the discoverability plugin emits a truthful per-post `author` and `datePublished` in
|
||||
`Article`/`BlogPosting` structured data, and the entry template renders a byline.
|
||||
|
||||
Without them, authorship and dates could only come from the per-site `content.schema` block, which matches by
|
||||
path prefix — one `/blog/*` entry covering *every* post. The only honest options would be to emit nothing, or to
|
||||
assert a single author and date identically across all posts: false of nearly every page carrying it, and
|
||||
exactly the kind of untrue markup structured-data policy prohibits.
|
||||
|
||||
Notes:
|
||||
|
||||
- Both fields are **optional**. An unattributed entry renders no byline and asserts no author — absence is a
|
||||
normal state, never a placeholder.
|
||||
- The byline element appears when the entry has an author **or** a date, and each part renders independently,
|
||||
so an entry with one but not the other is handled correctly.
|
||||
- `author` is a free-text display name, matching the kernel's page-level author. A real identity model is a
|
||||
larger design; blocking bylines on it would leave content unattributable meanwhile.
|
||||
|
||||
## Publication dates
|
||||
|
||||
Each entry's `publishedOn` date is carried across the SPI as that entry's own `publishedAt`, so the
|
||||
discoverability plugin can emit a **truthful per-post `datePublished`** in `Article`/`BlogPosting`
|
||||
structured data.
|
||||
|
||||
Notes:
|
||||
|
||||
- `publishedOn` is free-form display text. A value that is not an ISO `yyyy-MM-dd` date yields **no**
|
||||
`datePublished` rather than a guess — asserting a wrong date is worse than asserting none, because a
|
||||
consumer is told to trust it.
|
||||
- Dates are interpreted at **midnight UTC**, matching how the kernel's page editor parses its own date
|
||||
field, so a blog entry and a page dated the same day produce the same instant.
|
||||
|
||||
## Requirements
|
||||
|
||||
**Needs Runway 1.0.0 or later** (SPI `1.0.0`). The descriptor declares `requiresSpi: ">=1.0.0"`, so an older
|
||||
kernel blocks this plugin at startup with a reason and still boots its other plugins. Upgrade the kernel first, then
|
||||
the plugin.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
mvn package
|
||||
```
|
||||
|
||||
`target/blog/` (the install-ready folder) and `target/runway-plugin-blog-<version>.zip` (the UI-upload
|
||||
archive), where `<version>` is the `version:` in `plugin.yml`.
|
||||
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
## Install (either path, then restart the host)
|
||||
|
||||
```bash
|
||||
# 1. cp -r target/blog <external>/plugins/
|
||||
# 2. app console → /__app/plugins → install → upload runway-plugin-blog-<version>.zip
|
||||
```
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
mvn verify # 67 unit tests, incl. the no-host-linkage bytecode scan
|
||||
JAVA_HOME=… HOST_JAR=…/runway-app-<ver>-exec.jar VERIFY_TMPDIR=… scripts/verify-against-host.sh # 56 end-to-end checks
|
||||
```
|
||||
|
||||
## Try it
|
||||
|
||||
1. Console → **Blog** → **New entry**: id `hello-world`, tick a language, type a title and a Markdown body,
|
||||
tick **Published**, Save.
|
||||
2. Visit `https://<site>/blog/hello-world` — the entry wears the site's chrome.
|
||||
3. `GET /sitemap.xml` — the entry is listed with `hreflang` alternates and `<lastmod>`.
|
||||
4. Give a **page** the same path — the page serves, the blog editor and the Pages screen both warn.
|
||||
|
||||
_Java package `mx.quest.blog` · plugin id `blog` · built against `runway-spi` 1.0.0 · declared SPI floor
|
||||
`>=1.0.0`._
|
||||
|
||||
[commonmark-java]: https://github.com/commonmark/commonmark-java
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`),
|
||||
copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI may carry any
|
||||
license.
|
||||
@@ -0,0 +1,202 @@
|
||||
# Runway Blog plugin — design & reference
|
||||
|
||||
> The plugins' reference for **routable content that is not a kernel page**: a plugin `ContentSource` whose
|
||||
> items the kernel routes, renders in the tenant's own master chrome, lists in sitemap.xml / llms.txt and hands to
|
||||
> search — using **only the Runway SPI** (SPI 1.0.0). Grounded in the Runway kernel as built.
|
||||
|
||||
## 1. What it does
|
||||
|
||||
- **Entries as virtual pages.** Each entry is served by the kernel at `<prefix>/<slug>` (default prefix `/blog`),
|
||||
or at a per-entry **custom absolute path** (`/announcing-v2`) for the default language, with **per-language
|
||||
slugs** (`/es/blog/hola-mundo`). The kernel does the routing (real pages always win first), the locale ladder
|
||||
(`?lang=`, cookie, `Accept-Language`, canonical redirects), the `<head>` (title, description, `hreflang`
|
||||
alternates, canonical), the `ETag`/`304`, and wraps the body in the **site's own master** (`_master`).
|
||||
- **Body templates** shipped by the plugin: `entry-classic` (title, a meta line with the date and the byline, the
|
||||
body, a back link) and `entry-minimal` (title and body). The operator picks one per site.
|
||||
- **Discoverability and search, through the kernel catalog.** Published entries are part of the site's content
|
||||
catalog, so sitemap.xml (with `hreflang` and `<lastmod>`), llms.txt and the URL map (`${urls['blog:<id>']}`, usable
|
||||
in any page) list them, and a search engine that indexes the catalog finds an entry by the words of its body
|
||||
(`content.indexable-text`: the body rendered to HTML, the same transform the page uses). The blog has no
|
||||
blog-specific code in any of those plugins.
|
||||
- **Bylines and dates.** Each entry carries its own `author` and `publishedOn`; both cross the SPI as that entry's
|
||||
own values (`ContentRef.author`, `ContentRef.publishedAt`, midnight UTC; a non-ISO date yields no date), so
|
||||
structured data can attribute and date every post truthfully. Both are optional and render independently.
|
||||
- **Console** (`/__admin/blog`, tenant console, gated by `blog|manage`): list, create, edit (per-language title,
|
||||
description, slug, Markdown body; date, author, custom path, published), publish/unpublish, delete. The editor
|
||||
warns when a **published page owns an entry's URL** in some language (the page wins, so the entry is unreachable
|
||||
there). Per-site settings (`enabled`, `prefix`, `template`) are edited on the kernel's generic settings form,
|
||||
gated by `blog|settings`.
|
||||
- **Markdown** is rendered with [commonmark-java], bundled in this plugin's `lib/` and private to it. Entry
|
||||
Markdown is operator-authored, trusted content: raw HTML passes through, exactly as a page author may write
|
||||
markup.
|
||||
|
||||
## 2. Storage (the site's folder)
|
||||
|
||||
```
|
||||
sites/<siteId>/plugins/blog/
|
||||
└── entries/<entryId>/
|
||||
├── entry.yml # metadata (no id: the folder name is the id)
|
||||
├── body-en.md # one Markdown body per language
|
||||
└── body-es.md
|
||||
sites/<siteId>/plugins/blog.yml # the per-site settings (the kernel's settings store)
|
||||
```
|
||||
|
||||
- Read and written through **`PluginSiteFiles`**, which confines every path to `plugins/blog/` (symbolic links
|
||||
included) and writes atomically (temporary file + rename), so a public reader never sees a torn `entry.yml`.
|
||||
- `entry.yml` goes through the plugin's own **lenient** Jackson 3 `YAMLMapper`, so **an entry written by an earlier
|
||||
release or by hand loads unchanged** (a missing `published:` defaults, an unknown key is ignored) and is **written
|
||||
back byte for byte** (`BlogStoreTest` proves both with the fixture entries under `src/test/resources/fixtures`,
|
||||
written by blog 1.3.1 and including an entry with no `author`).
|
||||
- **`updatedAt`** is the newest modification time of the entry's files (`FileEntry.lastModified`), so a console
|
||||
edit of only a body moves the `ETag` and `<lastmod>` with no explicit bump. It is read when the source lists the
|
||||
entries, and that list is cached until a change is announced (§3) — so a file edited **on disk** does not move
|
||||
them until then.
|
||||
- **Metadata/body split**: listing reads only `entry.yml` files; a body is read only to render or index it — the
|
||||
`ContentSource` rule that keeps `/sitemap.xml` from reading the whole corpus.
|
||||
- Ids (`[a-z0-9-]`, ≤ 100) and language codes (`[a-z]{2,8}`) are validated before any path is formed. One
|
||||
unreadable `entry.yml` is skipped with a WARN; it never blanks the blog.
|
||||
- **Backups**: the entries live in the site's folder, so full backups carry them with no `BackupParticipant`.
|
||||
They are **published content, not personal data**, so nothing is declared under `siteData.personal` and a
|
||||
transfer copy carries them too.
|
||||
|
||||
## 3. Freshness: who drops what, and when
|
||||
|
||||
| Change | Announced by | What the kernel does | What the blog does |
|
||||
|---|---|---|---|
|
||||
| An entry is created, edited, (un)published or deleted | the console: `ContentChanges.changed(site, "blog", id)` after the write | evicts routing, the URL map and the catalog; relays to cluster peers; delivers a `CONTENT` `CatalogChange` | `BlogContentSource.onCatalogChanged` (SOURCE phase) drops the site's URL index and enumerated refs |
|
||||
| The blog's settings are saved | the kernel's settings form | evicts the settings cache; delivers `SettingsChange` | `onSettingsChanged` drops the index (a prefix change re-keys every URL) |
|
||||
| A site lifecycle event (incl. a backup **restore**) | the kernel | evicts its caches | `onSiteLifecycle` drops the index (the files were replaced wholesale) |
|
||||
|
||||
The source listens in the **`SOURCE` phase**: the kernel delivers every SOURCE listener first, evicts the catalog
|
||||
once more, and only then lets consumers (sitemap, search) re-read — so none of them rebuilds from the blog's stale
|
||||
index. A change replayed from a cluster peer arrives with `local = false` and drops this node's index the same way.
|
||||
A file edited by hand **on disk** announces nothing, and the blog's index and listing have **no** time-to-live:
|
||||
|
||||
- a **new** entry folder, an `entry.yml` change (title, slug, path, published) or a deleted entry takes effect only
|
||||
after the next console save of any entry, a save of the blog's settings, or a site lifecycle event — a **site
|
||||
reload** (`POST /__reload/site/<id>`, Runway Administration §12.2) is the deliberate one;
|
||||
- an edited **`body-<lang>.md`** is served at once (the body is read on every full render), but **under the old
|
||||
`ETag`** and with the old `<lastmod>`, and search keeps the old text: a browser or CDN holding the page
|
||||
revalidates to `304` and keeps the old body, until one of the events above. **After editing entry files on
|
||||
disk, reload the site.** (Measured against a packaged kernel: body changed on disk → `200` with the new body and the
|
||||
same `ETag`, conditional request → `304`; after the reload → a new `ETag`.)
|
||||
|
||||
**Result, for site managers:** an entry saved in the console serves at once, and is in sitemap.xml and search on
|
||||
the next request; an unpublished entry is a 404 at once and leaves both (the verify script checks each of these).
|
||||
|
||||
## 4. The body-template contract
|
||||
|
||||
The templates read `${master}` and `${content.*}`. The SPI documents that render model on `ContentSource` /
|
||||
`ContentRef.bodyTemplate` as a **contract**: a body template renders with
|
||||
exactly
|
||||
|
||||
- `master` — the site master to wrap (`th:replace="~{${master} :: …}"`);
|
||||
- `content` — `id`, `sourceKey`, `title`, `description` (in the rendered locale), `bodyHtml`, `attributes` (from
|
||||
`body()`), `updatedAt`;
|
||||
- `locale`; and `urls` (link targets: `${urls['index']}`, `${urls['blog:<id>']}`).
|
||||
|
||||
Nothing else is promised. The shipped templates use only these;
|
||||
**`BlogEntryTemplateContractTest` holds them to it**: statically (every `${…}` starts from one of the four
|
||||
variables, every `content.` key is a listed one, no bean is reached, every `#{…}` key is in the plugin's bundle) and
|
||||
by rendering them with Thymeleaf over a model built exactly to the contract, with no kernel class. The attributes
|
||||
the blog puts in `body()` are its own: `publishedOn` and `author`, each present only when set.
|
||||
|
||||
## 5. The console screen
|
||||
|
||||
`BlogAdminController` carries **`@ConsoleScreen`**: the kernel's own advice fills the operator shell's model
|
||||
(topbar, menus incl. this plugin's entry, language switcher, footer). Handlers return `ConsoleScreen.LAYOUT_VIEW` with
|
||||
`CONTENT_TEMPLATE` set to `__plugin__/blog/admin-list|admin-edit` and `PAGE_TITLE_KEY`.
|
||||
|
||||
- **Tenancy** is always the bound one: `RequestContext.site()`; empty (the application console) → `400`.
|
||||
- **Every handler** is `@PreAuthorize("@authz.may('blog|manage')")` (`AccessCheck`, bean `authz`).
|
||||
- **Every state change is a `POST`** (create, update, publish toggle, delete) checked by the console chain's CSRF
|
||||
filter; each form carries `${_csrf}`. The three `GET`s only render. A test asserts this shape.
|
||||
- **Validation before writing** — what the kernel's fail-closed re-filter would otherwise drop silently: a slug
|
||||
must match the slug grammar; a custom path must be absolute, free of `|` and `:`, and
|
||||
**`ContentCatalogView.servablePath`** (safe, not reserved, not an endpoint route such as `/sitemap.xml`).
|
||||
- **The reverse advisory** asks `ContentCatalogView.pageAt(site, path, locale)` for each language's real URL.
|
||||
- Console words come from `Messages.console` (the operator's UI language) and the plugin's bundle. The templates
|
||||
read only the controller's model plus `_csrf`, and only this plugin's message keys (the pretitle uses
|
||||
`blog.admin.pretitle`, not a kernel key) — `BlogAdminTemplatesRenderTest` checks both.
|
||||
|
||||
## 6. Settings
|
||||
|
||||
| Key | Type | Default | Notes |
|
||||
|---|---|---|---|
|
||||
| `enabled` | boolean | `true` | Off: nothing serves or lists; entries are kept. |
|
||||
| `prefix` | string | `/blog` | Normalized (leading `/`, no trailing `/`); `/` puts entries at the top level. A prefix under which the kernel would not serve an entry (`/app`, `/__x`, `/actuator`, `|`, `..` — checked with `servablePath` on a child path) falls back to `/blog`. |
|
||||
| `template` | enum | `entry-classic` | `entry-classic` or `entry-minimal`; anything else reads as classic. |
|
||||
|
||||
Read through **`PluginSettings.site(siteId)`** (stored value > descriptor default > code fallback; the code
|
||||
fallbacks equal the descriptor defaults, which a test asserts).
|
||||
|
||||
## 7. Inventory
|
||||
|
||||
| Piece | Type | Role |
|
||||
|---|---|---|
|
||||
| `BlogConfig` | `mainClass` `@Configuration` | wires the three beans from SPI services; bean names `blogStore`, `blogContentSource`, `blogAdminController` |
|
||||
| `BlogStore` | over `PluginSiteFiles` | `entries/<id>/entry.yml` + `body-<lang>.md` |
|
||||
| `BlogEntry` | record | one entry's metadata (the `entry.yml` document) |
|
||||
| `BlogSettings` | record | the effective per-site settings (`PluginSettings` + `servablePath`) |
|
||||
| `BlogContentSource` | `ContentSource` (`blog`) + `SiteEventListener` (SOURCE) | enumerate / resolve (O(1) index) / body / indexableText; index invalidation |
|
||||
| `BlogAdminController` | `@Controller` `@ConsoleScreen` | the authoring screens |
|
||||
| `templates/` | decoupled Thymeleaf | `entry-classic`, `entry-minimal`, `admin-list`, `admin-edit` |
|
||||
| `i18n/` | EN / ES | public labels + console |
|
||||
| `lib/commonmark-*.jar` | bundled | Markdown |
|
||||
|
||||
## 8. What it links (SPI 1.0.0)
|
||||
|
||||
`pom.xml` depends on `runway-spi` only (`runway-spi-testkit` and Thymeleaf for tests; Spring, Spring Security and
|
||||
Jackson 3 YAML as **provided** platform libraries); **`runway-app` is not a dependency in any scope**, and
|
||||
`BlogConfigTest` scans the compiled classes' constant pools for any `mx.quest.runway` reference outside
|
||||
`mx.quest.runway.spi`.
|
||||
|
||||
The SPI services it uses: `PluginSiteFiles` (with the plugin's own `YAMLMapper`), `PluginSettings`,
|
||||
`ContentCatalogView` (`servablePath`, `pageAt`), `ContentChanges`, `SiteEventListener` (SOURCE phase),
|
||||
`RequestContext` (`SiteView`), `Messages.console` and `@ConsoleScreen`.
|
||||
|
||||
`requiresSpi: ">=1.0.0"`: a kernel with an older SPI blocks the plugin before wiring, with a reason.
|
||||
|
||||
## 9. Verify
|
||||
|
||||
`scripts/verify-against-host.sh` (honours `JAVA_HOME` (required), `MVN`, `HOST_TARGET`, `HOST_JAR`, `VERIFY_TMPDIR`,
|
||||
`VERIFY_LOG_DIR`, `COMPANIONS`; never runs
|
||||
`mvn install`, never needs `--keep`) boots the **packaged** host in ACTIVE mode with the wizard's default site made
|
||||
bilingual (EN default, ES), the **1.3.1 fixture entries** copied into it, and — built offline from copies of the
|
||||
sibling folders, skipped if they cannot be built — the `discoverability` and `search` plugins. It checks:
|
||||
|
||||
- the plugin loads (registered, 0 blocked) with **zero** host-linkage and bean-name/surface findings (the kernel
|
||||
logs "linkage scan: …" and blocks a plugin that links host internals; a surface problem names the bean) and no
|
||||
WARN or ERROR about it, and the application console's plugins screen shows it Loaded with no health note (this check
|
||||
has no positive control since every companion became SPI-only; one needs a deliberately host-linked fixture jar);
|
||||
- the 1.3.1 entries serve unchanged: default URL, localized slug in Spanish, custom path, the byline and date, the
|
||||
entry without an author (date, no byline), the draft a 404, an `ETag` that revalidates `304`, and a page's
|
||||
`${urls['blog:hello-world']}`;
|
||||
- sitemap.xml and llms.txt list the published entries and not the draft; search finds an entry by a body word;
|
||||
- the console renders inside the shell, is gated for anonymous visitors, and every mutation is a CSRF-checked POST
|
||||
(no token → `403`, nothing written; a `GET` on a mutation path changes nothing);
|
||||
- create → serves at once, in sitemap.xml and search on the next request; edit the body → search follows;
|
||||
unpublish → `404` and gone from both; a reserved custom path is refused at save; a prefix change through the
|
||||
settings form re-keys the URLs at once (and a reserved prefix falls back to `/blog`); delete removes the folder;
|
||||
- a full backup and a transfer copy both carry the entries.
|
||||
|
||||
Unit tests (67) run on the testkit's fakes with no kernel class: the store (`BlogStoreTest`, incl. the 1.3.1
|
||||
fixture read in place and written back byte for byte, confinement through a planted symbolic link), the source and
|
||||
its listener (`BlogContentSourceTest`, driven by `EventDispatch` in the kernel's order), the controller
|
||||
(`BlogAdminControllerTest`: parsing, validation, announcements, advisory, tenancy, the screen's POST-only shape),
|
||||
the console templates (`BlogAdminTemplatesRenderTest`), the body-template contract
|
||||
(`BlogEntryTemplateContractTest`), and the plugin's contract with the host (`BlogConfigTest`: wiring, bean names,
|
||||
descriptor, EN/ES parity, the constant-pool scan).
|
||||
|
||||
## 10. Not covered (honest gaps)
|
||||
|
||||
- **No listing page.** There is no `/blog` index of entries; link entries from a site page with
|
||||
`${urls['blog:<id>']}`. A listing would be a widget or a virtual page — a feature for a later release.
|
||||
- **No per-entry `noindex` or canonical override**, no categories or tags, no RSS/Atom feed.
|
||||
- **`author` is free text** (a display name), not an account.
|
||||
- **Concurrent edits of one entry**: the last save wins (each file write is atomic; there is no merge).
|
||||
- **A file edited on disk** is not picked up until something announces a change (any console save, a settings
|
||||
save, a site reload); an edited body is served at once but under the old `ETag` until then (§3). Reload the site
|
||||
after editing entry files by hand.
|
||||
|
||||
[commonmark-java]: https://github.com/commonmark/commonmark-java
|
||||
@@ -0,0 +1,71 @@
|
||||
# Blog plugin — appended LAST to each site's bundle (add-only: a site defining the same key wins) and to the
|
||||
# operator console bundle. Public-side keys (the entry templates) + the console screens.
|
||||
|
||||
# Public entry templates
|
||||
blog.publishedOn=Published on
|
||||
blog.by=By
|
||||
blog.back=Back to the site
|
||||
|
||||
# Console — permissions / settings / menu labels (referenced from plugin.yml)
|
||||
blog.perm.settings=Configure the blog
|
||||
blog.perm.manage=Manage blog entries
|
||||
blog.settings.enabled=Blog enabled
|
||||
blog.settings.prefix=URL prefix
|
||||
blog.settings.template=Entry template
|
||||
blog.menu=Blog
|
||||
|
||||
# Console — list screen
|
||||
blog.admin.pretitle=Site
|
||||
blog.admin.title=Blog
|
||||
blog.admin.heading=Blog
|
||||
blog.admin.new=New entry
|
||||
blog.admin.new.tip=Create a new blog entry (it starts unpublished).
|
||||
blog.admin.disabled=The blog is disabled for this site (see the plugin's settings) — entries are kept but none serves.
|
||||
blog.admin.col.entry=Entry
|
||||
blog.admin.col.path=Path
|
||||
blog.admin.col.langs=Languages
|
||||
blog.admin.col.date=Date
|
||||
blog.admin.col.status=Status
|
||||
blog.admin.col.actions=Actions
|
||||
blog.admin.empty=No entries yet.
|
||||
blog.admin.published=Published
|
||||
blog.admin.draft=Draft
|
||||
blog.admin.edit=Edit
|
||||
blog.admin.publish=Publish
|
||||
blog.admin.unpublish=Unpublish
|
||||
blog.admin.delete=Delete
|
||||
blog.admin.delete.confirm=Delete this entry and all its languages?
|
||||
|
||||
# Console — editor
|
||||
blog.edit.heading=Edit entry
|
||||
blog.edit.headingNew=New entry
|
||||
blog.edit.back=Back to blog
|
||||
blog.edit.shadowed=A page owns this entry's address — the page wins, so the entry is unreachable there:
|
||||
blog.edit.entry=Entry
|
||||
blog.edit.id=Id
|
||||
blog.edit.id.tip=The entry's stable identity (lowercase letters, digits, hyphens). It names the entry's folder and its default slug; it cannot be changed later.
|
||||
blog.edit.date=Publication date
|
||||
blog.edit.author=Author
|
||||
blog.edit.author.tip=Who is credited for this post. Shown as a byline and used for structured data. Leave blank for an unattributed entry.
|
||||
blog.edit.customPath=Custom path
|
||||
blog.edit.customPath.tip=Optional absolute address (e.g. /announcing-v2) replacing the prefixed one for the default language. Leave empty for the normal <prefix>/<slug> address.
|
||||
blog.edit.published=Published
|
||||
blog.edit.defaultLang=default
|
||||
blog.edit.langOn=Published in this language
|
||||
blog.edit.title=Title
|
||||
blog.edit.slug=Slug
|
||||
blog.edit.slug.tip=The address segment under the blog prefix for this language. The default language's slug is the entry's base slug.
|
||||
blog.edit.description=Description
|
||||
blog.edit.body=Body (Markdown)
|
||||
blog.edit.save=Save
|
||||
|
||||
# Console — flash/error feedback
|
||||
blog.flash.created=Entry created.
|
||||
blog.flash.saved=Saved.
|
||||
blog.flash.published=Entry published.
|
||||
blog.flash.unpublished=Entry unpublished.
|
||||
blog.flash.deleted=Entry deleted.
|
||||
blog.error.duplicate=An entry with that id already exists.
|
||||
blog.error.reservedId=That id is reserved — pick another.
|
||||
blog.error.invalid=Some fields are invalid:
|
||||
blog.error.ioError=The entry could not be written.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Blog plugin — español.
|
||||
|
||||
blog.publishedOn=Publicado el
|
||||
blog.by=Por
|
||||
blog.back=Volver al sitio
|
||||
|
||||
blog.perm.settings=Configurar el blog
|
||||
blog.perm.manage=Gestionar entradas del blog
|
||||
blog.settings.enabled=Blog activo
|
||||
blog.settings.prefix=Prefijo de URL
|
||||
blog.settings.template=Plantilla de entrada
|
||||
blog.menu=Blog
|
||||
|
||||
blog.admin.pretitle=Sitio
|
||||
blog.admin.title=Blog
|
||||
blog.admin.heading=Blog
|
||||
blog.admin.new=Nueva entrada
|
||||
blog.admin.new.tip=Crea una nueva entrada (empieza sin publicar).
|
||||
blog.admin.disabled=El blog está desactivado para este sitio (ver la configuración del plugin) — las entradas se conservan pero ninguna se sirve.
|
||||
blog.admin.col.entry=Entrada
|
||||
blog.admin.col.path=Ruta
|
||||
blog.admin.col.langs=Idiomas
|
||||
blog.admin.col.date=Fecha
|
||||
blog.admin.col.status=Estado
|
||||
blog.admin.col.actions=Acciones
|
||||
blog.admin.empty=Aún no hay entradas.
|
||||
blog.admin.published=Publicada
|
||||
blog.admin.draft=Borrador
|
||||
blog.admin.edit=Editar
|
||||
blog.admin.publish=Publicar
|
||||
blog.admin.unpublish=Despublicar
|
||||
blog.admin.delete=Eliminar
|
||||
blog.admin.delete.confirm=¿Eliminar esta entrada y todos sus idiomas?
|
||||
|
||||
blog.edit.heading=Editar entrada
|
||||
blog.edit.headingNew=Nueva entrada
|
||||
blog.edit.back=Volver al blog
|
||||
blog.edit.shadowed=Una página posee la dirección de esta entrada — la página gana, así que la entrada es inaccesible ahí:
|
||||
blog.edit.entry=Entrada
|
||||
blog.edit.id=Id
|
||||
blog.edit.id.tip=La identidad estable de la entrada (minúsculas, dígitos, guiones). Nombra su carpeta y su slug por defecto; no puede cambiarse después.
|
||||
blog.edit.date=Fecha de publicación
|
||||
blog.edit.author=Autor
|
||||
blog.edit.author.tip=A quién se atribuye esta entrada. Se muestra como firma y se usa en los datos estructurados. Déjelo en blanco si no lleva autor.
|
||||
blog.edit.customPath=Ruta personalizada
|
||||
blog.edit.customPath.tip=Dirección absoluta opcional (p. ej. /anunciando-v2) que sustituye a la prefijada para el idioma por defecto. Vacío = la dirección normal <prefijo>/<slug>.
|
||||
blog.edit.published=Publicada
|
||||
blog.edit.defaultLang=por defecto
|
||||
blog.edit.langOn=Publicada en este idioma
|
||||
blog.edit.title=Título
|
||||
blog.edit.slug=Slug
|
||||
blog.edit.slug.tip=El segmento de la dirección bajo el prefijo del blog para este idioma. El slug del idioma por defecto es el slug base de la entrada.
|
||||
blog.edit.description=Descripción
|
||||
blog.edit.body=Cuerpo (Markdown)
|
||||
blog.edit.save=Guardar
|
||||
|
||||
# Consola — mensajes de estado/error
|
||||
blog.flash.created=Entrada creada.
|
||||
blog.flash.saved=Guardado.
|
||||
blog.flash.published=Entrada publicada.
|
||||
blog.flash.unpublished=Entrada despublicada.
|
||||
blog.flash.deleted=Entrada eliminada.
|
||||
blog.error.duplicate=Ya existe una entrada con ese id.
|
||||
blog.error.reservedId=Ese id está reservado — elige otro.
|
||||
blog.error.invalid=Algunos campos no son válidos:
|
||||
blog.error.ioError=No se pudo escribir la entrada.
|
||||
@@ -0,0 +1,43 @@
|
||||
# =============================================================================
|
||||
# Runway Blog Plugin — descriptor
|
||||
# Blog entries as first-class virtual pages via the kernel's ContentSource seam.
|
||||
# Links ONLY the Runway SPI (service tier, SPI 1.0.0).
|
||||
# The install folder name MUST equal this `id`: external/plugins/blog/.
|
||||
# =============================================================================
|
||||
id: blog
|
||||
name: Blog
|
||||
version: 2.1.0
|
||||
|
||||
# Built against the SPI service tier (ContentChanges, SiteEventListener, ContentCatalogView, PluginSettings,
|
||||
# PluginSiteFiles, RequestContext, Messages and @ConsoleScreen) as frozen in SPI 1.0.0. A kernel below it BLOCKS this
|
||||
# plugin at startup with a reason.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# The @Configuration registered into the host context before refresh. Its package (mx.quest.blog) lives
|
||||
# OUTSIDE mx.quest.runway so the host never double-scans it. Beans are wired EXPLICITLY (no @ComponentScan), and every
|
||||
# bean name starts with the plugin id (blog…).
|
||||
mainClass: mx.quest.blog.BlogConfig
|
||||
|
||||
# --- Per-site data -----------------------------------------------------------------------------------------
|
||||
# Entries live in sites/<id>/plugins/blog/entries/<entryId>/ (entry.yml + body-<lang>.md). They are PUBLISHED
|
||||
# CONTENT the site's own operators author, not visitor or user input, so nothing is
|
||||
# declared under siteData.personal: a transfer copy of the site carries the blog, like its pages.
|
||||
|
||||
# --- Grantable control-point permissions -----------------------------------------------------------------
|
||||
# `settings` (reserved id) gates the per-site config editor; `manage` gates the authoring screen.
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: blog.perm.settings, defaultRoles: [] }
|
||||
- { id: manage, realm: tenant, label: blog.perm.manage, defaultRoles: [] }
|
||||
|
||||
# --- Per-site settings (tenant-owned BEHAVIOUR; over sites/<id>/plugins/blog.yml; applied IMMEDIATELY — a save
|
||||
# reaches the blog's SiteEventListener, which drops its per-site URL index before anything re-reads it) -------
|
||||
siteSettings:
|
||||
- { key: enabled, type: boolean, default: true, label: blog.settings.enabled }
|
||||
- { key: prefix, type: string, default: "/blog", label: blog.settings.prefix }
|
||||
- { key: template, type: enum, default: entry-classic, range: "entry-classic,entry-minimal",
|
||||
label: blog.settings.template }
|
||||
|
||||
# --- Tenant-console menu entry (gated by the FULL namespaced permission key; visibility is UX only) --------
|
||||
menu:
|
||||
- { realm: tenant, region: menu, order: 55, label: blog.menu, path: "/__admin/blog",
|
||||
permission: "blog|manage", icon: "fa-solid fa-feather-pointed" }
|
||||
@@ -0,0 +1,184 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!-- Inherit the SAME managed versions the kernel uses (Spring Boot 4.0.6). NOT a Boot app — no repackage;
|
||||
`mvn package` produces a THIN jar of only this plugin's classes plus a lib/ with commonmark. -->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-blog</artifactId>
|
||||
<version>2.1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Blog Plugin</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
|
||||
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
A blog for Runway sites, built on the kernel's ContentSource seam: entries are plugin-owned files in
|
||||
the tenant's folder (metadata + per-language Markdown bodies), served as first-class virtual pages —
|
||||
own URLs under a configurable prefix (or per-entry custom paths), the site's master chrome, full
|
||||
locale dispatch, sitemap/llms.txt listing, search indexing, and by-id links. Authored in a console
|
||||
screen. Links only the Runway SPI (service tier, SPI 1.0.0).
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T18:56:00Z</project.build.outputTimestamp>
|
||||
<runway.version>1.0.0</runway.version>
|
||||
<!-- BUNDLED (goes into this plugin's lib/): the Markdown renderer for entry bodies. PRIVATE to this
|
||||
plugin until a second consumer exists — then it graduates to a code-less provider plugin (the
|
||||
library-provider convention). One version deployment-wide (shared classloader). -->
|
||||
<commonmark.version>0.25.1</commonmark.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
<!-- NO runway-app dependency, in any scope: the plugin links only the SPI, so a host
|
||||
import no longer compiles and the kernel's host-linkage scanner finds nothing to report. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- PLATFORM LIBRARIES — provided by the host at runtime (the kernel's MAJOR line pins their MAJOR lines);
|
||||
compile-only here and never bundled into lib/. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- The console controller: @Controller, @GetMapping/@PostMapping, RedirectAttributes. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- @PreAuthorize on the console handlers. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- entry.yml is read and written with this plugin's own (lenient) YAMLMapper over Jackson 3. -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- The bundled Markdown engine (compile scope → copied into lib/ by the packaging step below). -->
|
||||
<dependency>
|
||||
<groupId>org.commonmark</groupId>
|
||||
<artifactId>commonmark</artifactId>
|
||||
<version>${commonmark.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- The template tests render the shipped templates with Thymeleaf's own engine (decoupled logic), over the
|
||||
model the SPI documents — no kernel class involved. -->
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring6</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>runway-plugin-blog</finalName>
|
||||
<plugins>
|
||||
<!-- Stage the bundled third-party jars for lib/ (compile-scope, non-provided = just commonmark). -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>stage-lib</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/staged-lib</outputDirectory>
|
||||
<includeScope>runtime</includeScope>
|
||||
<!-- NEVER bundle the host's own artifacts: the SPI ships with the kernel; a second
|
||||
copy in lib/ would sit on the shared classloader beside the kernel's. -->
|
||||
<excludeGroupIds>mx.quest</excludeGroupIds>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/blog"/>
|
||||
<delete dir="${stage}"/>
|
||||
<mkdir dir="${stage}"/>
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
|
||||
<copy file="${project.build.directory}/runway-plugin-blog.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/lib">
|
||||
<fileset dir="${project.build.directory}/staged-lib"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/templates">
|
||||
<fileset dir="${project.basedir}/templates"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/i18n">
|
||||
<fileset dir="${project.basedir}/i18n"/>
|
||||
</copy>
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="blog"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-blog-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="blog/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder: ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-blog-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+331
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove
|
||||
# the blog's contract end to end against a Runway 1.0.0 kernel (SPI 1.0.0):
|
||||
# - it loads with ZERO host-linkage and bean-name/surface findings, and nothing blocks or quarantines it;
|
||||
# - entries WRITTEN BY blog 1.3.1 (the test fixture, placed in the site's plugins/blog/entries/ before the boot —
|
||||
# one of them without an author) load unchanged: they serve at their URLs (default prefix, localized slug,
|
||||
# custom path) inside the tenant's own master chrome, with the byline where there is one and none where there
|
||||
# is not; the draft does not serve;
|
||||
# - a page linking ${urls['blog:<id>']} gets the entry's URL from the kernel catalog;
|
||||
# - with discoverability and search installed (built from this repository's sibling folders into the scratch
|
||||
# folder; SKIPPED when they cannot be built): sitemap.xml and llms.txt list the published entries and not the
|
||||
# draft, and search finds an entry by a word that is only in its Markdown body (indexableText);
|
||||
# - the console screen (@ConsoleScreen) renders inside the operator shell, gated (anonymous → login), and every
|
||||
# mutation is a CSRF-checked POST: without the token → 403 and nothing written; a GET on a mutation path
|
||||
# changes nothing;
|
||||
# - signed in as the site owner: create → the entry serves AT ONCE and is in sitemap and search on the next
|
||||
# request (ContentChanges evicts routing, the catalog and search); edit the body → search follows; unpublish →
|
||||
# 404 and gone from sitemap and search; a reserved custom path is refused at save; a prefix change through the
|
||||
# settings form re-keys the URLs at once (onSettingsChanged); delete → the folder is gone;
|
||||
# - a FULL backup and a TRANSFER copy both carry the entries (published content, not personal data).
|
||||
# Verify ONLY against the packaged jar — never spring-boot:run (its restart classloader loads ZERO plugins).
|
||||
#
|
||||
# Usage: scripts/verify-against-host.sh [--keep] [--port N]
|
||||
# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host
|
||||
# MVN=/path/to/mvn Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR=/path/to/runway-app-<ver>-exec.jar the kernel to verify against (default: the host checkout's
|
||||
# runway-app/target jar MATCHING its pom version)
|
||||
# COMPANIONS="discoverability search" sibling plugins to install for the sitemap/llms.txt/search checks
|
||||
# (built offline from a COPY in the scratch folder; their own folders
|
||||
# are never written). Set it to "" to skip those checks.
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp)
|
||||
# VERIFY_LOG_DIR=/dir keep copies of the host logs and the backup manifests there
|
||||
# The script never runs `mvn install` (nothing is written to ~/.m2): it packages offline against whatever is already
|
||||
# in the local repository.
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment.
|
||||
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
|
||||
export JAVA_HOME
|
||||
JAVA="$JAVA_HOME/bin/java"
|
||||
MVN="${MVN:-mvn}"
|
||||
# Default host: the kernel at the root of the repository this plugin sits in (plugins/<name>/), else a kernel
|
||||
# checkout named `runway` beside the plugins checkout.
|
||||
if [ -z "${HOST_TARGET:-}" ]; then
|
||||
if [ -f "$HERE/../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../runway-app/target"
|
||||
else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi
|
||||
fi
|
||||
COMPANIONS="${COMPANIONS-discoverability search}"
|
||||
|
||||
KEEP="no"; PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--keep) KEEP="yes"; shift ;;
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
|
||||
APP_USER=root; APP_PW=Blog-Admin-2026; SITE_USER=owner; SITE_PW=Blog-Site-2026
|
||||
SECRET_KEY=blog-verify-master-key-2026
|
||||
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
|
||||
[ -n "$PORT" ] || PORT="$(free_port)"
|
||||
BASE="http://localhost:$PORT"
|
||||
|
||||
echo "[verify] building the plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "plugin build failed"; exit 1; }
|
||||
|
||||
# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same
|
||||
# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test.
|
||||
if [ -n "${HOST_JAR:-}" ]; then
|
||||
JAR="$HOST_JAR"
|
||||
else
|
||||
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
|
||||
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
|
||||
fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; }
|
||||
echo "[verify] host jar: $JAR"
|
||||
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/blog-verify.XXXXXX")"
|
||||
cleanup() {
|
||||
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
|
||||
&& cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$VERIFY_LOG_DIR"/ 2>/dev/null; }
|
||||
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ and
|
||||
# makes `rm -rf` leave the scratch folder behind.
|
||||
[ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; }
|
||||
}
|
||||
trap cleanup EXIT
|
||||
EXT="$SCRATCH/external"
|
||||
mkdir -p "$EXT/plugins"
|
||||
cp -r "$HERE/target/blog" "$EXT/plugins/blog"
|
||||
|
||||
# --- Companion plugins, built from a COPY (their own folders stay untouched) ---------------------------------------
|
||||
INSTALLED=""
|
||||
for id in $COMPANIONS; do
|
||||
src="$HERE/../$id"
|
||||
[ -f "$src/pom.xml" ] || { echo "[verify] companion $id: no source at $src"; continue; }
|
||||
mkdir -p "$SCRATCH/build"
|
||||
( cd "$src" && tar --exclude=./target -cf - . ) | ( mkdir -p "$SCRATCH/build/$id" && cd "$SCRATCH/build/$id" && tar -xf - )
|
||||
if ( cd "$SCRATCH/build/$id" && "$MVN" -o -q -DskipTests package >"$SCRATCH/build-$id.txt" 2>&1 ) \
|
||||
&& [ -d "$SCRATCH/build/$id/target/$id" ]; then
|
||||
cp -r "$SCRATCH/build/$id/target/$id" "$EXT/plugins/$id"
|
||||
INSTALLED="$INSTALLED $id"
|
||||
echo "[verify] companion $id $(sed -n 's/^version: *//p' "$EXT/plugins/$id/plugin.yml") installed"
|
||||
else
|
||||
echo "[verify] companion $id could not be built (see build-$id.txt) — its checks are skipped"
|
||||
fi
|
||||
done
|
||||
has() { case " $INSTALLED " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
PASS=0; FAIL=0; SKIP=0
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
skip() { echo " SKIP $1"; SKIP=$((SKIP+1)); }
|
||||
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \
|
||||
--runway.security.secret-key="$SECRET_KEY" ) >"$1" 2>&1 & PID=$!; }
|
||||
|
||||
echo "[verify] booting host (wizard) on :$PORT ..."
|
||||
boot "$SCRATCH/wizard.log"
|
||||
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; }
|
||||
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW"
|
||||
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
|
||||
|
||||
# --- The default site, prepared on disk before the ACTIVE boot reads it ---------------------------------------------
|
||||
SITE="$EXT/sites/default"
|
||||
[ -f "$SITE/site.yml" ] || { echo "the wizard did not seed $SITE"; exit 1; }
|
||||
# Two languages (English default, Spanish), so the localized slug and the locale ladder are exercised.
|
||||
python3 -I - "$SITE/site.yml" <<'PY'
|
||||
import re, sys
|
||||
p = sys.argv[1]; s = open(p, encoding="utf-8").read()
|
||||
s = re.sub(r'(?m)^locales:\n(?:- .*\n)*', 'locales:\n- "en"\n- "es"\n', s)
|
||||
open(p, "w", encoding="utf-8").write(s)
|
||||
PY
|
||||
grep -q '^- "es"' "$SITE/site.yml" || { echo "could not add Spanish to the site:"; cat "$SITE/site.yml"; exit 1; }
|
||||
# Entries exactly as blog 1.3.1 wrote them (the unit tests' fixture, produced by the 1.3.1 store).
|
||||
mkdir -p "$SITE/plugins/blog"
|
||||
cp -r "$HERE/src/test/resources/fixtures/blog-1.3.1/entries" "$SITE/plugins/blog/entries"
|
||||
# A page whose body links an entry through the kernel's URL map: the seeded About page, edited on disk.
|
||||
sed -i 's|<main id="content">|<main id="content"><a id="to-blog" href="#">blog</a>|' "$SITE/templates/about.html"
|
||||
sed -i 's|</thlogic>|<attr sel="#to-blog" th:href="${urls['"'"'blog:hello-world'"'"']}"/></thlogic>|' \
|
||||
"$SITE/templates/about.th.xml"
|
||||
# llms.txt is part of discoverability's opt-in GEO area (off by default): switch it on for this site.
|
||||
has discoverability && printf '"geo.enabled": true\n' > "$SITE/plugins/discoverability.yml"
|
||||
|
||||
echo "[verify] booting host (ACTIVE) ..."
|
||||
boot "$SCRATCH/active.log"
|
||||
wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; }
|
||||
LOG="$SCRATCH/active.log"
|
||||
ENTRIES="$SITE/plugins/blog/entries"
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' -H 'Accept-Language: en' "$@"; }
|
||||
get() { curl -s -H 'Accept-Language: en' "$@"; }
|
||||
|
||||
echo "== plugin load (SPI 1.0.0 contract) =="
|
||||
EXPECTED=$((1 + $(echo $INSTALLED | wc -w)))
|
||||
ck "plugins registered ($EXPECTED), 0 blocked" "grep -qE 'plugins: $EXPECTED registered, 0 blocked' '$LOG'"
|
||||
ck "blog not blocked / quarantined" "! grep -qE \"plugin 'blog' is blocked|plugin-quarantine/blog\" '$LOG'"
|
||||
# Host linkage and the surface rules: the kernel logs "plugin 'blog' linkage scan: <reason>" before "is blocked" (the
|
||||
# check above), and a surface problem names the offending bean ("bean name …", "… may not contribute"). The badge
|
||||
# wording of the plugins screen ("uses host internals") is matched too.
|
||||
ck "ZERO host-linkage findings for blog" "! grep -qE \"plugin 'blog' (uses host internals|linkage scan)\" '$LOG'"
|
||||
ck "ZERO bean-name/surface findings for blog" "! grep -qE \"plugin 'blog'.*(bean name|may not contribute)\" '$LOG'"
|
||||
ck "no WARN/ERROR from or about the blog" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"mx\\.quest\\.blog|'blog'|blog entr\""
|
||||
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
|
||||
|
||||
# The application console's plugins screen: blog's row shows the version, LOADED, and no health note at all — no
|
||||
# host-linkage badge, no contained failure, no warning.
|
||||
APP_JAR_C="$SCRATCH/cookies-app.txt"
|
||||
ac() { curl -s -H 'Accept-Language: en' -c "$APP_JAR_C" -b "$APP_JAR_C" "$@"; }
|
||||
ac -o /dev/null -X POST "$BASE/app/login" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "_csrf=$(ac "$BASE/app/login" | grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//')"
|
||||
ac "$BASE/__app/plugins" > "$SCRATCH/plugins-screen.html"
|
||||
row() { # plugin-id -> its <tr> on the plugins screen
|
||||
python3 -I - "$SCRATCH/plugins-screen.html" "$1" <<'PY2'
|
||||
import re, sys
|
||||
html = open(sys.argv[1], encoding="utf-8").read()
|
||||
for tr in re.findall(r"(?s)<tr\b.*?</tr>", html):
|
||||
if re.search(r'class="c-id">%s<' % re.escape(sys.argv[2]), tr):
|
||||
print(tr); break
|
||||
PY2
|
||||
}
|
||||
row blog > "$SCRATCH/plugins-row-blog.html"
|
||||
BLOG_VERSION="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")"
|
||||
ck "plugins screen: blog $BLOG_VERSION, Loaded" \
|
||||
"grep -q 'class=\"c-version\">$BLOG_VERSION<' '$SCRATCH/plugins-row-blog.html' && grep -q 'bg-green-lt' '$SCRATCH/plugins-row-blog.html'"
|
||||
ck "…with no host-linkage badge, no failure count and no health notes" \
|
||||
"[ -s '$SCRATCH/plugins-row-blog.html' ] && ! grep -qE 'c-host|c-failures|c-notes|c-warning|c-refused' '$SCRATCH/plugins-row-blog.html'"
|
||||
# There used to be a positive control here: "an unmigrated companion (discoverability) does show the badge". Every
|
||||
# companion is SPI-only now, so it failed for the wrong reason and was dropped. A real control
|
||||
# needs a deliberately host-linked fixture jar; until then the badge check above has none.
|
||||
|
||||
echo "== entries written by blog 1.3.1 serve unchanged =="
|
||||
get "$BASE/blog/hello-world" > "$SCRATCH/hello.html"
|
||||
ck "/blog/hello-world -> 200" "[ \"\$(code '$BASE/blog/hello-world')\" = 200 ]"
|
||||
ck "…inside the tenant's master chrome (site header + footer)" \
|
||||
"grep -q 'id=\"site-header\"' '$SCRATCH/hello.html' && grep -q 'id=\"site-footer\"' '$SCRATCH/hello.html' && ! grep -q 'from the master at render' '$SCRATCH/hello.html'"
|
||||
ck "…with its title, its rendered Markdown and its byline" \
|
||||
"grep -q 'Hello world' '$SCRATCH/hello.html' && grep -q '<strong>bold</strong>' '$SCRATCH/hello.html' && grep -q 'By Jane Doe' '$SCRATCH/hello.html' && grep -q 'Published on 2026-07-17' '$SCRATCH/hello.html'"
|
||||
get "$BASE/es/blog/hola-mundo" > "$SCRATCH/hola.html"
|
||||
ck "/es/blog/hola-mundo (the localized slug) -> 200 in Spanish" \
|
||||
"[ \"\$(code '$BASE/es/blog/hola-mundo')\" = 200 ] && grep -q 'Hola mundo' '$SCRATCH/hola.html' && grep -q 'Publicado el' '$SCRATCH/hola.html'"
|
||||
get "$BASE/blog/no-author" > "$SCRATCH/no-author.html"
|
||||
ck "the entry 1.3.1 wrote WITHOUT an author serves, with a date and no byline" \
|
||||
"[ \"\$(code '$BASE/blog/no-author')\" = 200 ] && grep -q 'Unattributed' '$SCRATCH/no-author.html' && grep -q 'Published on 2026-08-01' '$SCRATCH/no-author.html' && ! grep -q 'id=\"entry-author\"' '$SCRATCH/no-author.html'"
|
||||
ck "the custom path /announcing-v2 serves the launch entry" \
|
||||
"[ \"\$(code '$BASE/announcing-v2')\" = 200 ] && get '$BASE/announcing-v2' | grep -q 'By Richard Roe'"
|
||||
ck "the draft does not serve (404)" "[ \"\$(code '$BASE/blog/draft-post')\" = 404 ]"
|
||||
ck "a page's \${urls['blog:hello-world']} is the entry's URL (kernel catalog)" \
|
||||
"get '$BASE/about' | grep -q 'id=\"to-blog\" href=\"/blog/hello-world\"'"
|
||||
ck "an entry carries an ETag (its updatedAt) and revalidates 304" \
|
||||
"E=\$(curl -s -D - -o /dev/null '$BASE/blog/hello-world' | sed -n 's/^[Ee][Tt]ag: *//p' | tr -d '\r'); [ -n \"\$E\" ] && [ \"\$(code -H \"If-None-Match: \$E\" '$BASE/blog/hello-world')\" = 304 ]"
|
||||
|
||||
sitemap() { get "$BASE/sitemap.xml"; }
|
||||
search() { get "$BASE/search/api?q=$1"; }
|
||||
echo "== sitemap.xml / llms.txt / search through the kernel catalog =="
|
||||
if has discoverability; then
|
||||
sitemap > "$SCRATCH/sitemap-0.xml"
|
||||
ck "sitemap.xml lists the published entries (default + localized URLs, custom path)" \
|
||||
"grep -q '/blog/hello-world</loc>' '$SCRATCH/sitemap-0.xml' && grep -q '/es/blog/hola-mundo' '$SCRATCH/sitemap-0.xml' && grep -q '/announcing-v2</loc>' '$SCRATCH/sitemap-0.xml' && grep -q '/blog/no-author</loc>' '$SCRATCH/sitemap-0.xml'"
|
||||
ck "…and not the draft" "! grep -q 'draft-post' '$SCRATCH/sitemap-0.xml'"
|
||||
ck "llms.txt lists an entry" "get '$BASE/llms.txt' | grep -q '/blog/hello-world'"
|
||||
else
|
||||
skip "sitemap.xml / llms.txt (discoverability not installed)"
|
||||
fi
|
||||
if has search; then
|
||||
ck "search finds an entry by a word only in its Markdown body (indexableText)" \
|
||||
"search words | grep -q '/blog/hello-world'"
|
||||
ck "…and not the draft's body" "! search 'Not+yet' | grep -q 'draft-post'"
|
||||
else
|
||||
skip "search (search not installed)"
|
||||
fi
|
||||
|
||||
echo "== the console screen: @ConsoleScreen, gated, CSRF-checked POSTs =="
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
JAR_C="$SCRATCH/cookies.txt"
|
||||
sc() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; }
|
||||
ck "anonymous GET /__admin/blog does not render the screen (sign-in first)" \
|
||||
"R=\$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' '$BASE/__admin/blog'); echo \"\$R\" | grep -qE '^(302|303) .*/login|^40[13]'"
|
||||
ck "anonymous POST create without a token -> 403, nothing written" \
|
||||
"[ \"\$(code -X POST '$BASE/__admin/blog/create' -d 'id=anon-post&title_en=x&published=on')\" = 403 ] && [ ! -e '$ENTRIES/anon-post' ]"
|
||||
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
|
||||
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
|
||||
sc "$BASE/__admin/blog" > "$SCRATCH/console-list.html"
|
||||
ck "signed in: the list renders INSIDE the operator shell" \
|
||||
"grep -q 'id=\"topbar\"' '$SCRATCH/console-list.html' && grep -q 'id=\"op-main\"' '$SCRATCH/console-list.html' && grep -q 'id=\"bl-heading\"' '$SCRATCH/console-list.html'"
|
||||
ck "…with the 1.3.1 entries, the draft badge and the plugin's pretitle" \
|
||||
"grep -q '>hello-world<' '$SCRATCH/console-list.html' && grep -q '>draft-post<' '$SCRATCH/console-list.html' && grep -q '>Draft<' '$SCRATCH/console-list.html' && grep -q 'id=\"bl-pretitle\">Site<' '$SCRATCH/console-list.html'"
|
||||
ck "…and the shell's menu carries the Blog entry" "grep -q 'href=\"/__admin/blog\"' '$SCRATCH/console-list.html'"
|
||||
ck "every mutating form is a POST carrying the console's CSRF token" \
|
||||
"! grep -qE 'href=\"/__admin/blog/[^\"]*/(publish|delete)\"' '$SCRATCH/console-list.html' && grep -qE 'method=\"post\" action=\"/__admin/blog/hello-world/publish\"' '$SCRATCH/console-list.html' && grep -qE 'name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/console-list.html'"
|
||||
TOKEN="$(token < "$SCRATCH/console-list.html")"
|
||||
ck "signed in, POST without the token -> 403 and the entry stays published" \
|
||||
"[ \"\$(sc -o /dev/null -w '%{http_code}' -X POST '$BASE/__admin/blog/hello-world/publish')\" = 403 ] && grep -q 'published: true' '$ENTRIES/hello-world/entry.yml'"
|
||||
ck "signed in, GET on the publish path changes nothing" \
|
||||
"sc -o /dev/null '$BASE/__admin/blog/hello-world/publish'; grep -q 'published: true' '$ENTRIES/hello-world/entry.yml'"
|
||||
ck "the editor of an entry 1.3.1 wrote shows its fields" \
|
||||
"sc '$BASE/__admin/blog/no-author/edit' | grep -q 'value=\"Unattributed\"'"
|
||||
|
||||
echo "== create / edit / unpublish / delete: every change is visible on the next request =="
|
||||
[ -n "$(has discoverability && echo y)" ] && sitemap > /dev/null # warm the catalog cache before the change
|
||||
[ -n "$(has search && echo y)" ] && search warmup > /dev/null # …and the search index
|
||||
R="$(sc -o /dev/null -w '%{http_code} %{redirect_url}' -X POST "$BASE/__admin/blog/create" \
|
||||
--data-urlencode "_csrf=$TOKEN" --data-urlencode 'id=fresh-post' --data-urlencode 'title_en=Fresh post' \
|
||||
--data-urlencode 'title_es=Entrada nueva' --data-urlencode 'slug_es=entrada-nueva' \
|
||||
--data-urlencode 'body_en=Zanzibar is the first word of this body.' --data-urlencode 'locales_en=on' \
|
||||
--data-urlencode 'locales_es=on' --data-urlencode 'published=on' --data-urlencode 'publishedOn=2026-10-18')"
|
||||
ck "create -> redirect to the editor" "echo '$R' | grep -qE '^302 .*/__admin/blog/fresh-post/edit'"
|
||||
ck "…written into the entries folder" "[ -f '$ENTRIES/fresh-post/entry.yml' ] && [ -f '$ENTRIES/fresh-post/body-en.md' ]"
|
||||
ck "…and it serves AT ONCE (routing evicted)" "get '$BASE/blog/fresh-post' | grep -q 'Zanzibar'"
|
||||
ck "…in Spanish at its localized slug" "[ \"\$(code '$BASE/es/blog/entrada-nueva')\" = 200 ]"
|
||||
if has discoverability; then ck "…and is in sitemap.xml on the next request" "sitemap | grep -q '/blog/fresh-post</loc>'"; fi
|
||||
if has search; then ck "…and search finds it on the next request" "search zanzibar | grep -q '/blog/fresh-post'"; fi
|
||||
sc -o /dev/null -X POST "$BASE/__admin/blog/fresh-post" --data-urlencode "_csrf=$TOKEN" \
|
||||
--data-urlencode 'title_en=Fresh post' --data-urlencode 'body_en=Quokka replaced the old word.' \
|
||||
--data-urlencode 'locales_en=on' --data-urlencode 'published=on' --data-urlencode 'publishedOn=2026-10-18'
|
||||
ck "edit the body -> the page shows the new body" "get '$BASE/blog/fresh-post' | grep -q 'Quokka'"
|
||||
if has search; then
|
||||
ck "…search finds the new word" "search quokka | grep -q '/blog/fresh-post'"
|
||||
ck "…and no longer the old one" "! search zanzibar | grep -q '/blog/fresh-post'"
|
||||
fi
|
||||
ck "a reserved custom path is refused at save, nothing written" \
|
||||
"sc -X POST '$BASE/__admin/blog/create' --data-urlencode '_csrf=$TOKEN' -d 'id=bad-path&title_en=x&customPath=/app/x&published=on' | grep -q 'customPath' && [ ! -e '$ENTRIES/bad-path' ]"
|
||||
sc -o /dev/null -X POST "$BASE/__admin/blog/fresh-post/publish" --data-urlencode "_csrf=$TOKEN"
|
||||
ck "unpublish -> 404 at once" "[ \"\$(code '$BASE/blog/fresh-post')\" = 404 ]"
|
||||
if has discoverability; then ck "…and gone from sitemap.xml" "! sitemap | grep -q 'fresh-post'"; fi
|
||||
if has search; then ck "…and from search" "! search quokka | grep -q 'fresh-post'"; fi
|
||||
|
||||
echo "== a prefix change through the settings form re-keys every URL at once =="
|
||||
SETTINGS="$BASE/__admin/plugins/blog/settings"
|
||||
sc -o /dev/null -X POST "$SETTINGS" --data-urlencode "_csrf=$(sc "$SETTINGS" | token)" \
|
||||
--data-urlencode 'enabled=true' --data-urlencode 'prefix=/news' --data-urlencode 'template=entry-minimal'
|
||||
ck "the settings were stored" "grep -q 'prefix: \"/news\"' '$SITE/plugins/blog.yml'"
|
||||
ck "/news/hello-world -> 200 with the minimal template (no byline)" \
|
||||
"[ \"\$(code '$BASE/news/hello-world')\" = 200 ] && ! get '$BASE/news/hello-world' | grep -q 'By Jane Doe'"
|
||||
ck "/blog/hello-world -> 404 (the old URL is gone)" "[ \"\$(code '$BASE/blog/hello-world')\" = 404 ]"
|
||||
ck "the custom path is unaffected" "[ \"\$(code '$BASE/announcing-v2')\" = 200 ]"
|
||||
if has discoverability; then ck "sitemap.xml follows the new prefix" "sitemap | grep -q '/news/hello-world</loc>'"; fi
|
||||
sc -o /dev/null -X POST "$SETTINGS" --data-urlencode "_csrf=$(sc "$SETTINGS" | token)" \
|
||||
--data-urlencode 'enabled=true' --data-urlencode 'prefix=/app' --data-urlencode 'template=entry-classic'
|
||||
ck "a reserved prefix (/app) falls back to /blog instead of hiding every entry" \
|
||||
"[ \"\$(code '$BASE/blog/hello-world')\" = 200 ]"
|
||||
|
||||
echo "== backups carry the blog (published content, not personal data) =="
|
||||
sc -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download"
|
||||
sc -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer"
|
||||
zipq() { # zip mode -> prints what was asked
|
||||
python3 -I - "$@" <<'PY'
|
||||
import sys, zipfile
|
||||
z = zipfile.ZipFile(sys.argv[1]); mode = sys.argv[2]
|
||||
names = z.namelist()
|
||||
if mode == "has":
|
||||
sys.exit(0 if any(n.endswith(sys.argv[3]) for n in names) else 1)
|
||||
if mode == "read":
|
||||
n = next(n for n in names if n.endswith(sys.argv[3])); sys.stdout.write(z.read(n).decode("utf-8"))
|
||||
PY
|
||||
}
|
||||
zipq "$SCRATCH/full.zip" read manifest.yml > "$SCRATCH/full-manifest.yml" 2>/dev/null
|
||||
zipq "$SCRATCH/transfer.zip" read manifest.yml > "$SCRATCH/transfer-manifest.yml" 2>/dev/null
|
||||
ck "the full backup carries the entries" "zipq '$SCRATCH/full.zip' has plugins/blog/entries/hello-world/entry.yml"
|
||||
ck "the transfer copy carries them too" "zipq '$SCRATCH/transfer.zip' has plugins/blog/entries/no-author/body-en.md"
|
||||
ck "…and its manifest omits nothing of the blog" "! grep -q 'plugins/blog' '$SCRATCH/transfer-manifest.yml'"
|
||||
|
||||
echo "== delete =="
|
||||
sc -o /dev/null -X POST "$BASE/__admin/blog/fresh-post/delete" --data-urlencode "_csrf=$TOKEN"
|
||||
ck "delete removes the entry's folder" "[ ! -e '$ENTRIES/fresh-post' ]"
|
||||
ck "…and the other entries are intact" "[ -f '$ENTRIES/hello-world/entry.yml' ] && [ -f '$ENTRIES/no-author/entry.yml' ]"
|
||||
|
||||
ck "no ERROR in the host log after all of it" "! grep -q ' ERROR ' '$LOG'"
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed, $SKIP skipped"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,332 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The blog's tenant-console authoring screens ({@code /__admin/blog}): list, create, edit, publish/unpublish
|
||||
* and delete entries — a plugin-owned console surface rendered inside the operator shell through
|
||||
* {@link ConsoleScreen} (the kernel fills the shell's model; the {@code contentTemplate} resolves through this
|
||||
* plugin's own {@code __plugin__/blog/…} namespace).
|
||||
*
|
||||
* <p>Four platform disciplines enforced here:
|
||||
* <ul>
|
||||
* <li><b>tenancy is always the bound one</b> ({@link RequestContext#site()}), never a path/param id;</li>
|
||||
* <li><b>every mutation is announced</b> through {@link ContentChanges#changed} — the single freshness trigger
|
||||
* for the plugin's own URL index (delivered back to {@link BlogContentSource} as a SOURCE listener) and for
|
||||
* every kernel consumer (routing, sitemap, llms.txt, search), relayed cluster-wide by the host;</li>
|
||||
* <li><b>every state change is a CSRF-checked {@code POST}</b> (the console chain checks the token; the
|
||||
* templates put it in every form) — the {@code GET}s only render;</li>
|
||||
* <li><b>the reverse advisory</b>: the edit screen asks the kernel's
|
||||
* {@link ContentCatalogView#pageAt} whether a published page owns any of the entry's URLs — the page would
|
||||
* win, so the author is warned exactly where they type the slug.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Gated by this plugin's own grantable control point ({@code blog|manage}, checked by the kernel's
|
||||
* {@code AccessCheck}, bean {@code authz}); the per-site settings editor is gated separately by the reserved
|
||||
* {@code settings} point (host-rendered from the descriptor schema).
|
||||
*/
|
||||
@Controller
|
||||
@ConsoleScreen
|
||||
public class BlogAdminController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BlogAdminController.class);
|
||||
|
||||
private static final String PERMISSION = "@authz.may('blog|manage')";
|
||||
|
||||
/** Ids the routing table owns — an entry named like an action verb would be uneditable/unreachable. */
|
||||
private static final Set<String> RESERVED_IDS = Set.of("create", "new");
|
||||
private static final Pattern SAFE_SLUG = Pattern.compile("[a-z0-9][a-z0-9-]{0,98}[a-z0-9]|[a-z0-9]");
|
||||
|
||||
private final RequestContext request;
|
||||
private final BlogStore store;
|
||||
private final BlogContentSource source;
|
||||
private final ContentCatalogView catalog;
|
||||
private final ContentChanges changes;
|
||||
private final Messages messages;
|
||||
|
||||
public BlogAdminController(RequestContext request, BlogStore store, BlogContentSource source,
|
||||
ContentCatalogView catalog, ContentChanges changes, Messages messages) {
|
||||
this.request = request;
|
||||
this.store = store;
|
||||
this.source = source;
|
||||
this.catalog = catalog;
|
||||
this.changes = changes;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.console(key, fallback);
|
||||
}
|
||||
|
||||
/** One list row: the entry plus its resolved public path (under the current prefix settings). */
|
||||
public record EntryRow(BlogEntry entry, String publicPath) {
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/blog")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String list(Model model) {
|
||||
SiteView site = boundTenancy();
|
||||
List<EntryRow> rows = new ArrayList<>();
|
||||
for (BlogEntry entry : store.list(site.id())) {
|
||||
rows.add(new EntryRow(entry, source.publicPath(site.id(), entry)));
|
||||
}
|
||||
model.addAttribute("rows", rows);
|
||||
model.addAttribute("blogEnabled", source.settings(site.id()).enabled());
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "blog.admin.title");
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/blog/admin-list");
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/blog/new")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String createForm(Model model) {
|
||||
SiteView site = boundTenancy();
|
||||
editorModel(model, site, new BlogEntry("new-entry", Map.of(), Map.of(), List.of(), null, Map.of(),
|
||||
null, false, null, null, null), Map.of(), true);
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/blog/create")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String create(@RequestParam("id") String id, @RequestParam MultiValueMap<String, String> params,
|
||||
Model model, RedirectAttributes redirect) {
|
||||
SiteView site = boundTenancy();
|
||||
String entryId = id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
String error = null;
|
||||
try {
|
||||
BlogStore.requireSafeId(entryId);
|
||||
if (RESERVED_IDS.contains(entryId)) {
|
||||
error = message("blog.error.reservedId", "That id is reserved — pick another.");
|
||||
} else if (store.read(site.id(), entryId).isPresent()) {
|
||||
error = message("blog.error.duplicate", "An entry with that id already exists.");
|
||||
} else {
|
||||
validateForm(site, params);
|
||||
save(site, entryId, params);
|
||||
redirect.addFlashAttribute("flash",
|
||||
message("blog.flash.created", "Entry created."));
|
||||
return "redirect:/__admin/blog/" + entryId + "/edit";
|
||||
}
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
error = message("blog.error.invalid", "Some fields are invalid: ") + invalid.getMessage();
|
||||
} catch (IOException io) {
|
||||
log.warn("creating blog entry {}/{} failed", site.id(), entryId, io);
|
||||
error = message("blog.error.ioError", "The entry could not be written.");
|
||||
}
|
||||
// NEVER blank the form on failure: re-render the editor with exactly what the author typed.
|
||||
editorModel(model, site, parseEntry(site, entryId.isEmpty() ? "new-entry" : entryId, params),
|
||||
parseBodies(site, params), true);
|
||||
model.addAttribute("error", error);
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/blog/{id}/edit")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String editForm(@PathVariable("id") String id, Model model) {
|
||||
SiteView site = boundTenancy();
|
||||
BlogEntry entry = store.read(site.id(), id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such entry"));
|
||||
Map<String, String> bodies = new LinkedHashMap<>();
|
||||
for (Locale locale : site.locales()) {
|
||||
bodies.put(locale.getLanguage(), store.readBody(site.id(), id, locale.getLanguage()));
|
||||
}
|
||||
editorModel(model, site, entry, bodies, false);
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/blog/{id}")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String update(@PathVariable("id") String id, @RequestParam MultiValueMap<String, String> params,
|
||||
RedirectAttributes redirect) {
|
||||
SiteView site = boundTenancy();
|
||||
store.read(site.id(), id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such entry"));
|
||||
try {
|
||||
validateForm(site, params);
|
||||
save(site, id, params);
|
||||
redirect.addFlashAttribute("flash", message("blog.flash.saved", "Saved."));
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
redirect.addFlashAttribute("error",
|
||||
message("blog.error.invalid", "Some fields are invalid: ") + invalid.getMessage());
|
||||
} catch (IOException io) {
|
||||
log.warn("saving blog entry {}/{} failed", site.id(), id, io);
|
||||
redirect.addFlashAttribute("error", message("blog.error.ioError", "The entry could not be written."));
|
||||
}
|
||||
return "redirect:/__admin/blog/" + id + "/edit";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/blog/{id}/publish")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String togglePublished(@PathVariable("id") String id, RedirectAttributes redirect) {
|
||||
SiteView site = boundTenancy();
|
||||
BlogEntry entry = store.read(site.id(), id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such entry"));
|
||||
try {
|
||||
// Carry author and publishedOn through: toggling visibility is not an editorial change, and this
|
||||
// rebuild lists every field explicitly, so anything forgotten here is silently erased on publish.
|
||||
store.save(site.id(), new BlogEntry(entry.id(), entry.title(), entry.description(),
|
||||
entry.locales(), entry.slug(), entry.localizedSlugs(), entry.customPath(),
|
||||
!entry.published(), entry.publishedOn(), entry.author(), null), null);
|
||||
changes.changed(site.id(), BlogContentSource.KEY, id);
|
||||
redirect.addFlashAttribute("flash", entry.published()
|
||||
? message("blog.flash.unpublished", "Entry unpublished.")
|
||||
: message("blog.flash.published", "Entry published."));
|
||||
} catch (IOException io) {
|
||||
log.warn("toggling blog entry {}/{} failed", site.id(), id, io);
|
||||
redirect.addFlashAttribute("error", message("blog.error.ioError", "The entry could not be written."));
|
||||
}
|
||||
return "redirect:/__admin/blog";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/blog/{id}/delete")
|
||||
@PreAuthorize(PERMISSION)
|
||||
public String delete(@PathVariable("id") String id, RedirectAttributes redirect) {
|
||||
SiteView site = boundTenancy();
|
||||
try {
|
||||
store.delete(site.id(), id);
|
||||
changes.changed(site.id(), BlogContentSource.KEY, id);
|
||||
redirect.addFlashAttribute("flash", message("blog.flash.deleted", "Entry deleted."));
|
||||
} catch (IOException io) {
|
||||
log.warn("deleting blog entry {}/{} failed", site.id(), id, io);
|
||||
redirect.addFlashAttribute("error", message("blog.error.ioError", "The entry could not be deleted."));
|
||||
}
|
||||
return "redirect:/__admin/blog";
|
||||
}
|
||||
|
||||
// --- shared ------------------------------------------------------------------------------------------------
|
||||
|
||||
/** Reads the editor form into the entry + bodies, persists, and announces the change. */
|
||||
private void save(SiteView site, String entryId, MultiValueMap<String, String> params) throws IOException {
|
||||
store.save(site.id(), parseEntry(site, entryId, params), parseBodies(site, params));
|
||||
changes.changed(site.id(), BlogContentSource.KEY, entryId);
|
||||
}
|
||||
|
||||
/** The editor form → an entry (the default language's slug field doubles as the base slug). */
|
||||
private static BlogEntry parseEntry(SiteView site, String entryId, MultiValueMap<String, String> params) {
|
||||
Map<String, String> title = perLang(site, params, "title_");
|
||||
Map<String, String> description = perLang(site, params, "description_");
|
||||
Map<String, String> localizedSlugs = perLang(site, params, "slug_");
|
||||
List<String> locales = new ArrayList<>();
|
||||
for (Locale locale : site.locales()) {
|
||||
if (params.containsKey("locales_" + locale.getLanguage())) {
|
||||
locales.add(locale.getLanguage());
|
||||
}
|
||||
}
|
||||
String defaultLang = site.defaultLocale().getLanguage();
|
||||
String slug = localizedSlugs.remove(defaultLang);
|
||||
return new BlogEntry(entryId, title, description, locales, slug, localizedSlugs,
|
||||
first(params, "customPath"), params.containsKey("published"), first(params, "publishedOn"),
|
||||
first(params, "author"), null);
|
||||
}
|
||||
|
||||
private static Map<String, String> parseBodies(SiteView site, MultiValueMap<String, String> params) {
|
||||
Map<String, String> bodies = new LinkedHashMap<>();
|
||||
for (Locale locale : site.locales()) {
|
||||
String lang = locale.getLanguage();
|
||||
bodies.put(lang, first(params, "body_" + lang));
|
||||
}
|
||||
return bodies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects URL inputs the kernel's fail-closed backstop would otherwise DISCARD SILENTLY (the console
|
||||
* would flash "saved" while the entry quietly vanished from routing and listings): slugs must match the
|
||||
* slug grammar; a custom path must be absolute, free of the index separator, and a path the kernel would
|
||||
* serve content at ({@link ContentCatalogView#servablePath}: safe, not reserved, not an endpoint route).
|
||||
*/
|
||||
private void validateForm(SiteView site, MultiValueMap<String, String> params) {
|
||||
for (Locale locale : site.locales()) {
|
||||
String slug = first(params, "slug_" + locale.getLanguage());
|
||||
if (slug != null && !slug.isBlank() && !SAFE_SLUG.matcher(slug.trim()).matches()) {
|
||||
throw new IllegalArgumentException("slug (" + locale.getLanguage() + ")");
|
||||
}
|
||||
}
|
||||
String customPath = first(params, "customPath");
|
||||
if (customPath != null && !customPath.isBlank()) {
|
||||
String p = customPath.trim();
|
||||
if (!p.startsWith("/") || p.contains("|") || p.contains(":")
|
||||
|| !catalog.servablePath(site.id(), p)) {
|
||||
throw new IllegalArgumentException("customPath");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Populates the editor model, including the reverse advisory (which pages own this entry's URLs). */
|
||||
private void editorModel(Model model, SiteView site, BlogEntry entry, Map<String, String> bodies,
|
||||
boolean creating) {
|
||||
List<String> shadowedBy = new ArrayList<>();
|
||||
if (!creating) {
|
||||
for (Locale locale : site.locales()) {
|
||||
String lang = locale.getLanguage();
|
||||
// The REAL per-language URL (localized slug when set) — mirrors routing's own semantics.
|
||||
String path = source.publicPath(site.id(), entry, lang);
|
||||
catalog.pageAt(site.id(), path, locale)
|
||||
.ifPresent(slug -> shadowedBy.add(slug + " (" + lang + ")"));
|
||||
}
|
||||
}
|
||||
// Thymeleaf trap: a literal containing TWO '__' sequences inside a th.xml expression trips Thymeleaf's
|
||||
// __…__ preprocessing — so the form action (two '/__admin' literals in a ternary) is computed HERE and
|
||||
// passed as a plain model value the template reads with one ${formAction}.
|
||||
model.addAttribute("formAction", creating ? "/__admin/blog/create" : "/__admin/blog/" + entry.id());
|
||||
model.addAttribute("entry", entry);
|
||||
model.addAttribute("bodies", bodies);
|
||||
model.addAttribute("creating", creating);
|
||||
model.addAttribute("shadowedBy", shadowedBy);
|
||||
model.addAttribute("siteLocaleTags",
|
||||
site.locales().stream().map(Locale::getLanguage).toList());
|
||||
model.addAttribute("defaultLocaleTag", site.defaultLocale().getLanguage());
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "blog.admin.title");
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/blog/admin-edit");
|
||||
}
|
||||
|
||||
private static Map<String, String> perLang(SiteView site, MultiValueMap<String, String> params, String prefix) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (Locale locale : site.locales()) {
|
||||
String lang = locale.getLanguage();
|
||||
String value = first(params, prefix + lang);
|
||||
if (value != null && !value.isBlank()) {
|
||||
values.put(lang, value.trim());
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static String first(MultiValueMap<String, String> params, String name) {
|
||||
List<String> values = params.get(name);
|
||||
return (values == null || values.isEmpty()) ? null : values.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The site this console request is bound to. Empty on the application console (there is no tenancy there) —
|
||||
* a {@code 400}.
|
||||
*/
|
||||
private SiteView boundTenancy() {
|
||||
return request.site()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The blog plugin's Spring wiring — the {@code mainClass} the host registers before context refresh. Beans are wired
|
||||
* EXPLICITLY (never {@code @ComponentScan}), and every collaborator is a Runway SPI service the kernel provides:
|
||||
* <ul>
|
||||
* <li>{@link PluginSettings}, {@link PluginSiteFiles} and {@link ContentChanges} are <b>plugin-scoped</b> — the
|
||||
* kernel binds each to this plugin because the injecting class ({@code BlogConfig}) comes from this plugin's
|
||||
* jar, so they reach only {@code sites/<id>/plugins/blog.yml}, {@code sites/<id>/plugins/blog/} and this
|
||||
* plugin's own content source;</li>
|
||||
* <li>{@link ContentCatalogView}, {@link RequestContext} and {@link Messages} are kernel singletons.</li>
|
||||
* </ul>
|
||||
* The {@link BlogContentSource} bean is collected twice by type: as a {@link ContentSource} (routing, sitemap and
|
||||
* llms.txt, URL maps and search light up with zero further wiring) and as a {@link SiteEventListener} (its index
|
||||
* invalidation). The controller carries {@code @ConsoleScreen}, so the kernel renders it inside the operator shell.
|
||||
* Every bean name starts with the plugin id ({@code blog…}) — the kernel's bean-name rule.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class BlogConfig {
|
||||
|
||||
@Bean
|
||||
public BlogStore blogStore(PluginSiteFiles files) {
|
||||
return new BlogStore(files);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BlogContentSource blogContentSource(BlogStore blogStore, PluginSettings settings,
|
||||
ContentCatalogView catalog) {
|
||||
return new BlogContentSource(blogStore, settings, catalog);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BlogAdminController blogAdminController(RequestContext request, BlogStore blogStore,
|
||||
BlogContentSource blogContentSource,
|
||||
ContentCatalogView catalog, ContentChanges changes,
|
||||
Messages messages) {
|
||||
return new BlogAdminController(request, blogStore, blogContentSource, catalog, changes, messages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SettingsChange;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import org.commonmark.parser.Parser;
|
||||
import org.commonmark.renderer.html.HtmlRenderer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The blog as a kernel {@link ContentSource}: entries become first-class virtual pages — routed through the
|
||||
* full locale-dispatch ladder, rendered in the tenant's master chrome around this plugin's own body template,
|
||||
* listed in sitemap.xml/llms.txt with {@code hreflang} + {@code <lastmod>}, indexed by search, and linkable as
|
||||
* {@code ${urls['blog:<id>']}} — all host-provided; this class only answers the contract questions.
|
||||
*
|
||||
* <h2>The contract, honored</h2>
|
||||
* <ul>
|
||||
* <li>{@link #enumerate}: published entries only, metadata-only ({@link BlogStore#list} reads
|
||||
* {@code entry.yml} files, never a body), each with {@code updatedAt} from file times, cached until an
|
||||
* announced change: a console save moves the render ETag with no explicit bump; a body edited on disk
|
||||
* is served at once but under the OLD ETag until a site reload (docs/BLOG-PLUGIN.md §3).</li>
|
||||
* <li>{@link #resolve}: an O(1) probe of a per-site {@code path|lang → id} index (printable {@code |}),
|
||||
* rebuilt lazily after any invalidation — required because {@code content.arbitrary-paths} makes this
|
||||
* source run on <b>every</b> routing miss of an enabled site.</li>
|
||||
* <li>{@link #body}: Markdown → HTML via the bundled commonmark, fetched only for an actual 200 render.
|
||||
* Entry Markdown is operator-authored, first-party trusted content (raw HTML passes through, exactly as
|
||||
* a page author may write markup).</li>
|
||||
* <li>{@link #indexableText}: the same rendered HTML, for search.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Index invalidation: a SOURCE-phase {@link SiteEventListener}</h2>
|
||||
* The console announces every mutation through {@code ContentChanges.changed}; the kernel delivers it back here as
|
||||
* a {@code CONTENT} {@link CatalogChange} for this source's key, and this class drops the site's index. A site
|
||||
* lifecycle event drops it too (a <b>backup restore</b> replaces the entry files wholesale), and so does a save of
|
||||
* this plugin's own settings (a prefix change re-keys every URL). Running in the {@link Phase#SOURCE SOURCE} phase
|
||||
* is what keeps consumers honest: the kernel delivers every SOURCE listener first, evicts its content listing once
|
||||
* more, and only then lets sitemap and search consumers re-read — so none of them can rebuild from this source's
|
||||
* stale index. With clustering ON, the kernel relays the change to every node and delivers it there too
|
||||
* ({@code local == false}), so every node's index converges.
|
||||
*/
|
||||
public class BlogContentSource implements ContentSource, SiteEventListener {
|
||||
|
||||
public static final String KEY = "blog";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BlogContentSource.class);
|
||||
|
||||
private final BlogStore store;
|
||||
private final PluginSettings settings;
|
||||
private final ContentCatalogView catalog;
|
||||
private final Parser markdown = Parser.builder().build();
|
||||
private final HtmlRenderer html = HtmlRenderer.builder().build();
|
||||
|
||||
/** Per-site URL index: {@code path|lang → entryId}; dropped on any content/config/site change. */
|
||||
private final ConcurrentMap<String, Map<String, String>> index = new ConcurrentHashMap<>();
|
||||
/** Per-site enumerated refs — the metadata cache behind {@link #enumerate}, dropped by the SAME events, so
|
||||
* the per-render urlMap and per-request sitemap don't re-read the entries tree every time. */
|
||||
private final ConcurrentMap<String, List<ContentRef>> refs = new ConcurrentHashMap<>();
|
||||
|
||||
public BlogContentSource(BlogStore store, PluginSettings settings, ContentCatalogView catalog) {
|
||||
this.store = store;
|
||||
this.settings = settings;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return KEY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
// Custom paths escape the prefix; indexable-text opts this source into the search integration.
|
||||
return Capabilities.of(CAP_ARBITRARY_PATHS, CAP_INDEXABLE_TEXT);
|
||||
}
|
||||
|
||||
/** The site's effective settings — the one place the source and the console read them. */
|
||||
public BlogSettings settings(String siteId) {
|
||||
return BlogSettings.of(settings, catalog, siteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry's indexable material for {@code locale}: the Markdown body rendered to HTML — the SAME
|
||||
* transform the {@link #body} render uses. Engines strip <em>HTML</em> markup (they were built for page
|
||||
* HTML bodies), so handing them the rendered HTML yields clean prose in the index and in result snippets;
|
||||
* handing them the raw Markdown would leak {@code ## heading}, {@code **bold**} and {@code [text](url)}
|
||||
* link syntax straight into the terms and the visible snippet. Empty when the entry has no body for this
|
||||
* locale.
|
||||
*/
|
||||
@Override
|
||||
public String indexableText(SiteView site, String id, Locale locale) {
|
||||
String source = store.readBody(site.id(), id, locale.getLanguage());
|
||||
return source.isEmpty() ? "" : html.render(markdown.parse(source));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ContentRef> enumerate(SiteView site) {
|
||||
BlogSettings current = settings(site.id());
|
||||
if (!current.enabled()) {
|
||||
return List.of();
|
||||
}
|
||||
return refs.computeIfAbsent(site.id(), siteId -> {
|
||||
List<ContentRef> out = new ArrayList<>();
|
||||
for (BlogEntry entry : store.list(siteId)) {
|
||||
if (entry.published()) {
|
||||
out.add(toRef(entry, current));
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ContentRef> resolve(SiteView site, String path, Locale locale) {
|
||||
String id = index.computeIfAbsent(site.id(), sid -> buildIndex(site))
|
||||
.get(path + '|' + locale.getLanguage());
|
||||
if (id == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// Answer from the SAME cached refs the index was built from (one settings read, no torn view).
|
||||
for (ContentRef ref : enumerate(site)) {
|
||||
if (ref.id().equals(id)) {
|
||||
return Optional.of(ref);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContentBody body(SiteView site, String id, Locale locale) {
|
||||
String source = store.readBody(site.id(), id, locale.getLanguage());
|
||||
if (source.isBlank()) {
|
||||
return ContentBody.empty();
|
||||
}
|
||||
// Editorial metadata the body template may render. Absent keys are simply not put, so a template can
|
||||
// test for presence — an entry with no byline must render no byline, not an empty one.
|
||||
Map<String, String> attributes = new LinkedHashMap<>();
|
||||
store.read(site.id(), id).ifPresent(entry -> {
|
||||
if (entry.publishedOn() != null) {
|
||||
attributes.put("publishedOn", entry.publishedOn());
|
||||
}
|
||||
if (entry.author() != null) {
|
||||
attributes.put("author", entry.author());
|
||||
}
|
||||
});
|
||||
return new ContentBody(html.render(markdown.parse(source)), attributes);
|
||||
}
|
||||
|
||||
// --- invalidation (SiteEventListener, SOURCE phase) --------------------------------------------------------
|
||||
|
||||
/** {@link Phase#SOURCE}: this source's own index must be dropped before any consumer re-reads the listing. */
|
||||
@Override
|
||||
public Phase phase() {
|
||||
return Phase.SOURCE;
|
||||
}
|
||||
|
||||
/** Any lifecycle event — including a backup restore, which replaced the entry files wholesale. */
|
||||
@Override
|
||||
public void onSiteLifecycle(SiteLifecycleEvent event) {
|
||||
drop(event.siteId());
|
||||
}
|
||||
|
||||
/** This plugin's own settings were saved: a prefix or template change re-keys every URL and every ref. */
|
||||
@Override
|
||||
public void onSettingsChanged(SettingsChange change) {
|
||||
drop(change.siteId());
|
||||
}
|
||||
|
||||
/** This source's own content changed (announced by the console, on this node or a peer). */
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
if (change.cause() == CatalogChange.Cause.CONTENT && KEY.equals(change.sourceKey())) {
|
||||
drop(change.siteId());
|
||||
}
|
||||
}
|
||||
|
||||
private void drop(String siteId) {
|
||||
index.remove(siteId);
|
||||
refs.remove(siteId);
|
||||
}
|
||||
|
||||
// --- mapping -----------------------------------------------------------------------------------------------
|
||||
|
||||
/** Projects an entry onto the content noun under the site's current prefix settings. */
|
||||
private ContentRef toRef(BlogEntry entry, BlogSettings current) {
|
||||
String defaultPath = entry.customPath() != null ? entry.customPath()
|
||||
: current.pathFor(entry.effectiveSlug());
|
||||
Map<String, String> localizedPaths = new LinkedHashMap<>();
|
||||
entry.localizedSlugs().forEach((lang, slug) ->
|
||||
localizedPaths.put(lang, current.pathFor(slug)));
|
||||
List<Locale> locales = entry.locales().stream().map(Locale::forLanguageTag).toList();
|
||||
return new ContentRef(entry.id(), defaultPath, localizedPaths, locales, entry.title(),
|
||||
entry.description(), null, current.bodyTemplate(), entry.published(), entry.updatedAt(),
|
||||
false, null, null, Map.of(), entry.author(), publishedAt(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry's own {@code publishedOn} as an instant, for {@link ContentRef#publishedAt()} — so each post
|
||||
* carries ITS OWN publication date across the SPI boundary.
|
||||
*
|
||||
* <p>This is what makes per-post dates truthful. Without it, the discoverability plugin would have to take
|
||||
* {@code datePublished} from the per-site {@code content.schema} block, which matches by path prefix — so ONE
|
||||
* {@code /blog/*} entry would cover every post. A site's only honest options would be to emit no dates at all,
|
||||
* or to assert a single date identically on every post: a statement false of nearly every page carrying it,
|
||||
* and exactly the kind of untrue markup structured-data policy prohibits.
|
||||
*
|
||||
* <p>Interpreted at <b>midnight UTC</b> on the stated day, matching how the kernel's page editor parses its
|
||||
* own date field, so a blog entry and a page dated the same day produce the same instant.
|
||||
*
|
||||
* <p>The entry's {@code author} travels the same way, so a post is attributed to whoever
|
||||
* actually wrote it rather than to one name shared by every post on the site.
|
||||
*
|
||||
* <p>An unparseable value yields {@code null} — no date. {@code publishedOn} is free-form display text on
|
||||
* the entry, so it can legitimately hold something that is not a date; asserting a wrong
|
||||
* {@code datePublished} would be worse than asserting none, because a consumer is told to trust it.
|
||||
*/
|
||||
private static Instant publishedAt(BlogEntry entry) {
|
||||
String raw = entry.publishedOn();
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(raw.trim()).atStartOfDay(ZoneOffset.UTC).toInstant();
|
||||
} catch (DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One pass over the published refs → {@code path|lang → id} for O(1) miss-time resolution. Keys the FULL
|
||||
* union of the site's locales plus the default (parity with the SPI's default {@code resolve}, which
|
||||
* matches {@code pathFor(L)} for any lookup locale), with a locale's OWN localized slug taking precedence
|
||||
* over another entry's fallback claim. Two entries claiming one (path, lang) is a same-source collision
|
||||
* the kernel cannot see — logged loudly here; the deterministic winner is the explicit/localized claim,
|
||||
* else first-listed.
|
||||
*/
|
||||
private Map<String, String> buildIndex(SiteView site) {
|
||||
Map<String, String> paths = new HashMap<>();
|
||||
Locale siteDefault = site.defaultLocale();
|
||||
LinkedHashSet<Locale> lookupLocales = new LinkedHashSet<>();
|
||||
lookupLocales.add(siteDefault);
|
||||
lookupLocales.addAll(site.locales());
|
||||
for (ContentRef ref : enumerate(site)) {
|
||||
for (Locale locale : lookupLocales) {
|
||||
String key = ref.pathFor(locale) + '|' + locale.getLanguage();
|
||||
boolean explicit = ref.localizedPaths().containsKey(locale.getLanguage())
|
||||
|| ref.hasLocale(locale, siteDefault);
|
||||
String prior = explicit ? paths.put(key, ref.id()) : paths.putIfAbsent(key, ref.id());
|
||||
if (prior != null && !prior.equals(ref.id())) {
|
||||
log.warn("blog entries '{}' and '{}' (site '{}') both claim '{}' — '{}' wins; give one a "
|
||||
+ "different slug", prior, ref.id(), site.id(), key,
|
||||
explicit ? ref.id() : prior);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Map.copyOf(paths);
|
||||
}
|
||||
|
||||
/** For the console: the entry's public path in the site's default URL space (list-screen links). */
|
||||
public String publicPath(String siteId, BlogEntry entry) {
|
||||
return publicPath(siteId, entry, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry's public path for one language ({@code null} = the default URL space): the localized slug when
|
||||
* that language has one, else the default path — the exact semantics {@code toRef}/routing use, so the
|
||||
* console's reverse advisory checks the REAL per-language URLs.
|
||||
*/
|
||||
public String publicPath(String siteId, BlogEntry entry, String lang) {
|
||||
BlogSettings current = settings(siteId);
|
||||
if (lang != null && entry.localizedSlugs().containsKey(lang)) {
|
||||
return current.pathFor(entry.localizedSlugs().get(lang));
|
||||
}
|
||||
return entry.customPath() != null ? entry.customPath()
|
||||
: current.pathFor(entry.effectiveSlug());
|
||||
}
|
||||
|
||||
/** Test hook: the index currently cached for a site (null = not built). */
|
||||
Map<String, String> cachedIndex(String siteId) {
|
||||
return index.get(siteId);
|
||||
}
|
||||
|
||||
/** Test hook: the refs currently cached for a site (null = not built). */
|
||||
List<ContentRef> cachedRefs(String siteId) {
|
||||
return refs.get(siteId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* One blog entry's <b>metadata</b> — the {@code entry.yml} document under
|
||||
* {@code sites/<siteId>/plugins/blog/entries/<id>/}. Bodies live beside it as {@code body-<lang>.md} files
|
||||
* (one per language), so enumerating entries never reads a body — the ContentSource contract's
|
||||
* metadata/body split, made trivially honest by the file layout.
|
||||
*
|
||||
* <p>URLs: the entry serves at {@code <prefix>/<slug>} (the per-tenant {@code prefix} setting), with optional
|
||||
* per-language slug overrides ({@code localizedSlugs}) and an optional <b>custom absolute path</b>
|
||||
* ({@code customPath}, e.g. {@code /announcing-v2}) that replaces the prefixed default-locale URL entirely
|
||||
* (the reason this plugin declares {@code content.arbitrary-paths}).
|
||||
*
|
||||
* @param id the entry's stable identity — its folder name (never part of the YAML; re-applied
|
||||
* from the folder on read, like a page's slug)
|
||||
* @param title per-language titles ({@code lang → text})
|
||||
* @param description per-language descriptions
|
||||
* @param locales the language codes this entry is published in (empty ⇒ site default only)
|
||||
* @param slug the URL slug under the blog prefix ({@code null} ⇒ the id)
|
||||
* @param localizedSlugs per-language slug overrides ({@code lang → slug})
|
||||
* @param customPath an absolute path override for the default locale ({@code /…}), or {@code null}
|
||||
* @param published whether the entry is publicly visible
|
||||
* @param publishedOn the display publication date (ISO {@code yyyy-MM-dd}), or {@code null}
|
||||
* @param author display name credited for this entry, or {@code null} when unattributed. Free text
|
||||
* on purpose — a real identity model (accounts, profiles, affiliations) is a much
|
||||
* larger design, and blocking bylines on it would leave every entry unattributable
|
||||
* meanwhile. Matches the kernel's page-level author so the two cannot drift
|
||||
* @param updatedAt newest mtime of the entry's files — derived on read, never serialized; drives the
|
||||
* sitemap {@code <lastmod>} AND the render ETag (re-read only after an announced change)
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record BlogEntry(String id, Map<String, String> title, Map<String, String> description,
|
||||
List<String> locales, String slug, Map<String, String> localizedSlugs,
|
||||
String customPath, boolean published, String publishedOn, String author,
|
||||
@JsonIgnore Instant updatedAt) {
|
||||
|
||||
public BlogEntry {
|
||||
title = normalize(title);
|
||||
description = normalize(description);
|
||||
locales = (locales == null) ? List.of() : List.copyOf(locales);
|
||||
localizedSlugs = normalize(localizedSlugs);
|
||||
slug = blankToNull(slug);
|
||||
customPath = blankToNull(customPath);
|
||||
publishedOn = blankToNull(publishedOn);
|
||||
// Blank == unattributed: the editor posts "" for an untouched field, and an empty byline must not
|
||||
// serialize into entry.yml or render as an empty author element.
|
||||
author = blankToNull(author);
|
||||
}
|
||||
|
||||
/** This entry with its stable id applied (the folder name — never stored inside the YAML). */
|
||||
public BlogEntry withId(String id) {
|
||||
return new BlogEntry(id, title, description, locales, slug, localizedSlugs, customPath, published,
|
||||
publishedOn, author, updatedAt);
|
||||
}
|
||||
|
||||
/** This entry with the derived {@code updatedAt} applied (from the entry files' mtimes). */
|
||||
public BlogEntry withUpdatedAt(Instant updatedAt) {
|
||||
return new BlogEntry(id, title, description, locales, slug, localizedSlugs, customPath, published,
|
||||
publishedOn, author, updatedAt);
|
||||
}
|
||||
|
||||
/** The form serialized to {@code entry.yml}: no id (the folder carries it), no derived fields. */
|
||||
public BlogEntry forStorage() {
|
||||
return new BlogEntry(null, title, description, locales, slug, localizedSlugs, customPath, published,
|
||||
publishedOn, author, null);
|
||||
}
|
||||
|
||||
/** The effective URL slug under the blog prefix: the explicit {@link #slug}, else the id. */
|
||||
@JsonIgnore
|
||||
public String effectiveSlug() {
|
||||
return slug != null ? slug : id;
|
||||
}
|
||||
|
||||
private static Map<String, String> normalize(Map<String, String> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> clean = new LinkedHashMap<>();
|
||||
raw.forEach((k, v) -> {
|
||||
if (k != null && !k.isBlank() && v != null && !v.isBlank()) {
|
||||
clean.put(k.trim(), v.trim());
|
||||
}
|
||||
});
|
||||
return java.util.Collections.unmodifiableMap(clean);
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* The blog's effective per-site settings — typed reads over {@link PluginSettings} (live: a console save is visible
|
||||
* on the next read; an absent settings file means the descriptor's defaults). Kept as one value object so the
|
||||
* source, the console and the templates agree on defaults in exactly one place.
|
||||
*
|
||||
* @param enabled whether the blog serves at all on this site
|
||||
* @param prefix the URL prefix entries serve under (normalized: leading {@code /}, no trailing {@code /})
|
||||
* @param template the entry body template name within this plugin's own namespace (the operator's pick)
|
||||
*/
|
||||
public record BlogSettings(boolean enabled, String prefix, String template) {
|
||||
|
||||
public static final String PLUGIN_ID = "blog";
|
||||
|
||||
static final String DEFAULT_PREFIX = "/blog";
|
||||
static final String DEFAULT_TEMPLATE = "entry-classic";
|
||||
static final String MINIMAL_TEMPLATE = "entry-minimal";
|
||||
|
||||
/**
|
||||
* The site's effective settings (descriptor defaults: enabled, {@code /blog}, {@code entry-classic}).
|
||||
*
|
||||
* <p>The prefix is checked with {@link ContentCatalogView#servablePath}: an unsafe or reserved prefix
|
||||
* ({@code /__x}, {@code /app}, {@code /actuator}, a path with {@code |} or {@code ..}) would make every entry
|
||||
* path fail the kernel's fail-closed re-filter and silently vanish from routing and listings, so it falls back
|
||||
* to {@code /blog} instead. The question asked is "would the kernel serve an entry under this prefix?", so the
|
||||
* probe is a child path of the prefix — that is where entries live.
|
||||
*
|
||||
* @param settings this plugin's per-site settings
|
||||
* @param catalog the kernel's content surface (for its path rule; no content source is consulted)
|
||||
* @param siteId the site
|
||||
* @return the effective settings (never {@code null})
|
||||
*/
|
||||
public static BlogSettings of(PluginSettings settings, ContentCatalogView catalog, String siteId) {
|
||||
SettingsView view = settings.site(siteId);
|
||||
boolean enabled = view.bool("enabled", true);
|
||||
String prefix = normalizePrefix(view.string("prefix", DEFAULT_PREFIX));
|
||||
// Fail closed on the template name: it becomes part of a __plugin__/blog/<name> template lookup.
|
||||
String template = MINIMAL_TEMPLATE.equals(view.string("template", DEFAULT_TEMPLATE))
|
||||
? MINIMAL_TEMPLATE : DEFAULT_TEMPLATE;
|
||||
if (!catalog.servablePath(siteId, join(prefix, "x"))) {
|
||||
prefix = DEFAULT_PREFIX;
|
||||
}
|
||||
return new BlogSettings(enabled, prefix, template);
|
||||
}
|
||||
|
||||
/** The full logical body-template name the kernel resolves and namespace-validates. */
|
||||
public String bodyTemplate() {
|
||||
return "__plugin__/" + PLUGIN_ID + "/" + template;
|
||||
}
|
||||
|
||||
/** An entry's public path under this prefix — joined without doubling when the prefix is the root. */
|
||||
public String pathFor(String slug) {
|
||||
return join(prefix, slug);
|
||||
}
|
||||
|
||||
private static String join(String prefix, String slug) {
|
||||
return "/".equals(prefix) ? "/" + slug : prefix + "/" + slug;
|
||||
}
|
||||
|
||||
private static String normalizePrefix(String raw) {
|
||||
String p = raw.trim();
|
||||
if (!p.startsWith("/")) {
|
||||
p = "/" + p;
|
||||
}
|
||||
while (p.endsWith("/") && p.length() > 1) {
|
||||
p = p.substring(0, p.length() - 1);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.FileEntry;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import tools.jackson.core.StreamReadFeature;
|
||||
import tools.jackson.core.StreamWriteFeature;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
/**
|
||||
* The blog's per-site file store, over the kernel's {@link PluginSiteFiles} (this plugin's own subtree,
|
||||
* {@code sites/<siteId>/plugins/blog/}): {@code entries/<entryId>/entry.yml} (metadata) +
|
||||
* {@code entries/<entryId>/body-<lang>.md} (one Markdown body per language). The layout has not changed across releases,
|
||||
* so existing entries load unchanged. Everything lives in the site's own folder, so a full backup carries the whole
|
||||
* blog with no {@code BackupParticipant}, and the kernel confines every path to the subtree (symbolic links
|
||||
* included) — the store cannot reach another plugin's data or another site.
|
||||
*
|
||||
* <p><b>Metadata/body split on disk</b> is what makes the ContentSource contract trivially honest: {@link #list}
|
||||
* reads only {@code entry.yml} files (plus file times for {@code updatedAt}); {@link #readBody} is called only when a
|
||||
* body is actually rendered or indexed.
|
||||
*
|
||||
* <p>Ids and language codes are validated against a strict grammar before ever forming a path — an id is a folder
|
||||
* name, a language code a file-name fragment; neither may traverse (the kernel would refuse it anyway).
|
||||
*
|
||||
* <p><b>Concurrency.</b> Each file write is atomic (the kernel writes a temporary file and renames it), so a public
|
||||
* reader — the sitemap, a routing miss — never observes a half-written {@code entry.yml}. Two operators saving the
|
||||
* same entry at once: the last save wins.
|
||||
*
|
||||
* <p><b>Freshness.</b> The store announces nothing; the console calls {@code ContentChanges.changed} after every
|
||||
* mutation.
|
||||
*/
|
||||
public class BlogStore {
|
||||
|
||||
private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,98}[a-z0-9]|[a-z0-9]");
|
||||
private static final Pattern SAFE_LANG = Pattern.compile("[a-z]{2,8}");
|
||||
/** The entries folder, relative to this plugin's per-site subtree. */
|
||||
static final String ENTRIES = "entries";
|
||||
static final String METADATA = "entry.yml";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BlogStore.class);
|
||||
|
||||
/**
|
||||
* The YAML codec: <b>lenient</b> on read, so a hand-written {@code entry.yml} that omits {@code published:} or
|
||||
* carries a key this version does not know still loads (it defaults instead of failing) — and writes an entry back
|
||||
* byte for byte ({@code BlogStoreTest} proves it on the fixture entries). Streams are never auto-closed: the
|
||||
* caller owns them.
|
||||
*/
|
||||
private static final ObjectMapper YAML = YAMLMapper.builder()
|
||||
.disable(StreamWriteFeature.AUTO_CLOSE_TARGET)
|
||||
.disable(StreamReadFeature.AUTO_CLOSE_SOURCE)
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
|
||||
.build();
|
||||
|
||||
private final PluginSiteFiles files;
|
||||
|
||||
public BlogStore(PluginSiteFiles files) {
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every entry of the site (published and not), newest publication date first, with {@code updatedAt} derived
|
||||
* from file times. One unreadable entry is skipped with a WARN and never blanks the others.
|
||||
*
|
||||
* @throws UncheckedIOException if the entries folder itself cannot be listed
|
||||
*/
|
||||
public List<BlogEntry> list(String siteId) {
|
||||
List<FileEntry> dirs;
|
||||
try {
|
||||
dirs = files.list(siteId, ENTRIES);
|
||||
} catch (IOException ex) {
|
||||
throw new UncheckedIOException("listing blog entries of " + siteId, ex);
|
||||
}
|
||||
List<BlogEntry> out = new ArrayList<>();
|
||||
for (FileEntry dir : dirs) {
|
||||
String id = dir.name();
|
||||
if (!dir.directory() || !SAFE_ID.matcher(id).matches()) {
|
||||
continue;
|
||||
}
|
||||
// Per-ENTRY containment: one corrupt/hand-mangled entry.yml must never blank the whole blog
|
||||
// (the corpus-level backstop upstream would otherwise drop the entire source).
|
||||
try {
|
||||
read(siteId, id).ifPresent(out::add);
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("skipping unreadable blog entry {}/{}: {}", siteId, id, ex.toString());
|
||||
}
|
||||
}
|
||||
out.sort((a, b) -> {
|
||||
// Newest first for the console: by publishedOn (desc, nulls last), then id for stability.
|
||||
String pa = a.publishedOn() == null ? "" : a.publishedOn();
|
||||
String pb = b.publishedOn() == null ? "" : b.publishedOn();
|
||||
int byDate = pb.compareTo(pa);
|
||||
return byDate != 0 ? byDate : a.id().compareTo(b.id());
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One entry by id, or empty (also empty for an unsafe id — never a path probe — and for a malformed
|
||||
* {@code entry.yml}, which is logged).
|
||||
*
|
||||
* @throws UncheckedIOException if the file exists but cannot be read
|
||||
*/
|
||||
public Optional<BlogEntry> read(String siteId, String entryId) {
|
||||
if (!SAFE_ID.matcher(entryId).matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String path = metadataPath(entryId);
|
||||
Optional<String> text;
|
||||
try {
|
||||
text = files.readText(siteId, path);
|
||||
} catch (IOException ex) {
|
||||
throw new UncheckedIOException("reading blog entry " + siteId + "/" + entryId, ex);
|
||||
}
|
||||
if (text.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
BlogEntry parsed;
|
||||
try {
|
||||
parsed = YAML.readValue(text.get(), BlogEntry.class);
|
||||
} catch (RuntimeException parseFailure) {
|
||||
// A malformed file is THIS entry's problem, never the corpus's: absent + a WARN naming the file.
|
||||
log.warn("unparseable blog entry {}/{} — treated as absent: {}", siteId, path, parseFailure.toString());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (parsed == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(parsed.withId(entryId).withUpdatedAt(newestModification(siteId, entryId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or replaces an entry's metadata, and any bodies given ({@code lang → markdown}; a {@code null} body
|
||||
* map leaves bodies untouched, a blank body deletes that language's file). The caller announces the change
|
||||
* afterwards — the store never does.
|
||||
*
|
||||
* @throws IllegalArgumentException for an unsafe id or language code (nothing is written), or a body over the
|
||||
* kernel's write cap
|
||||
* @throws IOException when a write fails (for example, the site folder does not exist)
|
||||
*/
|
||||
public void save(String siteId, BlogEntry entry, Map<String, String> bodies) throws IOException {
|
||||
requireSafeId(entry.id());
|
||||
if (bodies != null) {
|
||||
bodies.keySet().forEach(BlogStore::requireSafeLang); // validate ALL before writing ANY
|
||||
}
|
||||
files.writeText(siteId, metadataPath(entry.id()), YAML.writeValueAsString(entry.forStorage()));
|
||||
if (bodies != null) {
|
||||
for (Map.Entry<String, String> body : bodies.entrySet()) {
|
||||
String path = bodyPath(entry.id(), body.getKey());
|
||||
if (body.getValue() == null || body.getValue().isBlank()) {
|
||||
files.delete(siteId, path);
|
||||
} else {
|
||||
files.writeText(siteId, path, body.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an entry (its folder and every file in it; symbolic links are removed, never followed). Unknown and
|
||||
* unsafe ids are a no-op.
|
||||
*/
|
||||
public void delete(String siteId, String entryId) throws IOException {
|
||||
if (!SAFE_ID.matcher(entryId).matches()) {
|
||||
return;
|
||||
}
|
||||
files.deleteTree(siteId, ENTRIES + "/" + entryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry's Markdown body for {@code lang}, or {@code ""} when that language has none (or the id or language
|
||||
* is unsafe).
|
||||
*
|
||||
* @throws UncheckedIOException if the body exists but cannot be read (including one over the kernel's cap)
|
||||
*/
|
||||
public String readBody(String siteId, String entryId, String lang) {
|
||||
if (!SAFE_ID.matcher(entryId).matches() || !SAFE_LANG.matcher(lang).matches()) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return files.readText(siteId, bodyPath(entryId, lang)).orElse("");
|
||||
} catch (IOException ex) {
|
||||
throw new UncheckedIOException("reading blog body " + siteId + "/" + entryId + "/" + lang, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/** The languages that have a body file for {@code entryId}, sorted. */
|
||||
public List<String> bodyLangs(String siteId, String entryId) {
|
||||
if (!SAFE_ID.matcher(entryId).matches()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> langs = new ArrayList<>();
|
||||
for (FileEntry file : entryFiles(siteId, entryId)) {
|
||||
String name = file.name();
|
||||
if (!file.directory() && name.startsWith("body-") && name.endsWith(".md")) {
|
||||
langs.add(name.substring("body-".length(), name.length() - ".md".length()));
|
||||
}
|
||||
}
|
||||
langs.sort(String::compareTo);
|
||||
return langs;
|
||||
}
|
||||
|
||||
static void requireSafeId(String id) {
|
||||
if (id == null || !SAFE_ID.matcher(id).matches()) {
|
||||
throw new IllegalArgumentException("invalid blog entry id: '" + id + "' (lowercase letters, "
|
||||
+ "digits and hyphens; no ':' — the composite blog:<id> identity must stay unambiguous)");
|
||||
}
|
||||
}
|
||||
|
||||
private static String requireSafeLang(String lang) {
|
||||
if (lang == null || !SAFE_LANG.matcher(lang).matches()) {
|
||||
throw new IllegalArgumentException("invalid language code: '" + lang + "'");
|
||||
}
|
||||
return lang;
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest modification time of the entry's files — {@code updatedAt}, which drives the sitemap
|
||||
* {@code <lastmod>} and the render {@code ETag} once the source re-lists (after an announced change).
|
||||
* {@code null} when no time is known.
|
||||
*/
|
||||
private Instant newestModification(String siteId, String entryId) {
|
||||
Instant newest = null;
|
||||
for (FileEntry file : entryFiles(siteId, entryId)) {
|
||||
Instant at = file.lastModified();
|
||||
if (!file.directory() && !Instant.EPOCH.equals(at) && (newest == null || at.isAfter(newest))) {
|
||||
newest = at;
|
||||
}
|
||||
}
|
||||
return newest;
|
||||
}
|
||||
|
||||
private List<FileEntry> entryFiles(String siteId, String entryId) {
|
||||
try {
|
||||
return files.list(siteId, ENTRIES + "/" + entryId);
|
||||
} catch (IOException ex) {
|
||||
// An unreadable folder contributes no file times and no body languages; the entry still lists.
|
||||
log.debug("listing blog entry {}/{} failed: {}", siteId, entryId, ex.toString());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static String metadataPath(String entryId) {
|
||||
return ENTRIES + "/" + entryId + "/" + METADATA;
|
||||
}
|
||||
|
||||
private static String bodyPath(String entryId, String lang) {
|
||||
return ENTRIES + "/" + entryId + "/body-" + requireSafeLang(lang) + ".md";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.ExtendedModelMap;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;
|
||||
|
||||
/**
|
||||
* {@link BlogAdminController} over SPI fakes: the form → entry parse (per-language fields, the default-language slug
|
||||
* as base slug, published checkbox), the {@code ContentChanges} announcement after every mutation (the platform's
|
||||
* freshness rule — and, delivered back, the source's own index drop), the reverse advisory through
|
||||
* {@code ContentCatalogView.pageAt}, the bound tenancy through {@code RequestContext}, console messages through
|
||||
* {@code Messages}, and the console-screen contract (annotation, paths, POST-only mutations, the permission gate).
|
||||
*/
|
||||
class BlogAdminControllerTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
|
||||
private record Fixture(BlogAdminController controller, BlogStore store, EventDispatch events,
|
||||
FakeContentCatalog catalog, BlogContentSource source) {
|
||||
}
|
||||
|
||||
private static Fixture fixture(Path tmp, boolean bound) throws IOException {
|
||||
Files.createDirectories(tmp.resolve("acme"));
|
||||
BlogStore store = new BlogStore(new TempDirSiteFiles(tmp, "blog"));
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().site("acme").route("/sitemap.xml");
|
||||
BlogContentSource source = new BlogContentSource(store, new FakePluginSettings(), catalog);
|
||||
EventDispatch events = new EventDispatch("blog", Set.of(BlogContentSource.KEY)).listener(source);
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", EN, List.of(EN, ES), null))
|
||||
.message("acme", "blog.flash.created", "Entrada creada.");
|
||||
if (bound) {
|
||||
kernel.current("acme");
|
||||
}
|
||||
BlogAdminController controller = new BlogAdminController(kernel, store, source, catalog, events, kernel);
|
||||
return new Fixture(controller, store, events, catalog, source);
|
||||
}
|
||||
|
||||
private static Fixture fixture(Path tmp) throws IOException {
|
||||
return fixture(tmp, true);
|
||||
}
|
||||
|
||||
private static MultiValueMap<String, String> form() {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("title_en", "My first post");
|
||||
params.add("title_es", "Mi primera entrada");
|
||||
params.add("description_en", "The very first.");
|
||||
params.add("slug_en", "first"); // the default language's slug = the base slug
|
||||
params.add("slug_es", "primera");
|
||||
params.add("body_en", "Hello **world**.");
|
||||
params.add("body_es", "Hola **mundo**.");
|
||||
params.add("locales_en", "on");
|
||||
params.add("locales_es", "on");
|
||||
params.add("published", "on");
|
||||
params.add("publishedOn", "2026-07-17");
|
||||
params.add("author", "Jane Doe");
|
||||
return params;
|
||||
}
|
||||
|
||||
private static List<String> announcedIds(Fixture f) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (CatalogChange c : f.events().announced()) {
|
||||
assertEquals(BlogContentSource.KEY, c.sourceKey(), "always this plugin's own source");
|
||||
assertEquals("acme", c.siteId(), "always the bound site");
|
||||
ids.add(c.id());
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createParsesTheFormAndAnnouncesTheChange(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
RedirectAttributesModelMap redirect = new RedirectAttributesModelMap();
|
||||
String view = f.controller().create("First-Post ", form(), new ExtendedModelMap(), redirect);
|
||||
assertEquals("redirect:/__admin/blog/first-post/edit", view, "the id is trimmed and lower-cased");
|
||||
|
||||
BlogEntry saved = f.store().read("acme", "first-post").orElseThrow();
|
||||
assertEquals("My first post", saved.title().get("en"));
|
||||
assertEquals("The very first.", saved.description().get("en"));
|
||||
assertEquals("first", saved.slug(), "the default language's slug field becomes the base slug");
|
||||
assertEquals(Map.of("es", "primera"), saved.localizedSlugs());
|
||||
assertEquals(List.of("en", "es"), saved.locales());
|
||||
assertTrue(saved.published());
|
||||
assertEquals("2026-07-17", saved.publishedOn());
|
||||
assertEquals("Jane Doe", saved.author());
|
||||
assertEquals("Hello **world**.", f.store().readBody("acme", "first-post", "en"));
|
||||
assertEquals("Hola **mundo**.", f.store().readBody("acme", "first-post", "es"));
|
||||
|
||||
assertEquals(List.of("first-post"), announcedIds(f), "one announcement, after the write");
|
||||
assertEquals("Entry created.", redirect.getFlashAttributes().get("flash"),
|
||||
"console words come from Messages.console (its fallback here)");
|
||||
assertTrue(f.events().failures().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAnnouncementReachesTheSourceSoTheNewEntryRoutesAtOnce(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
assertTrue(f.source().resolve(site, "/blog/first", EN).isEmpty(), "builds (and caches) an empty index");
|
||||
f.controller().create("first-post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap());
|
||||
assertEquals("first-post", f.source().resolve(site, "/blog/first", EN).orElseThrow().id(),
|
||||
"the source's SOURCE-phase listener dropped its stale index");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidIdReRendersTheEditorWithTheTypedStateNothingWritten(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
ExtendedModelMap model = new ExtendedModelMap();
|
||||
String view = f.controller().create("Bad:Id", form(), model, new RedirectAttributesModelMap());
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW, view, "failure RE-RENDERS the editor — never a blank form");
|
||||
assertNotNull(model.getAttribute("error"), "the error message is in the model");
|
||||
BlogEntry typed = (BlogEntry) model.getAttribute("entry");
|
||||
assertEquals("My first post", typed.title().get("en"), "everything the author typed is preserved");
|
||||
assertEquals("__plugin__/blog/admin-edit", model.getAttribute(ConsoleScreen.CONTENT_TEMPLATE));
|
||||
assertEquals(Boolean.TRUE, model.getAttribute("creating"));
|
||||
assertTrue(f.store().list("acme").isEmpty(), "nothing was written");
|
||||
assertTrue(f.events().announced().isEmpty(), "nothing was announced");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedAndDuplicateIdsAreRejected(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
for (String reserved : List.of("create", "new")) {
|
||||
ExtendedModelMap model = new ExtendedModelMap();
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW,
|
||||
f.controller().create(reserved, form(), model, new RedirectAttributesModelMap()));
|
||||
assertEquals("That id is reserved — pick another.", model.getAttribute("error"));
|
||||
assertTrue(f.store().read("acme", reserved).isEmpty(), reserved + " would collide with the route table");
|
||||
}
|
||||
f.controller().create("post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap());
|
||||
var other = form();
|
||||
other.set("title_en", "Another");
|
||||
ExtendedModelMap model = new ExtendedModelMap();
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW,
|
||||
f.controller().create("post", other, model, new RedirectAttributesModelMap()));
|
||||
assertEquals("An entry with that id already exists.", model.getAttribute("error"));
|
||||
assertEquals("My first post", f.store().read("acme", "post").orElseThrow().title().get("en"),
|
||||
"the existing entry is untouched");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsafeSlugOrCustomPathIsRejectedNotSilentlyDiscarded(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
var bad = form();
|
||||
bad.set("slug_es", "Bad Slug!");
|
||||
ExtendedModelMap model = new ExtendedModelMap();
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW, f.controller().create("post", bad, model,
|
||||
new RedirectAttributesModelMap()));
|
||||
assertTrue(String.valueOf(model.getAttribute("error")).contains("slug (es)"));
|
||||
assertTrue(f.store().read("acme", "post").isEmpty(), "an invalid slug never persists");
|
||||
|
||||
// Each of these would be dropped by the kernel's fail-closed re-filter (or is not even a path).
|
||||
for (String path : List.of("no-leading-slash", "/a|b", "/a:b", "/__admin/x", "/app/x", "/sitemap.xml",
|
||||
"/x/../y")) {
|
||||
var badPath = form();
|
||||
badPath.set("customPath", path);
|
||||
ExtendedModelMap m = new ExtendedModelMap();
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW,
|
||||
f.controller().create("post2", badPath, m, new RedirectAttributesModelMap()), path);
|
||||
assertTrue(String.valueOf(m.getAttribute("error")).contains("customPath"), path);
|
||||
assertTrue(f.store().read("acme", "post2").isEmpty(), path + ": an invalid custom path never persists");
|
||||
}
|
||||
var goodPath = form();
|
||||
goodPath.set("customPath", " /announcing-v2 ");
|
||||
f.controller().create("post3", goodPath, new ExtendedModelMap(), new RedirectAttributesModelMap());
|
||||
assertEquals("/announcing-v2", f.store().read("acme", "post3").orElseThrow().customPath());
|
||||
assertEquals(List.of("post3"), announcedIds(f), "only the valid save was announced");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFullLifecycleRoundTripsAndAnnouncesEveryMutation(@TempDir Path tmp) throws IOException {
|
||||
// create → update (slug change + published checkbox ABSENT = silent unpublish, the intended
|
||||
// full-state-form UX) → publish-toggle twice (ONLY the flag flips) → delete (folder gone).
|
||||
Fixture f = fixture(tmp);
|
||||
f.controller().create("post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap());
|
||||
|
||||
var update = form();
|
||||
update.set("slug_en", "renamed");
|
||||
update.remove("published");
|
||||
RedirectAttributesModelMap saved = new RedirectAttributesModelMap();
|
||||
assertEquals("redirect:/__admin/blog/post/edit", f.controller().update("post", update, saved));
|
||||
assertEquals("Saved.", saved.getFlashAttributes().get("flash"));
|
||||
BlogEntry updated = f.store().read("acme", "post").orElseThrow();
|
||||
assertEquals("renamed", updated.slug(), "the slug change persisted");
|
||||
assertFalse(updated.published(), "checkbox absent ⇒ unpublished (full-state form semantics)");
|
||||
assertEquals("Mi primera entrada", updated.title().get("es"), "other fields intact");
|
||||
|
||||
RedirectAttributesModelMap toggled = new RedirectAttributesModelMap();
|
||||
assertEquals("redirect:/__admin/blog", f.controller().togglePublished("post", toggled));
|
||||
assertEquals("Entry published.", toggled.getFlashAttributes().get("flash"));
|
||||
BlogEntry republished = f.store().read("acme", "post").orElseThrow();
|
||||
assertTrue(republished.published(), "toggle flips ONLY the flag");
|
||||
assertEquals("renamed", republished.slug(), "the positional rebuild kept every other field");
|
||||
assertEquals("2026-07-17", republished.publishedOn());
|
||||
RedirectAttributesModelMap untoggled = new RedirectAttributesModelMap();
|
||||
f.controller().togglePublished("post", untoggled);
|
||||
assertEquals("Entry unpublished.", untoggled.getFlashAttributes().get("flash"));
|
||||
assertFalse(f.store().read("acme", "post").orElseThrow().published());
|
||||
|
||||
RedirectAttributesModelMap deleted = new RedirectAttributesModelMap();
|
||||
assertEquals("redirect:/__admin/blog", f.controller().delete("post", deleted));
|
||||
assertEquals("Entry deleted.", deleted.getFlashAttributes().get("flash"));
|
||||
assertTrue(f.store().read("acme", "post").isEmpty(), "deleted");
|
||||
assertEquals(List.of("post", "post", "post", "post", "post"), announcedIds(f),
|
||||
"create, update, publish, unpublish, delete — each announced");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidUpdateFlashesTheErrorAndWritesNothing(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
f.controller().create("post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap());
|
||||
var bad = form();
|
||||
bad.set("customPath", "/__nope");
|
||||
bad.set("title_en", "Changed");
|
||||
RedirectAttributesModelMap redirect = new RedirectAttributesModelMap();
|
||||
assertEquals("redirect:/__admin/blog/post/edit", f.controller().update("post", bad, redirect));
|
||||
assertTrue(String.valueOf(redirect.getFlashAttributes().get("error")).contains("customPath"));
|
||||
assertEquals("My first post", f.store().read("acme", "post").orElseThrow().title().get("en"));
|
||||
assertEquals(1, f.events().announced().size(), "only the create");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownEntriesAre404(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
assertEquals(404, assertThrows(ResponseStatusException.class,
|
||||
() -> f.controller().editForm("ghost", new ExtendedModelMap())).getStatusCode().value());
|
||||
assertEquals(404, assertThrows(ResponseStatusException.class,
|
||||
() -> f.controller().update("ghost", form(), new RedirectAttributesModelMap())).getStatusCode().value());
|
||||
assertEquals(404, assertThrows(ResponseStatusException.class,
|
||||
() -> f.controller().togglePublished("ghost", new RedirectAttributesModelMap()))
|
||||
.getStatusCode().value());
|
||||
assertTrue(f.store().read("acme", "ghost").isEmpty(), "an update never creates");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutABoundTenancyEveryScreenIs400(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, false);
|
||||
assertEquals(400, assertThrows(ResponseStatusException.class,
|
||||
() -> f.controller().list(new ExtendedModelMap())).getStatusCode().value(),
|
||||
"the application console has no site: RequestContext.site() is empty there");
|
||||
assertEquals(400, assertThrows(ResponseStatusException.class,
|
||||
() -> f.controller().create("x", form(), new ExtendedModelMap(), new RedirectAttributesModelMap()))
|
||||
.getStatusCode().value());
|
||||
assertEquals(400, assertThrows(ResponseStatusException.class,
|
||||
() -> f.controller().delete("x", new RedirectAttributesModelMap())).getStatusCode().value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theListModelCarriesRowsPathsAndTheEnabledFlag(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
BlogStoreTest.install131(tmp, "acme");
|
||||
ExtendedModelMap model = new ExtendedModelMap();
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW, f.controller().list(model));
|
||||
@SuppressWarnings("unchecked")
|
||||
List<BlogAdminController.EntryRow> rows = (List<BlogAdminController.EntryRow>) model.getAttribute("rows");
|
||||
assertEquals(List.of("launch", "no-author", "hello-world", "draft-post"),
|
||||
rows.stream().map(r -> r.entry().id()).toList(), "every entry, drafts included, newest first");
|
||||
assertEquals("/announcing-v2", rows.get(0).publicPath());
|
||||
assertEquals("/blog/hello-world", rows.get(2).publicPath());
|
||||
assertEquals(Boolean.TRUE, model.getAttribute("blogEnabled"));
|
||||
assertEquals("__plugin__/blog/admin-list", model.getAttribute(ConsoleScreen.CONTENT_TEMPLATE));
|
||||
assertEquals("blog.admin.title", model.getAttribute(ConsoleScreen.PAGE_TITLE_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEditorModelCarriesTheReverseAdvisoryWhenAPageOwnsThePath(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
f.controller().create("first-post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap());
|
||||
f.catalog().page("acme", "/blog/first", EN, "about");
|
||||
f.catalog().page("acme", "/blog/first", ES, "wrong-locale-claim");
|
||||
f.catalog().page("acme", "/blog/primera", ES, "acerca");
|
||||
|
||||
ExtendedModelMap model = new ExtendedModelMap();
|
||||
assertEquals(ConsoleScreen.LAYOUT_VIEW, f.controller().editForm("first-post", model));
|
||||
assertEquals(List.of("about (en)", "acerca (es)"), model.getAttribute("shadowedBy"),
|
||||
"each language's REAL URL is checked in that language's URL space");
|
||||
assertEquals("__plugin__/blog/admin-edit", model.getAttribute(ConsoleScreen.CONTENT_TEMPLATE));
|
||||
assertEquals("/__admin/blog/first-post", model.getAttribute("formAction"));
|
||||
assertEquals(List.of("en", "es"), model.getAttribute("siteLocaleTags"));
|
||||
assertEquals("en", model.getAttribute("defaultLocaleTag"));
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> bodies = (Map<String, String>) model.getAttribute("bodies");
|
||||
assertEquals(Map.of("en", "Hello **world**.", "es", "Hola **mundo**."), bodies);
|
||||
|
||||
ExtendedModelMap creating = new ExtendedModelMap();
|
||||
f.controller().createForm(creating);
|
||||
assertEquals(List.of(), creating.getAttribute("shadowedBy"), "no advisory before the entry exists");
|
||||
assertEquals("/__admin/blog/create", creating.getAttribute("formAction"));
|
||||
}
|
||||
|
||||
/** Toggling publish/unpublish must not erase the byline (the positional rebuild is a known-recurring hazard). */
|
||||
@Test
|
||||
void togglingPublishPreservesTheAuthor(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp);
|
||||
f.store().save("acme", new BlogEntry("post", Map.of("en", "Post"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "2026-03-04", "Jane Doe", null), Map.of("en", "# Hi"));
|
||||
f.controller().togglePublished("post", new RedirectAttributesModelMap());
|
||||
BlogEntry hidden = f.store().read("acme", "post").orElseThrow();
|
||||
assertFalse(hidden.published(), "precondition: the toggle actually flipped visibility");
|
||||
assertEquals("Jane Doe", hidden.author(), "unpublishing must not un-attribute the entry");
|
||||
f.controller().togglePublished("post", new RedirectAttributesModelMap());
|
||||
assertEquals("Jane Doe", f.store().read("acme", "post").orElseThrow().author());
|
||||
assertEquals("# Hi", f.store().readBody("acme", "post", "en"), "a toggle never touches a body");
|
||||
}
|
||||
|
||||
@Test
|
||||
void itIsAConsoleScreenWhoseMutationsArePermissionGatedPosts() {
|
||||
Class<BlogAdminController> type = BlogAdminController.class;
|
||||
assertNotNull(type.getAnnotation(Controller.class));
|
||||
assertNotNull(type.getAnnotation(ConsoleScreen.class), "the kernel renders it inside the operator shell");
|
||||
int gets = 0;
|
||||
int posts = 0;
|
||||
for (Method m : type.getDeclaredMethods()) {
|
||||
GetMapping get = m.getAnnotation(GetMapping.class);
|
||||
PostMapping post = m.getAnnotation(PostMapping.class);
|
||||
if (get == null && post == null) {
|
||||
continue;
|
||||
}
|
||||
String[] paths = get != null ? get.value() : post.value();
|
||||
for (String path : paths) {
|
||||
assertTrue(path.equals("/__admin/blog") || path.startsWith("/__admin/blog/"),
|
||||
m.getName() + ": every mapping lies under /__admin/blog (" + path + ")");
|
||||
}
|
||||
PreAuthorize gate = m.getAnnotation(PreAuthorize.class);
|
||||
assertNotNull(gate, m.getName() + " is permission-gated");
|
||||
assertEquals("@authz.may('blog|manage')", gate.value());
|
||||
if (get != null) {
|
||||
gets++;
|
||||
assertTrue(Set.of("list", "createForm", "editForm").contains(m.getName()),
|
||||
m.getName() + ": a GET only renders");
|
||||
} else {
|
||||
posts++;
|
||||
}
|
||||
}
|
||||
assertEquals(3, gets);
|
||||
assertEquals(4, posts, "create, update, publish toggle, delete — each a CSRF-checked POST");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Renders the console templates ({@code admin-list}, {@code admin-edit}) through the real decoupled-logic pipeline
|
||||
* with the models the controller builds — a binding typo (a {@code /} where {@code //} belongs, a broken selector) is
|
||||
* a RUNTIME failure the unit tests can't see; this test turns it into a build failure. And it holds the templates to
|
||||
* the {@code @ConsoleScreen} contract: the only shell variables they read are {@code _csrf} (and their own
|
||||
* controller's model), they reach no bean, and every {@code #{…}} key is in this plugin's own bundle.
|
||||
*/
|
||||
class BlogAdminTemplatesRenderTest {
|
||||
|
||||
/** What the controller puts in the model for these templates — the plugin's own variables. */
|
||||
private static final Set<String> OWN_MODEL = Set.of("rows", "row", "blogEnabled", "entry", "bodies", "creating",
|
||||
"shadowedBy", "siteLocaleTags", "defaultLocaleTag", "formAction", "lang");
|
||||
/** What the shell promises a console screen's content template (SPI {@code ConsoleScreen}). */
|
||||
private static final Set<String> SHELL_CONTRACT = Set.of("_csrf", "tenantSiteId");
|
||||
|
||||
private static String live(String file) throws IOException {
|
||||
return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
}
|
||||
|
||||
private static Map<String, Object> withCsrf(Map<String, Object> vars) {
|
||||
Map<String, Object> all = new HashMap<>(vars);
|
||||
// The shell's CsrfToken, as SpEL reads it (parameterName, token).
|
||||
all.put("_csrf", Map.of("parameterName", "_csrf", "token", "tok-123"));
|
||||
return all;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConsoleTemplatesReadOnlyTheirOwnModelAndThePromisedShellVariables() throws IOException {
|
||||
Pattern root = Pattern.compile("\\$\\{\\s*!?\\s*([A-Za-z_@#][\\w]*)");
|
||||
Pattern message = Pattern.compile("#\\{([^}(]+)");
|
||||
Set<String> bundle = BlogConfigTest.keys("i18n/messages.properties");
|
||||
Set<String> roots = new TreeSet<>();
|
||||
for (String file : List.of("admin-list.th.xml", "admin-edit.th.xml")) {
|
||||
String logic = live(file);
|
||||
Matcher m = root.matcher(logic);
|
||||
while (m.find()) {
|
||||
roots.add(m.group(1));
|
||||
}
|
||||
Matcher k = message.matcher(logic);
|
||||
while (k.find()) {
|
||||
assertTrue(bundle.contains(k.group(1).trim()), file + ": #{" + k.group(1)
|
||||
+ "} is not in this plugin's bundle (no kernel console key is promised)");
|
||||
}
|
||||
}
|
||||
for (String r : roots) {
|
||||
assertFalse(r.startsWith("@"), "no bean reference in the console templates: " + r);
|
||||
assertTrue(r.startsWith("#") || OWN_MODEL.contains(r) || SHELL_CONTRACT.contains(r),
|
||||
"a variable neither the controller nor the shell contract provides: " + r);
|
||||
}
|
||||
assertTrue(roots.contains("_csrf"), "every mutating form carries the CSRF token");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theListScreenRendersRowsBadgesPostFormsAndCsrf(@TempDir Path tmp) {
|
||||
BlogEntry published = new BlogEntry("hello", Map.of("en", "Hello"), Map.of(), List.of("en", "es"),
|
||||
null, Map.of(), null, true, "2026-07-17", null, null);
|
||||
BlogEntry draft = new BlogEntry("secret", Map.of("en", "Secret"), Map.of(), List.of(),
|
||||
null, Map.of(), null, false, null, null, null);
|
||||
String html = new TemplateHarness(tmp).render("__plugin__/blog/admin-list", Locale.ENGLISH, withCsrf(Map.of(
|
||||
"rows", List.of(new BlogAdminController.EntryRow(published, "/blog/hello"),
|
||||
new BlogAdminController.EntryRow(draft, "/blog/secret")),
|
||||
"blogEnabled", true)));
|
||||
|
||||
assertTrue(html.contains("/blog/hello") && html.contains("/blog/secret"), "the resolved public paths");
|
||||
assertTrue(html.contains("en, es"), "the languages");
|
||||
assertTrue(html.contains("2026-07-17"), "the date renders");
|
||||
assertTrue(html.contains(">Published<") && html.contains(">Draft<"), "the plugin's badges");
|
||||
assertTrue(html.contains("bg-green-lt") && html.contains("bg-yellow-lt"));
|
||||
assertTrue(html.contains("href=\"/__admin/blog/hello/edit\""), "the edit link (a GET that only renders)");
|
||||
assertTrue(html.contains("method=\"post\" action=\"/__admin/blog/hello/publish\""), "publish is a POST");
|
||||
assertTrue(html.contains("method=\"post\" action=\"/__admin/blog/secret/delete\""), "delete is a POST");
|
||||
assertEquals(4, html.split("name=\"_csrf\" value=\"tok-123\"", -1).length - 1,
|
||||
"every mutating form (2 rows × publish + delete) carries the console's CSRF token");
|
||||
assertFalse(html.contains("href=\"/__admin/blog/hello/publish\"") || html.contains("/delete\" href"),
|
||||
"no link points at a mutation");
|
||||
assertTrue(html.contains(">Site<"), "the pretitle comes from the plugin's own bundle");
|
||||
assertFalse(html.contains("??"), "every message key resolved");
|
||||
assertFalse(html.contains("id=\"bl-disabled\""), "no banner when enabled");
|
||||
assertFalse(html.contains("id=\"bl-empty\""), "no empty row with entries");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theListScreenShowsTheEmptyRowAndTheDisabledBanner(@TempDir Path tmp) {
|
||||
TemplateHarness harness = new TemplateHarness(tmp);
|
||||
String disabled = harness.render("__plugin__/blog/admin-list", Locale.of("es"), withCsrf(Map.of(
|
||||
"rows", List.<BlogAdminController.EntryRow>of(), "blogEnabled", false)));
|
||||
assertTrue(disabled.contains("id=\"bl-disabled\""), "disabled banner present");
|
||||
assertTrue(disabled.contains("id=\"bl-empty\""), "the empty row");
|
||||
assertTrue(disabled.contains(">Sitio<"), "Spanish console words from the plugin's bundle");
|
||||
assertFalse(disabled.contains("??"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEditorRendersPerLanguageCardsForBothCreateAndEdit(@TempDir Path tmp) {
|
||||
TemplateHarness harness = new TemplateHarness(tmp);
|
||||
BlogEntry entry = new BlogEntry("hello", Map.of("en", "Hello", "es", "Hola"),
|
||||
Map.of("en", "Desc"), List.of("en"), "hello-slug", Map.of("es", "hola-slug"),
|
||||
"/custom", true, "2026-07-17", "Jane Doe", null);
|
||||
Map<String, Object> vars = Map.of(
|
||||
"formAction", "/__admin/blog/hello",
|
||||
"entry", entry,
|
||||
"bodies", Map.of("en", "# Body EN", "es", ""),
|
||||
"creating", false,
|
||||
"shadowedBy", List.of("about (en)"),
|
||||
"siteLocaleTags", List.of("en", "es"),
|
||||
"defaultLocaleTag", "en");
|
||||
String html = harness.render("__plugin__/blog/admin-edit", Locale.ENGLISH, withCsrf(vars));
|
||||
|
||||
assertTrue(html.contains("method=\"post\" action=\"/__admin/blog/hello\""), "edit mode POSTs to the entry");
|
||||
assertTrue(html.contains("name=\"_csrf\" value=\"tok-123\""), "with the console's CSRF token");
|
||||
assertTrue(html.contains("name=\"title_en\"") && html.contains("name=\"title_es\""),
|
||||
"one language card per site locale, fields renamed per language");
|
||||
assertTrue(html.contains("value=\"Hello\"") && html.contains("value=\"Hola\""), "titles prefilled");
|
||||
assertTrue(html.contains("value=\"hello-slug\""), "the default language's slug is the base slug");
|
||||
assertTrue(html.contains("value=\"hola-slug\""), "the localized slug prefills");
|
||||
assertTrue(html.contains("name=\"body_en\"") && html.contains("# Body EN"), "the Markdown body prefills");
|
||||
assertTrue(html.contains("value=\"/custom\""), "the custom path prefills");
|
||||
assertTrue(html.contains("value=\"Jane Doe\""), "the author prefills");
|
||||
assertTrue(html.contains("name=\"locales_en\" checked"), "a published language is ticked");
|
||||
assertTrue(html.contains("readonly"), "the id is readonly on edit");
|
||||
assertTrue(html.contains("about (en)"), "the reverse advisory renders the winning page");
|
||||
assertTrue(html.contains("en · default"), "the default language is marked");
|
||||
assertFalse(html.contains("??"), "every message key resolved");
|
||||
|
||||
Map<String, Object> creating = Map.of(
|
||||
"formAction", "/__admin/blog/create",
|
||||
"entry", new BlogEntry("new-entry", Map.of(), Map.of(), List.of(), null, Map.of(),
|
||||
null, false, null, null, null),
|
||||
"bodies", Map.<String, String>of(),
|
||||
"creating", true,
|
||||
"shadowedBy", List.<String>of(),
|
||||
"siteLocaleTags", List.of("en"),
|
||||
"defaultLocaleTag", "en");
|
||||
String createHtml = harness.render("__plugin__/blog/admin-edit", Locale.ENGLISH, withCsrf(creating));
|
||||
assertTrue(createHtml.contains("action=\"/__admin/blog/create\""), "create mode posts to /create");
|
||||
assertFalse(createHtml.contains("readonly"), "the id is editable on create");
|
||||
assertFalse(createHtml.contains("id=\"be-shadowed\""), "no advisory on create");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name rule,
|
||||
* the descriptor (SPI floor, release version, no personal data, the settings the code reads), the i18n bundles, and
|
||||
* that the compiled classes link nothing of the host but the SPI — the same things the kernel's load-time checks
|
||||
* warn about (and refuse from Runway 1.0).
|
||||
*/
|
||||
class BlogConfigTest {
|
||||
|
||||
private static final String PREFIX = "blog";
|
||||
|
||||
static Set<String> keys(String file) throws IOException {
|
||||
Properties p = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
|
||||
p.load(in);
|
||||
}
|
||||
return new TreeSet<>(p.stringPropertyNames());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> descriptor() throws IOException {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(BlogConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromSpiServicesUnderPrefixedNames(@TempDir Path sites) throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null))
|
||||
.current("acme");
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings());
|
||||
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "blog"));
|
||||
ctx.registerBean(ContentCatalogView.class, () -> new FakeContentCatalog().site("acme"));
|
||||
ctx.registerBean(ContentChanges.class, () -> new EventDispatch("blog", Set.of("blog")));
|
||||
ctx.registerBean(FakeSiteServices.class, () -> kernel);
|
||||
ctx.register(BlogConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
assertEquals(Set.of("blogStore", "blogContentSource", "blogAdminController"),
|
||||
new TreeSet<>(Arrays.stream(ctx.getBeanDefinitionNames())
|
||||
.filter(n -> n.startsWith("blog") && !n.equals("blogConfig")).toList()),
|
||||
"the mainClass itself is registered by the host as plugin:blog");
|
||||
BlogContentSource source = ctx.getBean("blogContentSource", BlogContentSource.class);
|
||||
assertSame(source, ctx.getBean(ContentSource.class), "collected as the site's content source");
|
||||
assertSame(source, ctx.getBean(SiteEventListener.class), "…and as its own index's listener");
|
||||
assertEquals("blog", source.key());
|
||||
ctx.getBean("blogStore", BlogStore.class).save("acme", new BlogEntry("hi", Map.of("en", "Hi"), Map.of(),
|
||||
List.of("en"), null, Map.of(), null, true, null, null, null), Map.of("en", "x"));
|
||||
assertTrue(Files.isRegularFile(sites.resolve("acme/plugins/blog/entries/hi/entry.yml")),
|
||||
"the store writes through the injected PluginSiteFiles");
|
||||
org.springframework.ui.ExtendedModelMap model = new org.springframework.ui.ExtendedModelMap();
|
||||
ctx.getBean("blogAdminController", BlogAdminController.class).list(model);
|
||||
assertEquals(1, ((List<?>) model.getAttribute("rows")).size(),
|
||||
"the controller reads the bound site through RequestContext");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginId() {
|
||||
assertEquals(Set.of("blogStore", "blogContentSource", "blogAdminController"), beanMethodNames());
|
||||
for (Method m : BlogConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
for (String alias : bean.name()) {
|
||||
assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertEquals("blog", yml.get("id"));
|
||||
assertEquals(BlogConfig.class.getName(), yml.get("mainClass"));
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-blog</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals("2.1.0", version.group(1));
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree");
|
||||
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T18:56:00Z</project.build.outputTimestamp>"));
|
||||
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void theDescriptorDeclaresNoPersonalDataAndTheSettingsTheCodeReads() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertNull(yml.get("siteData"), "blog entries are published content the site's operators author, not personal data");
|
||||
List<Map<String, Object>> schema = (List<Map<String, Object>>) yml.get("siteSettings");
|
||||
Map<String, Object> byKey = new java.util.HashMap<>();
|
||||
schema.forEach(s -> byKey.put(String.valueOf(s.get("key")), s.get("default")));
|
||||
assertEquals(Map.of("enabled", true, "prefix", BlogSettings.DEFAULT_PREFIX,
|
||||
"template", BlogSettings.DEFAULT_TEMPLATE), byKey, "the code's fallbacks match the declared defaults");
|
||||
List<Map<String, Object>> permissions = (List<Map<String, Object>>) yml.get("permissions");
|
||||
assertEquals(List.of("settings", "manage"), permissions.stream().map(p -> p.get("id")).toList());
|
||||
List<Map<String, Object>> menu = (List<Map<String, Object>>) yml.get("menu");
|
||||
assertEquals("/__admin/blog", menu.get(0).get("path"));
|
||||
assertEquals("blog|manage", menu.get(0).get("permission"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEnglishAndSpanishBundlesDefineTheSameKeysAndEveryDescriptorLabel() throws IOException {
|
||||
Set<String> en = keys("i18n/messages.properties");
|
||||
assertEquals(en, keys("i18n/messages_es.properties"));
|
||||
String yml = Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8);
|
||||
Matcher label = Pattern.compile("label: (blog\\.[\\w.]+)").matcher(yml);
|
||||
int found = 0;
|
||||
while (label.find()) {
|
||||
found++;
|
||||
assertTrue(en.contains(label.group(1)), "descriptor label without words: " + label.group(1));
|
||||
}
|
||||
assertEquals(6, found, "2 permissions, 3 settings, 1 menu entry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternals() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
|
||||
scanned++;
|
||||
String rel = classes.relativize(file).toString().replace('\\', '/');
|
||||
if (rel.startsWith("mx/quest/runway/")) {
|
||||
problems.add(rel + " lives under mx.quest.runway");
|
||||
}
|
||||
// The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every
|
||||
// byte as one char, so an ASCII pattern finds them without parsing the class file.
|
||||
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(scanned >= 6, "the compiled classes were found (" + scanned + ")");
|
||||
assertTrue(problems.isEmpty(), "host linkage: " + problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* {@link BlogContentSource} against the ContentSource contract: published-only metadata enumeration, the O(1) URL
|
||||
* index (prefix + localized slugs + custom paths), Markdown bodies fetched only via {@code body()}, the per-site enable
|
||||
* switch and prefix setting (through {@code PluginSettings}, with the kernel's path rule) — and its index invalidation
|
||||
* as a {@code SOURCE}-phase {@link SiteEventListener}, driven by the testkit's {@link EventDispatch} in the kernel's
|
||||
* delivery order.
|
||||
*/
|
||||
class BlogContentSourceTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
|
||||
private record Fixture(BlogStore store, BlogContentSource source, FakePluginSettings settings,
|
||||
EventDispatch events) {
|
||||
}
|
||||
|
||||
private static Fixture fixture(Path tmp, Map<String, Object> cfg) throws IOException {
|
||||
Files.createDirectories(tmp.resolve("acme"));
|
||||
BlogStore store = new BlogStore(new TempDirSiteFiles(tmp, "blog"));
|
||||
FakePluginSettings settings = new FakePluginSettings()
|
||||
.defaults(Map.of("enabled", true, "prefix", "/blog", "template", "entry-classic"))
|
||||
.site("acme", cfg);
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().site("acme").route("/sitemap.xml");
|
||||
BlogContentSource source = new BlogContentSource(store, settings, catalog);
|
||||
EventDispatch events = new EventDispatch("blog", Set.of(BlogContentSource.KEY)).listener(source);
|
||||
return new Fixture(store, source, settings, events);
|
||||
}
|
||||
|
||||
private static BlogEntry entry(String id, boolean published) {
|
||||
return new BlogEntry(id, Map.of("en", "T-" + id, "es", "ES-" + id), Map.of("en", "D"),
|
||||
List.of("en", "es"), null, Map.of("es", id + "-es"), null, published, "2026-07-17", null, null);
|
||||
}
|
||||
|
||||
private static Map<String, ContentRef> byId(BlogContentSource source) {
|
||||
Map<String, ContentRef> out = new HashMap<>();
|
||||
for (ContentRef r : source.enumerate(SITE)) {
|
||||
out.put(r.id(), r);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Test
|
||||
void enumeratesPublishedEntriesAsRefsUnderThePrefix(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), Map.of("en", "# Hi"));
|
||||
f.store().save("acme", entry("draft", false), null);
|
||||
|
||||
List<ContentRef> refs = f.source().enumerate(SITE);
|
||||
assertEquals(1, refs.size(), "unpublished entries are never enumerated (draft-leak fail-closed)");
|
||||
ContentRef ref = refs.get(0);
|
||||
assertEquals("hello", ref.id());
|
||||
assertEquals("/blog/hello", ref.pathFor(EN), "default prefix + slug");
|
||||
assertEquals("/blog/hello-es", ref.pathFor(ES), "localized slug under the same prefix");
|
||||
assertEquals("T-hello", ref.titleFor(EN));
|
||||
assertEquals("D", ref.descriptionFor(EN));
|
||||
assertEquals(List.of(EN, ES), ref.locales());
|
||||
assertEquals("__plugin__/blog/entry-classic", ref.bodyTemplate(), "the default template setting");
|
||||
assertTrue(ref.published());
|
||||
assertNotNull(ref.updatedAt(), "file-time-derived — a body edit moves the ETag automatically");
|
||||
assertEquals(BlogContentSource.KEY, f.source().key());
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesWrittenBy131EnumerateAndResolveUnchanged(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
BlogStoreTest.install131(tmp, "acme");
|
||||
Map<String, ContentRef> refs = byId(f.source());
|
||||
assertEquals(Set.of("hello-world", "no-author", "launch"), refs.keySet(), "the draft stays out");
|
||||
assertEquals("/blog/hello-world", refs.get("hello-world").pathFor(EN));
|
||||
assertEquals("/blog/hola-mundo", refs.get("hello-world").pathFor(ES));
|
||||
assertEquals("Jane Doe", refs.get("hello-world").author());
|
||||
assertNull(refs.get("no-author").author(), "the entry with no author stays unattributed");
|
||||
assertEquals(Instant.parse("2026-08-01T00:00:00Z"), refs.get("no-author").publishedAt());
|
||||
assertEquals("/announcing-v2", refs.get("launch").pathFor(EN), "the custom path survives");
|
||||
assertEquals("launch", f.source().resolve(SITE, "/announcing-v2", EN).orElseThrow().id());
|
||||
assertTrue(f.source().body(SITE, "hello-world", EN).bodyHtml().contains("<strong>bold</strong>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesThroughTheIndexIncludingCustomPaths(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
f.store().save("acme", new BlogEntry("launch", Map.of("en", "Launch"), Map.of(), List.of("en"),
|
||||
null, Map.of(), "/announcing-v2", true, null, null, null), null);
|
||||
|
||||
assertEquals("hello", f.source().resolve(SITE, "/blog/hello", EN).orElseThrow().id());
|
||||
assertEquals("hello", f.source().resolve(SITE, "/blog/hello-es", ES).orElseThrow().id(),
|
||||
"the localized slug resolves under its own locale");
|
||||
assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/hello-es", EN),
|
||||
"a localized slug never doubles as another locale's URL");
|
||||
assertEquals("launch", f.source().resolve(SITE, "/announcing-v2", EN).orElseThrow().id(),
|
||||
"a custom path escapes the prefix (the arbitrary-paths capability)");
|
||||
assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/nope", EN));
|
||||
assertTrue(f.source().capabilities().has(ContentSource.CAP_ARBITRARY_PATHS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void itIsASourcePhaseListener(@TempDir Path tmp) throws IOException {
|
||||
assertEquals(SiteEventListener.Phase.SOURCE, fixture(tmp, Map.of()).source().phase(),
|
||||
"its own index must drop BEFORE sitemap/search consumers re-read the listing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void itsOwnContentChangeDropsTheIndexAndTheRefs(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
f.source().resolve(SITE, "/blog/hello", EN);
|
||||
assertNotNull(f.source().cachedIndex("acme"), "index built lazily on first resolve");
|
||||
assertNotNull(f.source().cachedRefs("acme"));
|
||||
|
||||
// What the console calls after a save — delivered back as a CONTENT change for this source's key.
|
||||
f.store().save("acme", entry("second", true), null);
|
||||
f.events().changed("acme", BlogContentSource.KEY, "second");
|
||||
assertNull(f.source().cachedIndex("acme"), "own-content change drops the index");
|
||||
assertNull(f.source().cachedRefs("acme"), "…and the enumerated refs");
|
||||
assertEquals("second", f.source().resolve(SITE, "/blog/second", EN).orElseThrow().id(),
|
||||
"the next probe sees the new entry");
|
||||
assertTrue(f.events().failures().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplayedChangeFromAPeerNodeDropsItToo(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
f.source().resolve(SITE, "/blog/hello", EN);
|
||||
f.events().catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, BlogContentSource.KEY, null,
|
||||
"blog", List.of(), List.of(), false));
|
||||
assertNull(f.source().cachedIndex("acme"), "local == false still converges this node's index");
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherChangesLeaveTheIndexAlone(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
f.source().resolve(SITE, "/blog/hello", EN);
|
||||
Map<String, String> built = f.source().cachedIndex("acme");
|
||||
|
||||
f.events().page("acme", "about", List.of(), List.of());
|
||||
f.events().catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "products", "x", "shop",
|
||||
List.of(), List.of(), true));
|
||||
f.events().settings("acme", "search");
|
||||
f.events().catalog(new CatalogChange("globex", CatalogChange.Cause.CONTENT, BlogContentSource.KEY, "x",
|
||||
"blog", List.of(), List.of(), true));
|
||||
assertTrue(built == f.source().cachedIndex("acme"),
|
||||
"a page write, another source's change, another plugin's settings, another site: kept");
|
||||
}
|
||||
|
||||
@Test
|
||||
void itsOwnSettingsSaveDropsTheIndexAndRekeysEveryUrl(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
assertEquals("/blog/hello", f.source().enumerate(SITE).get(0).pathFor(EN));
|
||||
f.source().resolve(SITE, "/blog/hello", EN);
|
||||
|
||||
f.settings().site("acme", Map.of("prefix", "/news"));
|
||||
f.events().settings("acme", "blog");
|
||||
assertNull(f.source().cachedIndex("acme"), "a prefix change re-keys every URL — dropped");
|
||||
assertEquals("/news/hello", f.source().enumerate(SITE).get(0).pathFor(EN));
|
||||
assertEquals("hello", f.source().resolve(SITE, "/news/hello", EN).orElseThrow().id());
|
||||
assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/hello", EN), "the old URL is gone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyLifecycleEventDropsTheIndex(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
for (SiteLifecycleEvent.Kind kind : SiteLifecycleEvent.Kind.values()) {
|
||||
f.source().resolve(SITE, "/blog/hello", EN);
|
||||
assertNotNull(f.source().cachedIndex("acme"));
|
||||
f.events().lifecycle("acme", kind, kind == SiteLifecycleEvent.Kind.RESTORED);
|
||||
assertNull(f.source().cachedIndex("acme"), kind + " drops it (a restore replaced the files wholesale)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bodyRendersMarkdownAndCarriesThePublicationDate(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true), Map.of("en", "# Title\n\nSome **bold** text."));
|
||||
|
||||
ContentBody body = f.source().body(SITE, "hello", EN);
|
||||
assertTrue(body.bodyHtml().contains("<h1>Title</h1>"), "markdown heading rendered");
|
||||
assertTrue(body.bodyHtml().contains("<strong>bold</strong>"), "markdown emphasis rendered");
|
||||
assertEquals("2026-07-17", body.attributes().get("publishedOn"));
|
||||
assertEquals("", f.source().body(SITE, "hello", ES).bodyHtml(), "no es body → empty (soft)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorruptEntryNeverBlanksTheRestOfTheBlog(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("good", true), Map.of("en", "fine"));
|
||||
Path corrupt = tmp.resolve("acme/plugins/blog/entries/broken");
|
||||
Files.createDirectories(corrupt);
|
||||
Files.writeString(corrupt.resolve("entry.yml"), "title: [unclosed");
|
||||
|
||||
List<ContentRef> refs = f.source().enumerate(SITE);
|
||||
assertEquals(1, refs.size(), "the good entry survives its corrupt sibling");
|
||||
assertEquals("good", f.source().resolve(SITE, "/blog/good", EN).orElseThrow().id());
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoEntriesClaimingOnePathResolveDeterministically(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", new BlogEntry("one", Map.of("en", "One"), Map.of(), List.of("en"),
|
||||
"shared", Map.of(), null, true, "2026-01-02", null, null), null);
|
||||
f.store().save("acme", new BlogEntry("two", Map.of("en", "Two"), Map.of(), List.of("en"),
|
||||
"shared", Map.of(), null, true, "2026-01-01", null, null), null);
|
||||
String winner = f.source().resolve(SITE, "/blog/shared", EN).orElseThrow().id();
|
||||
f.events().changed("acme", BlogContentSource.KEY, null);
|
||||
assertEquals(winner, f.source().resolve(SITE, "/blog/shared", EN).orElseThrow().id(),
|
||||
"one deterministic winner, the same after a rebuild");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDisabledSiteServesAndListsNothing(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of("enabled", false));
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
assertTrue(f.source().enumerate(SITE).isEmpty());
|
||||
assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/hello", EN));
|
||||
assertTrue(!f.source().settings("acme").enabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomPrefixRekeysEveryUrl(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of("prefix", "news/"));
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
assertEquals("/news/hello", f.source().enumerate(SITE).get(0).pathFor(EN), "normalized: leading /, no trailing");
|
||||
assertEquals("hello", f.source().resolve(SITE, "/news/hello", EN).orElseThrow().id());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRootPrefixServesEntriesAtTheTopLevel(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of("prefix", "/"));
|
||||
f.store().save("acme", entry("hello", true), null);
|
||||
assertEquals("/hello", f.source().enumerate(SITE).get(0).pathFor(EN), "never '//hello'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrefixTheKernelWouldNotServeFallsBackToBlog(@TempDir Path tmp) throws IOException {
|
||||
for (String bad : List.of("/__admin", "/app", "/actuator", "/a|b", "/x/../y")) {
|
||||
Fixture f = fixture(tmp.resolve("p" + Math.abs(bad.hashCode())), Map.of("prefix", bad));
|
||||
assertEquals("/blog", f.source().settings("acme").prefix(),
|
||||
bad + ": entries under it would silently vanish — the default is used instead");
|
||||
}
|
||||
for (String ok : List.of("/sitemap.xml", "/login", "/news/archive")) {
|
||||
assertEquals(ok, fixture(tmp.resolve("ok" + Math.abs(ok.hashCode())), Map.of("prefix", ok))
|
||||
.source().settings("acme").prefix(), ok + ": only the path an entry would get is checked");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTemplateSettingFailsClosedToClassic(@TempDir Path tmp) throws IOException {
|
||||
assertEquals("__plugin__/blog/entry-minimal",
|
||||
fixture(tmp.resolve("a"), Map.of("template", "entry-minimal")).source().settings("acme").bodyTemplate());
|
||||
assertEquals("__plugin__/blog/entry-classic",
|
||||
fixture(tmp.resolve("b"), Map.of("template", "../../evil")).source().settings("acme").bodyTemplate(),
|
||||
"an unknown template name never reaches the template lookup");
|
||||
}
|
||||
|
||||
@Test
|
||||
void indexableTextIsRenderedHtmlPerLocaleSoEnginesStripCleanly(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", entry("hello", true),
|
||||
Map.of("en", "# Hi\n\nRunway makes [hosting](/x) simple.", "es", "# Hola"));
|
||||
|
||||
assertTrue(f.source().capabilities().has(ContentSource.CAP_INDEXABLE_TEXT),
|
||||
"the blog opts into the search seam — entries are first-class search citizens");
|
||||
String en = f.source().indexableText(SITE, "hello", EN);
|
||||
assertTrue(en.contains("<h1>Hi</h1>"), "heading rendered, not left as '# Hi': " + en);
|
||||
assertTrue(en.contains("<a href=\"/x\">hosting</a>"), "link rendered, not left as Markdown syntax: " + en);
|
||||
assertTrue(f.source().indexableText(SITE, "hello", ES).contains("<h1>Hola</h1>"), "per-locale material");
|
||||
assertEquals("", f.source().indexableText(SITE, "hello", Locale.FRENCH),
|
||||
"an untranslated locale indexes as metadata only, never an error");
|
||||
assertEquals("", f.source().indexableText(SITE, "no-such-entry", EN), "an unknown id degrades to empty");
|
||||
}
|
||||
|
||||
/** Each entry carries ITS OWN publication date across the SPI boundary (not one shared schema block). */
|
||||
@Test
|
||||
void eachEntryCarriesItsOwnPublicationDate(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", new BlogEntry("older", Map.of("en", "Older"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "2026-03-04", null, null), null);
|
||||
f.store().save("acme", new BlogEntry("newer", Map.of("en", "Newer"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "2026-09-10", null, null), null);
|
||||
Map<String, ContentRef> refs = byId(f.source());
|
||||
assertEquals(Instant.parse("2026-03-04T00:00:00Z"), refs.get("older").publishedAt());
|
||||
assertEquals(Instant.parse("2026-09-10T00:00:00Z"), refs.get("newer").publishedAt());
|
||||
assertNotEquals(refs.get("older").publishedAt(), refs.get("newer").publishedAt());
|
||||
}
|
||||
|
||||
/** A free-form publishedOn yields NO date rather than a guess (a wrong datePublished is worse than none). */
|
||||
@Test
|
||||
void anUnparseablePublishedOnYieldsNoDateRatherThanAGuess(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", new BlogEntry("freeform", Map.of("en", "Freeform"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "last spring", null, null), null);
|
||||
f.store().save("acme", new BlogEntry("undated", Map.of("en", "Undated"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, null, null, null), null);
|
||||
assertNull(byId(f.source()).get("freeform").publishedAt(), "a non-date must not become a fabricated instant");
|
||||
assertNull(byId(f.source()).get("undated").publishedAt());
|
||||
}
|
||||
|
||||
/** Each entry carries ITS OWN author across the SPI boundary, so structured data attributes the right person. */
|
||||
@Test
|
||||
void eachEntryCarriesItsOwnAuthor(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", new BlogEntry("ada", Map.of("en", "Ada"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "2026-03-04", "Jane Doe", null), null);
|
||||
f.store().save("acme", new BlogEntry("anon", Map.of("en", "Anon"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "2026-03-04", " ", null), null);
|
||||
assertEquals("Jane Doe", byId(f.source()).get("ada").author());
|
||||
assertNull(byId(f.source()).get("anon").author(), "a blank byline must normalise to absent");
|
||||
}
|
||||
|
||||
/** The byline reaches the RENDER attributes too — and is absent, not empty, when the entry has none. */
|
||||
@Test
|
||||
void theAuthorReachesTheRenderAttributes(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
f.store().save("acme", new BlogEntry("ada", Map.of("en", "Ada"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, "2026-03-04", "Jane Doe", null), Map.of("en", "# Hello"));
|
||||
f.store().save("acme", new BlogEntry("anon", Map.of("en", "Anon"), Map.of(), List.of("en"),
|
||||
null, Map.of(), null, true, null, null, null), Map.of("en", "# Hi"));
|
||||
assertEquals("Jane Doe", f.source().body(SITE, "ada", EN).attributes().get("author"));
|
||||
assertEquals(Map.of(), f.source().body(SITE, "anon", EN).attributes(),
|
||||
"an unattributed, undated entry puts nothing into the render attributes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicPathsFollowTheRoutingSemantics(@TempDir Path tmp) throws IOException {
|
||||
Fixture f = fixture(tmp, Map.of());
|
||||
BlogEntry custom = new BlogEntry("launch", Map.of("en", "L"), Map.of(), List.of("en", "es"), "v2",
|
||||
Map.of("es", "lanzamiento"), "/announcing-v2", true, null, null, null);
|
||||
assertEquals("/announcing-v2", f.source().publicPath("acme", custom));
|
||||
assertEquals("/blog/lanzamiento", f.source().publicPath("acme", custom, "es"), "the localized slug");
|
||||
assertEquals("/announcing-v2", f.source().publicPath("acme", custom, "en"));
|
||||
BlogEntry plain = new BlogEntry("plain", Map.of("en", "P"), Map.of(), List.of("en"), "slugged",
|
||||
Map.of(), null, true, null, null, null);
|
||||
assertEquals("/blog/slugged", f.source().publicPath("acme", plain));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The entry body templates against the <b>documented body-template render model</b> — the SPI contract on
|
||||
* {@code ContentSource} / {@code ContentRef.bodyTemplate} for {@code ${master}} and {@code ${content.*}}. The kernel
|
||||
* promises exactly {@code master}, {@code content.{id, sourceKey, title, description, bodyHtml, attributes, updatedAt}},
|
||||
* {@code locale} and {@code urls}; nothing else.
|
||||
*
|
||||
* <ul>
|
||||
* <li>Statically: every {@code ${…}} expression in the shipped entry templates starts from one of those four
|
||||
* variables, and every {@code content.} key it reads is one the contract lists.</li>
|
||||
* <li>Dynamically: an entry stored by {@link BlogStore} and projected by {@link BlogContentSource} renders through
|
||||
* the real decoupled templates with a model built exactly to the contract — the tenant's master chrome around
|
||||
* the Markdown body, the plugin's own labels, and the byline in each of its four states.</li>
|
||||
* </ul>
|
||||
* The real kernel render (routing, the locale ladder, the master resolution) is exercised by
|
||||
* {@code scripts/verify-against-host.sh}.
|
||||
*/
|
||||
class BlogEntryTemplateContractTest {
|
||||
|
||||
private static final Set<String> MODEL_ROOTS = Set.of("master", "content", "locale", "urls");
|
||||
private static final Set<String> CONTENT_KEYS =
|
||||
Set.of("id", "sourceKey", "title", "description", "bodyHtml", "attributes", "updatedAt");
|
||||
private static final List<String> ENTRY_TEMPLATES = List.of("entry-classic", "entry-minimal");
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
|
||||
private static String liveLogic(String template) throws IOException {
|
||||
return Files.readString(Path.of("templates", template + ".th.xml"), StandardCharsets.UTF_8)
|
||||
.replaceAll("(?s)<!--.*?-->", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEntryTemplatesReadOnlyTheDocumentedRenderModel() throws IOException {
|
||||
Pattern expression = Pattern.compile("\\$\\{([^}]*)}");
|
||||
Pattern root = Pattern.compile("^\\s*([A-Za-z_][\\w]*)");
|
||||
Pattern contentKey = Pattern.compile("\\bcontent\\.(\\w+)");
|
||||
Set<String> roots = new TreeSet<>();
|
||||
Set<String> keys = new TreeSet<>();
|
||||
for (String template : ENTRY_TEMPLATES) {
|
||||
Matcher m = expression.matcher(liveLogic(template));
|
||||
while (m.find()) {
|
||||
Matcher r = root.matcher(m.group(1));
|
||||
assertTrue(r.find(), template + ": an expression with no variable root: ${" + m.group(1) + "}");
|
||||
roots.add(r.group(1));
|
||||
Matcher k = contentKey.matcher(m.group(1));
|
||||
while (k.find()) {
|
||||
keys.add(k.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(MODEL_ROOTS.containsAll(roots), "variables outside the contract: " + roots);
|
||||
assertTrue(CONTENT_KEYS.containsAll(keys), "content keys outside the contract: " + keys);
|
||||
assertEquals(Set.of("master", "content", "urls"), roots, "the templates use the chrome, the payload and links");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEntryTemplatesReferenceNoBeanAndOnlyThePluginsOwnMessages() throws IOException {
|
||||
Set<String> bundle = BlogConfigTest.keys("i18n/messages.properties");
|
||||
Pattern message = Pattern.compile("#\\{([^}(]+)");
|
||||
for (String template : ENTRY_TEMPLATES) {
|
||||
String logic = liveLogic(template);
|
||||
assertFalse(logic.matches("(?s).*\\$\\{\\s*@.*"), template + " must not reach a bean (not in the contract)");
|
||||
Matcher m = message.matcher(logic);
|
||||
while (m.find()) {
|
||||
assertTrue(bundle.contains(m.group(1).trim()), template + ": #{" + m.group(1)
|
||||
+ "} is not in this plugin's bundle (a public page renders with the site's bundle + ours)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The model the kernel builds for a source item's 200 render, exactly as the SPI documents it. */
|
||||
private static Map<String, Object> contractModel(String master, ContentRef ref, ContentBody body, Locale locale) {
|
||||
Map<String, Object> content = new HashMap<>();
|
||||
content.put("id", ref.id());
|
||||
content.put("sourceKey", BlogContentSource.KEY);
|
||||
content.put("title", ref.titleFor(locale));
|
||||
content.put("description", ref.descriptionFor(locale));
|
||||
content.put("bodyHtml", body.bodyHtml());
|
||||
content.put("attributes", body.attributes());
|
||||
content.put("updatedAt", ref.updatedAt() == null ? "" : ref.updatedAt().toString());
|
||||
return Map.of("master", master, "content", Map.copyOf(content), "locale", locale,
|
||||
"urls", Map.of("index", "/", "blog:" + ref.id(), ref.pathFor(locale)));
|
||||
}
|
||||
|
||||
private record Rig(TemplateHarness harness, BlogStore store, BlogContentSource source, String master) {
|
||||
|
||||
String render(String id, Locale locale) {
|
||||
ContentRef ref = source.enumerate(SITE).stream().filter(r -> r.id().equals(id)).findFirst().orElseThrow();
|
||||
return harness.render(ref.bodyTemplate(), locale,
|
||||
contractModel(master, ref, source.body(SITE, id, locale), locale));
|
||||
}
|
||||
}
|
||||
|
||||
private static Rig rig(Path tmp, Map<String, Object> settings) throws IOException {
|
||||
Path sites = tmp.resolve("sites");
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
BlogStore store = new BlogStore(new TempDirSiteFiles(sites, "blog"));
|
||||
BlogContentSource source = new BlogContentSource(store, new FakePluginSettings().site("acme", settings),
|
||||
new FakeContentCatalog().site("acme"));
|
||||
TemplateHarness harness = new TemplateHarness(tmp.resolve("templates"));
|
||||
String master = harness.master("sites/acme/_master",
|
||||
"<!DOCTYPE html><html><head><title>ACME-MASTER</title></head><body>"
|
||||
+ "<header id=\"site-header\">acme header</header>"
|
||||
+ "<main id=\"content\">m</main>"
|
||||
+ "<footer id=\"site-footer\">acme footer</footer></body></html>");
|
||||
return new Rig(harness, store, source, master);
|
||||
}
|
||||
|
||||
private static BlogEntry entry(String id, String publishedOn, String author) {
|
||||
return new BlogEntry(id, Map.of("en", "My first post", "es", "Mi primera entrada"),
|
||||
Map.of("en", "The very first."), List.of("en", "es"), null, Map.of("es", "primera-entrada"),
|
||||
null, true, publishedOn, author, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMarkdownEntryRendersInsideTheTenantsChromeWithPluginLabels(@TempDir Path tmp) throws IOException {
|
||||
Rig rig = rig(tmp, Map.of());
|
||||
rig.store().save("acme", entry("first-post", "2026-07-17", null),
|
||||
Map.of("en", "Hello **world**.", "es", "Hola **mundo**."));
|
||||
|
||||
String html = rig.render("first-post", EN);
|
||||
assertTrue(html.contains("ACME-MASTER"), "the TENANT's master head wraps the entry");
|
||||
assertTrue(html.contains("acme header") && html.contains("acme footer"), "tenant chrome seams");
|
||||
assertTrue(html.contains("My first post"), "the entry title");
|
||||
assertTrue(html.contains("Hello <strong>world</strong>."), "the Markdown body, rendered");
|
||||
assertTrue(html.contains("Published on 2026-07-17") && html.contains("datetime=\"2026-07-17\""),
|
||||
"the plugin's own #{} label + the publication date");
|
||||
assertTrue(html.contains("href=\"/\""), "the back link reads urls['index']");
|
||||
|
||||
String es = rig.render("first-post", ES);
|
||||
assertTrue(es.contains("Mi primera entrada") && es.contains("Hola <strong>mundo</strong>."), "the es payload");
|
||||
assertTrue(es.contains("Publicado el 2026-07-17"), "the plugin's es label");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAuthoredEntryRendersAByline(@TempDir Path tmp) throws IOException {
|
||||
Rig rig = rig(tmp, Map.of());
|
||||
rig.store().save("acme", entry("authored", "2026-07-17", "Jane Doe"), Map.of("en", "Body."));
|
||||
String html = rig.render("authored", EN);
|
||||
assertTrue(html.contains("By Jane Doe"), () -> "expected a rendered byline; got:\n" + html);
|
||||
assertTrue(html.contains("2026-07-17"), "the date still renders alongside it");
|
||||
}
|
||||
|
||||
/** The meta line used to render only with a date; an undated but authored post must keep its byline. */
|
||||
@Test
|
||||
void anUndatedButAuthoredEntryStillRendersItsByline(@TempDir Path tmp) throws IOException {
|
||||
Rig rig = rig(tmp, Map.of());
|
||||
rig.store().save("acme", entry("undated", null, "Richard Roe"), Map.of("en", "Body."));
|
||||
String html = rig.render("undated", EN);
|
||||
assertTrue(html.contains("By Richard Roe"), () -> "an undated entry must still show its byline:\n" + html);
|
||||
assertFalse(html.contains("Published on"), "…and must not show an empty date label");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntryWithNeitherAuthorNorDateRendersNoMetaLine(@TempDir Path tmp) throws IOException {
|
||||
Rig rig = rig(tmp, Map.of());
|
||||
rig.store().save("acme", entry("bare", null, null), Map.of("en", "Body."));
|
||||
String html = rig.render("bare", EN);
|
||||
assertFalse(html.contains("blog-entry-meta"), () -> "no meta line when there is nothing in it:\n" + html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMinimalTemplateRendersTitleAndBodyOnly(@TempDir Path tmp) throws IOException {
|
||||
Rig rig = rig(tmp, Map.of("template", "entry-minimal"));
|
||||
rig.store().save("acme", entry("min", "2026-07-17", "Jane Doe"), Map.of("en", "Just **this**."));
|
||||
String html = rig.render("min", EN);
|
||||
assertTrue(html.contains("ACME-MASTER") && html.contains("acme footer"), "the same tenant chrome");
|
||||
assertTrue(html.contains("My first post") && html.contains("Just <strong>this</strong>."), "title + body");
|
||||
assertFalse(html.contains("Jane Doe") || html.contains("Published on") || html.contains("entry-back"),
|
||||
"no byline, no date, no back link");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* {@link BlogStore} over the kernel's {@code PluginSiteFiles} (the testkit's {@link TempDirSiteFiles}, which applies
|
||||
* the kernel's confinement rules): the {@code entries/<id>/entry.yml} + {@code body-<lang>.md} layout under the
|
||||
* site's own folder, the metadata/body split, id/lang safety, the derived {@code updatedAt} — and that entries
|
||||
* <b>written by blog 1.3.1</b> (the fixture under {@code src/test/resources/fixtures/blog-1.3.1}, produced by the
|
||||
* 1.3.1 store itself) load unchanged, and are written back byte for byte.
|
||||
*/
|
||||
class BlogStoreTest {
|
||||
|
||||
static final Path FIXTURE = Path.of("src/test/resources/fixtures/blog-1.3.1/entries");
|
||||
|
||||
private static BlogStore store(Path sites) throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
Files.createDirectories(sites.resolve("globex"));
|
||||
return new BlogStore(new TempDirSiteFiles(sites, "blog"));
|
||||
}
|
||||
|
||||
private static BlogEntry entry(String id) {
|
||||
return new BlogEntry(id, Map.of("en", "Hello", "es", "Hola"), Map.of("en", "First post"),
|
||||
List.of("en", "es"), null, Map.of("es", "hola-mundo"), null, true, "2026-07-17", null, null);
|
||||
}
|
||||
|
||||
/** Copies the 1.3.1 entries into a site's plugin subtree, exactly where 1.3.1 kept them. */
|
||||
static Path install131(Path sites, String siteId) throws IOException {
|
||||
Path entries = sites.resolve(siteId).resolve("plugins/blog/entries");
|
||||
try (Stream<Path> walk = Files.walk(FIXTURE)) {
|
||||
for (Path from : walk.toList()) {
|
||||
Path to = entries.resolve(FIXTURE.relativize(from).toString());
|
||||
if (Files.isDirectory(from)) {
|
||||
Files.createDirectories(to);
|
||||
} else {
|
||||
Files.copy(from, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveAndReadRoundTripWithBodies(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("hello-world"), Map.of("en", "# Hi\n\nBody.", "es", "# Hola"));
|
||||
|
||||
BlogEntry read = store.read("acme", "hello-world").orElseThrow();
|
||||
assertEquals("hello-world", read.id(), "the folder name is the id (never stored in the YAML)");
|
||||
assertEquals("Hello", read.title().get("en"));
|
||||
assertEquals("hola-mundo", read.localizedSlugs().get("es"));
|
||||
assertEquals("hello-world", read.effectiveSlug(), "no explicit slug → the id");
|
||||
assertTrue(read.published());
|
||||
assertNotNull(read.updatedAt(), "updatedAt derived from file times");
|
||||
assertEquals("# Hi\n\nBody.", store.readBody("acme", "hello-world", "en"));
|
||||
assertEquals("", store.readBody("acme", "hello-world", "fr"), "no body for that language → empty");
|
||||
assertEquals(List.of("en", "es"), store.bodyLangs("acme", "hello-world"));
|
||||
|
||||
// The files land inside the site's own folder, in the plugin's subtree — the backup-completeness guarantee.
|
||||
Path dir = sites.resolve("acme/plugins/blog/entries/hello-world");
|
||||
assertTrue(Files.isRegularFile(dir.resolve("entry.yml")));
|
||||
assertTrue(Files.isRegularFile(dir.resolve("body-en.md")));
|
||||
assertFalse(Files.readString(dir.resolve("entry.yml")).contains("hello-world"),
|
||||
"the id is never written into the YAML");
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesWrittenBy131LoadUnchanged(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
install131(sites, "acme");
|
||||
|
||||
assertEquals(List.of("launch", "no-author", "hello-world", "draft-post"),
|
||||
store.list("acme").stream().map(BlogEntry::id).toList(),
|
||||
"all four, newest publication date first, undated last");
|
||||
|
||||
BlogEntry hello = store.read("acme", "hello-world").orElseThrow();
|
||||
assertEquals(Map.of("en", "Hello world", "es", "Hola mundo"), hello.title());
|
||||
assertEquals(Map.of("en", "The very first post.", "es", "La primera entrada."), hello.description());
|
||||
assertEquals(List.of("en", "es"), hello.locales());
|
||||
assertEquals(Map.of("es", "hola-mundo"), hello.localizedSlugs());
|
||||
assertTrue(hello.published());
|
||||
assertEquals("2026-07-17", hello.publishedOn());
|
||||
assertEquals("Jane Doe", hello.author());
|
||||
assertNotNull(hello.updatedAt());
|
||||
assertEquals("# Hello\n\nSome **bold** words and a [link](/about).\n",
|
||||
store.readBody("acme", "hello-world", "en"));
|
||||
assertEquals(List.of("en", "es"), store.bodyLangs("acme", "hello-world"));
|
||||
|
||||
BlogEntry unattributed = store.read("acme", "no-author").orElseThrow();
|
||||
assertNull(unattributed.author(), "an entry 1.3.1 wrote without an author loads unattributed");
|
||||
assertEquals("2026-08-01", unattributed.publishedOn());
|
||||
assertTrue(unattributed.published());
|
||||
|
||||
BlogEntry launch = store.read("acme", "launch").orElseThrow();
|
||||
assertEquals("v2", launch.slug());
|
||||
assertEquals("/announcing-v2", launch.customPath());
|
||||
assertEquals("Richard Roe", launch.author());
|
||||
|
||||
BlogEntry draft = store.read("acme", "draft-post").orElseThrow();
|
||||
assertFalse(draft.published());
|
||||
assertNull(draft.publishedOn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void savingAn131EntryBackWritesTheSameBytes(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
Path entries = install131(sites, "acme");
|
||||
for (String id : List.of("hello-world", "no-author", "launch", "draft-post")) {
|
||||
String before = Files.readString(entries.resolve(id).resolve("entry.yml"), StandardCharsets.UTF_8);
|
||||
store.save("acme", store.read("acme", id).orElseThrow(), null);
|
||||
assertEquals(before, Files.readString(entries.resolve(id).resolve("entry.yml"), StandardCharsets.UTF_8),
|
||||
id + ": entry.yml is written back exactly as the 1.3.1 store wrote it");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHandWrittenEntryWithMissingAndUnknownKeysStillLoads(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
Path dir = sites.resolve("acme/plugins/blog/entries/by-hand");
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve("entry.yml"), "title:\n en: \"By hand\"\nfutureKey: 42\n");
|
||||
BlogEntry entry = store.read("acme", "by-hand").orElseThrow();
|
||||
assertEquals("By hand", entry.title().get("en"));
|
||||
assertFalse(entry.published(), "an omitted 'published:' defaults (lenient), never fails the entry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyEntryFileIsAbsent(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
Path dir = sites.resolve("acme/plugins/blog/entries/empty");
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve("entry.yml"), "");
|
||||
assertTrue(store.read("acme", "empty").isEmpty());
|
||||
assertTrue(store.list("acme").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatedAtIsTheNewestFileTimeOfTheEntry(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("post"), Map.of("en", "body"));
|
||||
Path dir = sites.resolve("acme/plugins/blog/entries/post");
|
||||
Files.setLastModifiedTime(dir.resolve("entry.yml"), FileTime.from(Instant.parse("2026-01-01T00:00:00Z")));
|
||||
Files.setLastModifiedTime(dir.resolve("body-en.md"), FileTime.from(Instant.parse("2026-03-01T00:00:00Z")));
|
||||
assertEquals(Instant.parse("2026-03-01T00:00:00Z"), store.read("acme", "post").orElseThrow().updatedAt(),
|
||||
"a body-only edit moves updatedAt (and so the ETag and <lastmod>)");
|
||||
Files.setLastModifiedTime(dir.resolve("entry.yml"), FileTime.from(Instant.parse("2026-05-01T00:00:00Z")));
|
||||
assertEquals(Instant.parse("2026-05-01T00:00:00Z"), store.read("acme", "post").orElseThrow().updatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankBodyDeletesThatLanguagesFile(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("post"), Map.of("en", "text", "es", "texto"));
|
||||
Map<String, String> bodies = new java.util.HashMap<>();
|
||||
bodies.put("es", " ");
|
||||
bodies.put("fr", null);
|
||||
store.save("acme", entry("post"), bodies);
|
||||
assertEquals("text", store.readBody("acme", "post", "en"), "untouched language kept");
|
||||
assertEquals("", store.readBody("acme", "post", "es"), "blanked language's file removed");
|
||||
assertEquals(List.of("en"), store.bodyLangs("acme", "post"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesTheWholeEntry(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("gone"), Map.of("en", "x", "es", "y"));
|
||||
store.save("acme", entry("kept"), Map.of("en", "z"));
|
||||
store.delete("acme", "gone");
|
||||
assertTrue(store.read("acme", "gone").isEmpty());
|
||||
assertFalse(Files.exists(sites.resolve("acme/plugins/blog/entries/gone")));
|
||||
assertTrue(store.read("acme", "kept").isPresent(), "only that entry");
|
||||
store.delete("acme", "never-existed");
|
||||
store.delete("acme", "../escape");
|
||||
assertTrue(Files.isDirectory(sites.resolve("acme/plugins/blog/entries")), "unsafe ids are a no-op");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsafeIdsNeverTouchThePathAndUnsafeLangsThrowBeforeWriting(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
assertTrue(store.read("acme", "../escape").isEmpty(), "a traversal id is an empty read, not a probe");
|
||||
assertTrue(store.read("acme", "has:colon").isEmpty(), "':' is out — blog:<id> must stay unambiguous");
|
||||
assertEquals("", store.readBody("acme", "x", "../en"), "a traversal lang reads empty");
|
||||
assertEquals("", store.readBody("acme", "../x", "en"), "a traversal id reads empty");
|
||||
assertEquals(List.of(), store.bodyLangs("acme", "../x"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> store.save("acme", entry("post"), Map.of("../en", "x")), "an unsafe lang never writes");
|
||||
assertTrue(store.read("acme", "post").isEmpty(), "…not even the metadata");
|
||||
assertThrows(IllegalArgumentException.class, () -> BlogStore.requireSafeId("Bad:Id"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlogStore.requireSafeId(null));
|
||||
assertThrows(IllegalArgumentException.class, () -> store.save("acme", entry("-bad"), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listSortsNewestFirstAndSkipsForeignFoldersAndFiles(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", new BlogEntry("older", Map.of("en", "Old"), Map.of(), List.of("en"), null,
|
||||
Map.of(), null, true, "2026-01-01", null, null), null);
|
||||
store.save("acme", new BlogEntry("newer", Map.of("en", "New"), Map.of(), List.of("en"), null,
|
||||
Map.of(), null, true, "2026-07-01", null, null), null);
|
||||
store.save("acme", new BlogEntry("a-same-day", Map.of("en", "A"), Map.of(), List.of("en"), null,
|
||||
Map.of(), null, true, "2026-07-01", null, null), null);
|
||||
Files.createDirectories(sites.resolve("acme/plugins/blog/entries/.hidden-junk"));
|
||||
Files.writeString(sites.resolve("acme/plugins/blog/entries/stray-file"), "x");
|
||||
Files.createDirectories(sites.resolve("acme/plugins/blog/entries/no-metadata"));
|
||||
|
||||
assertEquals(List.of("a-same-day", "newer", "older"),
|
||||
store.list("acme").stream().map(BlogEntry::id).toList(),
|
||||
"newest publication date first, then id; non-conforming folders, files and empty folders skipped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorruptEntryIsSkippedNotFatal(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("good"), Map.of("en", "fine"));
|
||||
Path corrupt = sites.resolve("acme/plugins/blog/entries/broken");
|
||||
Files.createDirectories(corrupt);
|
||||
Files.writeString(corrupt.resolve("entry.yml"), "title: [unclosed");
|
||||
assertEquals(List.of("good"), store.list("acme").stream().map(BlogEntry::id).toList());
|
||||
assertTrue(store.read("acme", "broken").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSymlinkedEntryFolderCannotLeadOutOfTheSubtree(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("good"), Map.of("en", "fine"));
|
||||
// Another site's data, reached through a link planted inside acme's blog folder.
|
||||
store.save("globex", entry("secret"), Map.of("en", "globex only"));
|
||||
Files.createSymbolicLink(sites.resolve("acme/plugins/blog/entries/secret"),
|
||||
sites.resolve("globex/plugins/blog/entries/secret"));
|
||||
assertEquals(List.of("good"), store.list("acme").stream().map(BlogEntry::id).toList(),
|
||||
"a link is never listed");
|
||||
assertThrows(IllegalArgumentException.class, () -> store.read("acme", "secret"),
|
||||
"reading through the link is refused by the kernel's real-path rule");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sitesAreIsolated(@TempDir Path sites) throws IOException {
|
||||
BlogStore store = store(sites);
|
||||
store.save("acme", entry("post"), Map.of("en", "acme text"));
|
||||
assertTrue(store.list("globex").isEmpty());
|
||||
assertEquals("", store.readBody("globex", "post", "en"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteWithNoBlogFolderListsNothing(@TempDir Path sites) throws IOException {
|
||||
assertTrue(store(sites).list("acme").isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package mx.quest.blog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring6.expression.ThymeleafEvaluationContext;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.FileTemplateResolver;
|
||||
|
||||
/**
|
||||
* Renders this plugin's SHIPPED templates ({@code templates/*.html} + their decoupled {@code .th.xml} logic) with
|
||||
* Thymeleaf's own Spring engine — no kernel class. The templates are copied under the logical names the kernel uses
|
||||
* ({@code __plugin__/blog/<name>}), a site master can be added next to them, and {@code #{…}} resolves from this
|
||||
* plugin's own bundles ({@code i18n/messages*.properties}), as the kernel appends them.
|
||||
*
|
||||
* <p>What this cannot see is anything the kernel adds beyond the documented render model — which is the point: a
|
||||
* template that renders here needs nothing but the contract.
|
||||
*/
|
||||
final class TemplateHarness {
|
||||
|
||||
private final Path root;
|
||||
private final SpringTemplateEngine engine;
|
||||
|
||||
TemplateHarness(Path root) {
|
||||
this.root = root;
|
||||
try {
|
||||
Path target = root.resolve("__plugin__/blog");
|
||||
Files.createDirectories(target);
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.toList()) {
|
||||
Files.copy(file, target.resolve(file.getFileName().toString()));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
FileTemplateResolver resolver = new FileTemplateResolver();
|
||||
resolver.setPrefix(root.toAbsolutePath() + "/");
|
||||
resolver.setSuffix(".html");
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setUseDecoupledLogic(true);
|
||||
resolver.setCacheable(false);
|
||||
ReloadableResourceBundleMessageSource messages = new ReloadableResourceBundleMessageSource();
|
||||
messages.setBasename("file:" + Path.of("i18n/messages").toAbsolutePath());
|
||||
messages.setDefaultEncoding("UTF-8");
|
||||
messages.setFallbackToSystemLocale(false);
|
||||
engine = new SpringTemplateEngine();
|
||||
engine.setTemplateResolver(resolver);
|
||||
engine.setTemplateEngineMessageSource(messages);
|
||||
}
|
||||
|
||||
/** Writes a site master ({@code <name>.html} + an empty logic file) and returns its logical name. */
|
||||
String master(String name, String html) {
|
||||
try {
|
||||
Path file = root.resolve(name + ".html");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, html, StandardCharsets.UTF_8);
|
||||
Files.writeString(root.resolve(name + ".th.xml"), "<?xml version=\"1.0\"?><thlogic></thlogic>",
|
||||
StandardCharsets.UTF_8);
|
||||
return name;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
String render(String template, Locale locale, Map<String, Object> vars) {
|
||||
GenericApplicationContext app = new GenericApplicationContext();
|
||||
app.refresh();
|
||||
Context ctx = new Context(locale);
|
||||
vars.forEach(ctx::setVariable);
|
||||
ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
|
||||
new ThymeleafEvaluationContext(app, DefaultConversionService.getSharedInstance()));
|
||||
return engine.process(template, ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Not yet.
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
title:
|
||||
en: "Work in progress"
|
||||
description: {}
|
||||
locales:
|
||||
- "en"
|
||||
localizedSlugs: {}
|
||||
published: false
|
||||
@@ -0,0 +1,3 @@
|
||||
# Hello
|
||||
|
||||
Some **bold** words and a [link](/about).
|
||||
@@ -0,0 +1,3 @@
|
||||
# Hola
|
||||
|
||||
Unas palabras **en negrita**.
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title:
|
||||
es: "Hola mundo"
|
||||
en: "Hello world"
|
||||
description:
|
||||
es: "La primera entrada."
|
||||
en: "The very first post."
|
||||
locales:
|
||||
- "en"
|
||||
- "es"
|
||||
localizedSlugs:
|
||||
es: "hola-mundo"
|
||||
published: true
|
||||
publishedOn: "2026-07-17"
|
||||
author: "Jane Doe"
|
||||
@@ -0,0 +1 @@
|
||||
Version two is here.
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title:
|
||||
en: "Announcing v2"
|
||||
description: {}
|
||||
locales:
|
||||
- "en"
|
||||
slug: "v2"
|
||||
localizedSlugs: {}
|
||||
customPath: "/announcing-v2"
|
||||
published: true
|
||||
publishedOn: "2026-09-10"
|
||||
author: "Richard Roe"
|
||||
@@ -0,0 +1 @@
|
||||
Written before bylines existed.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title:
|
||||
en: "Unattributed"
|
||||
description:
|
||||
en: "Nobody signed this."
|
||||
locales:
|
||||
- "en"
|
||||
localizedSlugs: {}
|
||||
published: true
|
||||
publishedOn: "2026-08-01"
|
||||
@@ -0,0 +1,96 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>Blog entry</title></head>
|
||||
<body>
|
||||
<div id="content">
|
||||
<div class="page-header d-print-none mb-3">
|
||||
<div class="row align-items-center">
|
||||
<div class="col">
|
||||
<div class="page-pretitle" id="be-pretitle">Site</div>
|
||||
<h2 class="page-title" id="be-heading">Edit entry</h2>
|
||||
</div>
|
||||
<div class="col-auto"><a class="btn" id="be-back" href="/__admin/blog">Back to blog</a></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The reverse advisory: a real PAGE owns this entry's URL — the
|
||||
page wins, so the entry is unreachable there. Rendered only when it applies. -->
|
||||
<div class="alert alert-warning" id="be-shadowed" role="alert">
|
||||
<span id="be-shadowed-text">A page owns this entry's address.</span>
|
||||
<span id="be-shadowed-by" class="font-monospace">page</span>
|
||||
</div>
|
||||
|
||||
<form id="be-form" method="post" action="/__admin/blog/x">
|
||||
<input id="be-csrf" type="hidden" name="_csrf" value="">
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="be-l-entry">Entry</h3></div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4" id="be-id-wrap">
|
||||
<label class="form-label" id="be-l-id" for="be-id">Id</label>
|
||||
<input id="be-id" class="form-control font-monospace" type="text" name="id" value=""
|
||||
placeholder="my-first-post">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" id="be-l-date" for="be-date">Publication date</label>
|
||||
<input id="be-date" class="form-control" type="date" name="publishedOn" value="">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" id="be-l-author" for="be-author">Author</label>
|
||||
<input id="be-author" class="form-control" type="text" name="author" value=""
|
||||
placeholder="Jane Doe">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" id="be-l-custom" for="be-custom">Custom path</label>
|
||||
<input id="be-custom" class="form-control font-monospace" type="text" name="customPath"
|
||||
value="" placeholder="/announcing-v2">
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-check form-switch">
|
||||
<input id="be-published" class="form-check-input" type="checkbox" name="published">
|
||||
<span class="form-check-label" id="be-l-published">Published</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- One card per site language: title, description, slug, body (Markdown). -->
|
||||
<div class="card mb-3" id="be-lang-card">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title"><span id="be-lang-name">en</span></h3>
|
||||
<div class="card-actions">
|
||||
<label class="form-check mb-0">
|
||||
<input id="be-lang-on" class="form-check-input" type="checkbox" name="locales_en">
|
||||
<span class="form-check-label" id="be-l-langon">Published in this language</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-8">
|
||||
<label class="form-label be-l-title">Title</label>
|
||||
<input class="form-control be-title" type="text" name="title_en" value="">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label be-l-slug">Slug</label>
|
||||
<input class="form-control font-monospace be-slug" type="text" name="slug_en" value="">
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label be-l-desc">Description</label>
|
||||
<input class="form-control be-desc" type="text" name="description_en" value="">
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label be-l-body">Body (Markdown)</label>
|
||||
<textarea class="form-control font-monospace be-body" name="body_en" rows="10"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" id="be-save">Save</button>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Blog entry editor. One language card per SITE locale (th:each over siteLocaleTags); the default
|
||||
language's slug field doubles as the base slug. On CREATE the form posts to /create with an editable id;
|
||||
on EDIT the id is readonly and the form posts to /__admin/blog/<id>. `//` reaches nested elements
|
||||
(`/` matches direct children only); the published/keep ternaries stay at the Thymeleaf level (a message
|
||||
expression cannot nest inside a SpEL expression). -->
|
||||
<thlogic>
|
||||
<attr sel="#be-pretitle" th:text="#{blog.admin.pretitle}"/>
|
||||
<attr sel="#be-heading" th:text="${creating} ? #{blog.edit.headingNew} : #{blog.edit.heading}"/>
|
||||
<attr sel="#be-back" th:text="#{blog.edit.back}"/>
|
||||
|
||||
<attr sel="#be-shadowed" th:if="${!shadowedBy.isEmpty()}"/>
|
||||
<attr sel="#be-shadowed-text" th:text="#{blog.edit.shadowed}"/>
|
||||
<attr sel="#be-shadowed-by" th:text="${#strings.listJoin(shadowedBy, ', ')}"/>
|
||||
|
||||
<!-- The action is model-computed (two '/__admin' literals in one expression would trip Thymeleaf's
|
||||
__…__ preprocessing). -->
|
||||
<attr sel="#be-form" th:attr="action=${formAction}"/>
|
||||
<attr sel="#be-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
|
||||
<attr sel="#be-l-entry" th:text="#{blog.edit.entry}"/>
|
||||
<attr sel="#be-l-id" th:text="#{blog.edit.id}"/>
|
||||
<attr sel="#be-id" th:attr="value=${creating ? '' : entry.id()},readonly=${creating ? null : 'readonly'},
|
||||
title=#{blog.edit.id.tip}"/>
|
||||
<attr sel="#be-l-date" th:text="#{blog.edit.date}"/>
|
||||
<attr sel="#be-date" th:attr="value=${entry.publishedOn()}"/>
|
||||
<attr sel="#be-l-author" th:text="#{blog.edit.author}"/>
|
||||
<attr sel="#be-author" th:attr="value=${entry.author()},title=#{blog.edit.author.tip}"/>
|
||||
<attr sel="#be-l-custom" th:text="#{blog.edit.customPath}"/>
|
||||
<attr sel="#be-custom" th:attr="value=${entry.customPath()},title=#{blog.edit.customPath.tip}"/>
|
||||
<attr sel="#be-l-published" th:text="#{blog.edit.published}"/>
|
||||
<attr sel="#be-published" th:attr="checked=${entry.published() ? 'checked' : null}"/>
|
||||
|
||||
<!-- One card per site language; every inner field is renamed to its <field>_<lang> form name. -->
|
||||
<attr sel="#be-lang-card" th:each="lang : ${siteLocaleTags}"/>
|
||||
<attr sel="#be-lang-card//#be-lang-name"
|
||||
th:text="${lang == defaultLocaleTag} ? (${lang} + ' · ' + #{blog.edit.defaultLang}) : ${lang}"/>
|
||||
<attr sel="#be-lang-card//#be-lang-on"
|
||||
th:attr="name='locales_' + ${lang},checked=${entry.locales().contains(lang) ? 'checked' : null}"/>
|
||||
<attr sel="#be-lang-card//#be-l-langon" th:text="#{blog.edit.langOn}"/>
|
||||
<attr sel="#be-lang-card//.be-l-title" th:text="#{blog.edit.title}"/>
|
||||
<attr sel="#be-lang-card//.be-title"
|
||||
th:attr="name='title_' + ${lang},value=${entry.title().get(lang)}"/>
|
||||
<attr sel="#be-lang-card//.be-l-slug" th:text="#{blog.edit.slug}"/>
|
||||
<attr sel="#be-lang-card//.be-slug"
|
||||
th:attr="name='slug_' + ${lang},title=#{blog.edit.slug.tip},
|
||||
value=${lang == defaultLocaleTag ? entry.effectiveSlug() : entry.localizedSlugs().get(lang)}"/>
|
||||
<attr sel="#be-lang-card//.be-l-desc" th:text="#{blog.edit.description}"/>
|
||||
<attr sel="#be-lang-card//.be-desc"
|
||||
th:attr="name='description_' + ${lang},value=${entry.description().get(lang)}"/>
|
||||
<attr sel="#be-lang-card//.be-l-body" th:text="#{blog.edit.body}"/>
|
||||
<attr sel="#be-lang-card//.be-body"
|
||||
th:attr="name='body_' + ${lang}" th:text="${bodies.get(lang)}"/>
|
||||
|
||||
<attr sel="#be-save" th:text="#{blog.edit.save}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,63 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>Blog</title></head>
|
||||
<body>
|
||||
<div id="content">
|
||||
<div class="page-header d-print-none mb-3">
|
||||
<div class="row align-items-center">
|
||||
<div class="col">
|
||||
<div class="page-pretitle" id="bl-pretitle">Site</div>
|
||||
<h2 class="page-title" id="bl-heading">Blog</h2>
|
||||
</div>
|
||||
<div class="col-auto"><a class="btn btn-primary" id="bl-new" href="/__admin/blog/new">New entry</a></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-warning" id="bl-disabled" role="alert">
|
||||
<span id="bl-disabled-text">The blog is disabled for this site (see the plugin's settings) — entries are
|
||||
kept but none serves.</span>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-vcenter card-table" data-listing-table="runway.admin.blog">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-col-key="id" id="bl-h-id">Entry</th>
|
||||
<th data-col-key="path" id="bl-h-path">Path</th>
|
||||
<th data-col-key="langs" id="bl-h-langs">Languages</th>
|
||||
<th data-col-key="date" id="bl-h-date">Date</th>
|
||||
<th data-col-key="status" id="bl-h-status">Status</th>
|
||||
<th data-nosort data-col-key="actions" id="bl-h-actions" class="w-1">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="bl-empty"><td colspan="6" class="text-secondary text-center" id="bl-empty-text">No entries yet.</td></tr>
|
||||
<tr id="bl-row">
|
||||
<td class="b-id font-monospace">id</td>
|
||||
<td class="b-path text-secondary">—</td>
|
||||
<td class="b-langs text-secondary">—</td>
|
||||
<td class="b-date text-secondary">—</td>
|
||||
<td><span class="badge b-badge">status</span></td>
|
||||
<td>
|
||||
<div class="btn-list flex-nowrap">
|
||||
<a class="btn btn-sm b-edit" href="#">Edit</a>
|
||||
<form class="b-publish-form d-inline" method="post" action="#">
|
||||
<input class="b-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" class="btn btn-sm b-publish">Publish</button>
|
||||
</form>
|
||||
<form class="b-delete-form d-inline" method="post" action="#">
|
||||
<input class="b-csrf" type="hidden" name="_csrf" value="">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger b-delete"
|
||||
data-confirm="Delete this entry and all its languages?">Delete</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Blog console list. One row per entry; the publish/delete forms are real POSTs (CSRF hidden input injected
|
||||
per form — the per-site token from ${_csrf}). `//` reaches nested elements (`/` matches direct children only). -->
|
||||
<thlogic>
|
||||
<attr sel="#bl-pretitle" th:text="#{blog.admin.pretitle}"/>
|
||||
<attr sel="#bl-heading" th:text="#{blog.admin.heading}"/>
|
||||
<attr sel="#bl-new" th:text="#{blog.admin.new}" th:attr="title=#{blog.admin.new.tip}"/>
|
||||
|
||||
<attr sel="#bl-disabled" th:if="${!blogEnabled}"/>
|
||||
<attr sel="#bl-disabled-text" th:text="#{blog.admin.disabled}"/>
|
||||
|
||||
<attr sel="#bl-h-id" th:text="#{blog.admin.col.entry}"/>
|
||||
<attr sel="#bl-h-path" th:text="#{blog.admin.col.path}"/>
|
||||
<attr sel="#bl-h-langs" th:text="#{blog.admin.col.langs}"/>
|
||||
<attr sel="#bl-h-date" th:text="#{blog.admin.col.date}"/>
|
||||
<attr sel="#bl-h-status" th:text="#{blog.admin.col.status}"/>
|
||||
<attr sel="#bl-h-actions" th:text="#{blog.admin.col.actions}"/>
|
||||
|
||||
<attr sel="#bl-empty" th:if="${rows.isEmpty()}"/>
|
||||
<attr sel="#bl-empty-text" th:text="#{blog.admin.empty}"/>
|
||||
|
||||
<attr sel="#bl-row" th:each="row : ${rows}"/>
|
||||
<attr sel="#bl-row//.b-id" th:text="${row.entry().id()}"/>
|
||||
<attr sel="#bl-row//.b-path" th:text="${row.publicPath()}"/>
|
||||
<attr sel="#bl-row//.b-langs"
|
||||
th:text="${row.entry().locales().isEmpty() ? '—' : #strings.listJoin(row.entry().locales(), ', ')}"/>
|
||||
<attr sel="#bl-row//.b-date" th:text="${row.entry().publishedOn() != null ? row.entry().publishedOn() : '—'}"/>
|
||||
<attr sel="#bl-row//.b-badge" th:text="${row.entry().published()} ? #{blog.admin.published} : #{blog.admin.draft}"
|
||||
th:classappend="${row.entry().published() ? 'bg-green-lt' : 'bg-yellow-lt'}"/>
|
||||
<attr sel="#bl-row//.b-edit" th:text="#{blog.admin.edit}"
|
||||
th:attr="href='/__admin/blog/' + ${row.entry().id()} + '/edit'"/>
|
||||
<attr sel="#bl-row//.b-publish-form"
|
||||
th:attr="action='/__admin/blog/' + ${row.entry().id()} + '/publish'"/>
|
||||
<attr sel="#bl-row//.b-publish"
|
||||
th:text="${row.entry().published()} ? #{blog.admin.unpublish} : #{blog.admin.publish}"/>
|
||||
<attr sel="#bl-row//.b-delete-form"
|
||||
th:attr="action='/__admin/blog/' + ${row.entry().id()} + '/delete'"/>
|
||||
<attr sel="#bl-row//.b-delete" th:text="#{blog.admin.delete}"
|
||||
th:attr="data-confirm=#{blog.admin.delete.confirm}"/>
|
||||
<!-- The per-site CSRF token on every mutating form (the messages-editor idiom). -->
|
||||
<attr sel="#bl-row//.b-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,31 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Blog entry</title>
|
||||
<!-- Static preview head only — replaced at render by the TENANT's master head (the seam contract). -->
|
||||
</head>
|
||||
<body>
|
||||
<header id="site-header">Site header (from the master at render)</header>
|
||||
|
||||
<main id="content">
|
||||
<article class="blog-entry">
|
||||
<header class="blog-entry-header">
|
||||
<h1 id="entry-title">Entry title</h1>
|
||||
<p id="entry-meta" class="blog-entry-meta">
|
||||
<time id="entry-date">2026-01-01</time>
|
||||
<span id="entry-author">By Someone</span>
|
||||
</p>
|
||||
</header>
|
||||
<div id="entry-body" class="blog-entry-body">
|
||||
<p>The entry body renders here.</p>
|
||||
</div>
|
||||
<footer class="blog-entry-footer">
|
||||
<a id="entry-back" href="/">Back</a>
|
||||
</footer>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
<footer id="site-footer">Site footer (from the master at render)</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Blog entry (classic): the tenant's OWN master supplies head/header/footer (this file is byte-identical across
|
||||
tenants; ALL variance flows through the model). It reads ONLY the body-template render model the
|
||||
SPI documents on ContentSource/ContentRef.bodyTemplate: ${master}, ${content.*} (id, sourceKey,
|
||||
title, description, bodyHtml, attributes, updatedAt), ${locale} and ${urls[...]} — BlogEntryTemplateContractTest
|
||||
fails the build if anything else creeps in. Labels resolve via #{} from THIS plugin's bundles (appended last —
|
||||
a site that defines the same key wins). `//` reaches nested elements (`/` matches direct children only). -->
|
||||
<thlogic>
|
||||
<attr sel="head" th:replace="~{${master} :: head}"/>
|
||||
<attr sel="#site-header" th:replace="~{${master} :: #site-header}"/>
|
||||
<attr sel="#site-footer" th:replace="~{${master} :: #site-footer}"/>
|
||||
|
||||
<attr sel="#entry-title" th:text="${content.title}"/>
|
||||
<!-- Editorial byline. The meta line renders when the entry has a date OR an author, and each part renders
|
||||
independently — an entry with an author but no date (or the reverse) is a normal state, and gating the
|
||||
whole line on the date alone would silently swallow the byline. Each is absent from
|
||||
content.attributes when unset, so nothing renders as an empty element. -->
|
||||
<attr sel="#entry-meta"
|
||||
th:if="${content.attributes['publishedOn'] != null or content.attributes['author'] != null}"/>
|
||||
<attr sel="#entry-meta//#entry-date"
|
||||
th:if="${content.attributes['publishedOn'] != null}"
|
||||
th:text="#{blog.publishedOn} + ' ' + ${content.attributes['publishedOn']}"
|
||||
th:attr="datetime=${content.attributes['publishedOn']}"/>
|
||||
<attr sel="#entry-meta//#entry-author"
|
||||
th:if="${content.attributes['author'] != null}"
|
||||
th:text="#{blog.by} + ' ' + ${content.attributes['author']}"/>
|
||||
<attr sel="#entry-body" th:utext="${content.bodyHtml}"/>
|
||||
<!-- Back to the site home in the CURRENT locale (the home page's locale-correct URL when it exists). -->
|
||||
<attr sel="#entry-back" th:text="#{blog.back}"
|
||||
th:attr="href=${urls['index'] != null ? urls['index'] : '/'}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Blog entry</title>
|
||||
<!-- Static preview head only — replaced at render by the TENANT's master head (the seam contract). -->
|
||||
</head>
|
||||
<body>
|
||||
<header id="site-header">Site header (from the master at render)</header>
|
||||
|
||||
<main id="content">
|
||||
<article class="blog-entry blog-entry-minimal">
|
||||
<h1 id="entry-title">Entry title</h1>
|
||||
<div id="entry-body" class="blog-entry-body">
|
||||
<p>The entry body renders here.</p>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
<footer id="site-footer">Site footer (from the master at render)</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Blog entry (minimal): title + body only — no date line, no back link. Same contract as classic: the tenant's
|
||||
master chrome, only the documented render model (${master}, ${content.*}), tenant-invariant file. -->
|
||||
<thlogic>
|
||||
<attr sel="head" th:replace="~{${master} :: head}"/>
|
||||
<attr sel="#site-header" th:replace="~{${master} :: #site-header}"/>
|
||||
<attr sel="#site-footer" th:replace="~{${master} :: #site-footer}"/>
|
||||
|
||||
<attr sel="#entry-title" th:text="${content.title}"/>
|
||||
<attr sel="#entry-body" th:utext="${content.bodyHtml}"/>
|
||||
</thlogic>
|
||||
Reference in new issue
Block a user