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.3.0] — 2026-10-21
|
||||
|
||||
First public release of `discoverability`: SEO and GEO for Runway sites — `/sitemap.xml`, `/robots.txt`
|
||||
(including groups for AI crawlers), `/llms.txt` and schema.org JSON-LD from one shared core, adding only what the
|
||||
kernel's own SEO leaves out. 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,170 @@
|
||||
# discoverability — SEO+ & GEO for Runway
|
||||
|
||||
One Runway plugin that makes a site legible to **search engines** and **AI answer engines**, sharing a single
|
||||
schema.org **JSON-LD** core. It adds the layer the platform's lean SEO deliberately leaves out — it **never
|
||||
duplicates** a tag the kernel already emits (canonical, `hreflang`, `robots`, Open Graph, Twitter cards are
|
||||
free).
|
||||
|
||||
- **SEO+** — JSON-LD structured data (`WebSite` / `WebPage`|`Article` / `Organization` / `BreadcrumbList`) in
|
||||
every indexable page's `<head>`; a per-site **`/sitemap.xml`** with `hreflang` alternates.
|
||||
|
||||
**Since 1.1.0** the sitemap and `llms.txt` enumerate the host's whole **content catalog** — kernel pages AND
|
||||
every content source's items (blog entries, any plugin content) — fail-closed re-filtered by the kernel, with the
|
||||
URLs the kernel computes for the page head too, so head and sitemap provably agree (since 2.0.0 through the
|
||||
SPI's `ContentCatalogView`). Every item now carries a `<lastmod>` (from its `updatedAt`; pages gain this for the first time).
|
||||
Content whose URL collides with the reserved surface (e.g. a page at `/login`) is no longer listed.
|
||||
- **GEO** (opt-in) — **`/llms.txt`** (a compact, machine-friendly page index for LLM/answer engines); a
|
||||
`SearchAction` + `Speakable` **answer schema** that enriches the SEO JSON-LD by `@id`.
|
||||
|
||||
Everything is per-site: SEO+ on by default, GEO opt-in — no restart to change (per-tenant config applies live).
|
||||
|
||||
- **What it does & how it maps to seams:** [`docs/DISCOVERABILITY-PLUGIN.md`](docs/DISCOVERABILITY-PLUGIN.md)
|
||||
- **How to build any Runway plugin:** [`../docs/PLUGIN-AUTHORING-GUIDE.md`](../docs/PLUGIN-AUTHORING-GUIDE.md)
|
||||
|
||||
## Links only the Runway SPI (2.0.0+)
|
||||
|
||||
2.0.0 compiles against `runway-spi` alone: settings through `PluginSettings`, the content listing and its URLs
|
||||
through `ContentCatalogView`, sites through `Sites`, and IndexNow as a `SiteEventListener` that receives each
|
||||
change with the item's URLs before and after it — so **unpublished, deleted and moved pages are now submitted**,
|
||||
and only by the node where the change happened. Everything it serves for an unchanged site is byte-for-byte what
|
||||
1.6.0 served, except three fixes (an item missing from the default locale is linked at its real URL in
|
||||
`llms.txt`; a root-relative self canonical no longer drops a page from the sitemap; a host-less site's fallback
|
||||
base is the request's trusted origin). The console bean is now `discoverabilityAdminModel`.
|
||||
|
||||
**Upgrade:** no data or setting changes. Details: [`CHANGELOG.md`](CHANGELOG.md),
|
||||
[`docs/DISCOVERABILITY-PLUGIN.md`](docs/DISCOVERABILITY-PLUGIN.md) §2.
|
||||
|
||||
## Absolute JSON-LD on a host-less site; llms.txt revalidates honestly (2.1.0, needs SPI 1.0.0)
|
||||
|
||||
A site with neither a base URL nor a host name (the platform's catch-all default) now gets absolute `@id`s and
|
||||
URLs in its JSON-LD — built on `HeadContext.origin()`, the trusted origin the page is served under — and with them
|
||||
the GEO `SearchAction` and the breadcrumb trail it never had. `llms.txt`'s `Last-Modified` now advances when only
|
||||
the site name, `geo.summary` or the base URL changes. **Needs Runway 1.0.0 or later** (SPI `1.0.0`; an older
|
||||
kernel blocks it with a reason). Details: [`CHANGELOG.md`](CHANGELOG.md).
|
||||
|
||||
## A settings page in sections, every field explained (1.6.0+)
|
||||
|
||||
The per-site settings page is laid out in six sections — structured data, sitemap & robots.txt, AI crawlers,
|
||||
GEO, product on the homepage, IndexNow — with a help line under every field (English and Spanish), a
|
||||
**Learn more** link into the matching section of the help page, rarely needed fields under **Advanced**, and
|
||||
fields hidden while the switch they depend on is off. A site that turns IndexNow on while the platform has it
|
||||
off is told so on the form, and the operator gets one WARN per site in the log. No setting changed name, type,
|
||||
default or meaning. Details:
|
||||
[`docs/DISCOVERABILITY-PLUGIN.md`](docs/DISCOVERABILITY-PLUGIN.md) §4.
|
||||
|
||||
## IndexNow, AI crawlers by class, and a sitemap index (1.5.0+)
|
||||
|
||||
**IndexNow (opt-in twice).** Tells Bing, Yandex, Seznam, Naver and Yep when a site's content changes.
|
||||
**Google does not participate** — this is a freshness signal for those engines, not a ranking one anywhere.
|
||||
|
||||
It is the only feature here that makes an outbound request, so it takes two switches, both off by default: the
|
||||
platform operator permits it (`runway.plugin.discoverability.indexnow.enabled`) and the tenant enables it plus
|
||||
sets a key. The key is served at `/indexnow-key.txt` and named in every submission via the spec's
|
||||
`keyLocation`. Submissions are batched, capped, and dropped rather than retried on failure.
|
||||
|
||||
|
||||
**Decline training while staying citable.** The three AI-agent classes — *training*, *live retrieval*,
|
||||
*user-triggered fetch* — carry opposite consequences, and each now has its own per-site setting
|
||||
(`robots.ai-training`, `robots.ai-retrieval`, `robots.ai-user`; `inherit` by default, meaning "whatever
|
||||
`robots.ai-policy` says"). Declining training costs a site nothing it can see; declining retrieval removes it
|
||||
from generated answers; declining user-triggered fetch breaks a visit somebody initiated. One switch could not
|
||||
express that.
|
||||
|
||||
A site that sets none of them gets a **byte-identical** `robots.txt` to before.
|
||||
|
||||
**`/sitemap.xml` becomes an index only when it has to.** Under 10,000 URLs it stays exactly the single
|
||||
`<urlset>` it always was. Past that it is a `<sitemapindex>` over `/sitemap-1.xml` … `/sitemap-N.xml`, up to 20
|
||||
shards (200,000 URLs). Shard membership comes from the **sorted** URL list, not source-registration order, so
|
||||
two nodes behind a load balancer cannot serve different content for the same shard number.
|
||||
|
||||
## Per-site settings reach the page ETag (1.4.2+)
|
||||
|
||||
`StructuredDataHead` declares its per-site settings file (`plugins/discoverability.yml`) through
|
||||
`HeadContributor#headInputs`, so the kernel folds it into every page's `ETag`.
|
||||
|
||||
Before that, it did not. Head markup is spliced in at the **response edge**, after the page validator has been
|
||||
computed and possibly answered `304` with no body — so changing the organisation name, the GEO block or the
|
||||
search URL changed the delivered page and **not** its validator. Every client and CDN holding the old one kept
|
||||
the previous markup indefinitely, until some unrelated file happened to move; the operator, checking with a
|
||||
fresh fetch, saw the new value and reasonably concluded it was live.
|
||||
|
||||
**If you add a head contributor that reads a file, declare it.** An undeclared input is invisible to the
|
||||
validator and fails silently, in the direction that looks correct.
|
||||
|
||||
## Reproducible structured data (1.4.1+)
|
||||
|
||||
The emitted JSON-LD is **byte-reproducible**: the same inputs always render the same bytes, across restarts
|
||||
and across machines.
|
||||
|
||||
That was not true before 1.4.1. `SearchAction.target` was built with `Map.of(...)`, and `java.util.Map.of`
|
||||
randomizes iteration order **per JVM instance**, so the key order flipped on roughly every other restart —
|
||||
stable within one run, different after the next. Semantically harmless (the graphs are equal key-sorted), but
|
||||
it made rendered pages non-reproducible and quietly broke the promise of a page's strong `ETag`, which folds
|
||||
metadata and templates rather than the body and therefore did *not* change when the bytes did.
|
||||
|
||||
**If you extend the schema types: never build a serialized node with a multi-entry `Map.of(...)`.** Use
|
||||
`Ld.node(...)` or a `LinkedHashMap`. A test enforces this at the source level, deliberately — the behavioural
|
||||
test alone catches a reintroduction only about half the time, because the defect is probabilistic.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
mvn verify # SPI-only: runway-spi + runway-spi-testkit
|
||||
mvn -P host-it verify # + the host-integration tests (runway-app, test scope)
|
||||
```
|
||||
|
||||
Produces the thin `target/runway-plugin-discoverability.jar` (running the plugin's unit tests — 178;
|
||||
the `host-it` profile adds 6 that run the plugin against the real kernel classes) and **both** installable forms:
|
||||
`target/discoverability/` (folder) and `target/runway-plugin-discoverability-<version>.zip` (the UI-upload archive).
|
||||
|
||||
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 (the `host-it` profile needs
|
||||
`runway-app` there too).
|
||||
|
||||
## Install (either path, then restart the host)
|
||||
|
||||
> **Upgrading? Do not park the old version inside `external/plugins/`.** The loader scans that directory and
|
||||
> reads every `plugin.yml`; a parked copy still declares the same `id:`, so the scan sees a duplicate id and
|
||||
> **fails fast at startup** — the platform refuses to boot because someone kept a rollback copy. Renaming the
|
||||
> folder does not help; the id inside the descriptor is what collides. Park it outside the tree, or keep the
|
||||
> release zip.
|
||||
|
||||
|
||||
```bash
|
||||
cp -r target/discoverability <runway-external>/plugins/ # 1. filesystem
|
||||
# 2. app console → /__app/plugins → install → upload runway-plugin-discoverability-<version>.zip
|
||||
```
|
||||
|
||||
Loads only in **ACTIVE** mode (after first-run setup). Configure per site on the plugin's tenant settings page.
|
||||
|
||||
## Verify (one command)
|
||||
|
||||
```bash
|
||||
scripts/verify-against-host.sh # build → throwaway Runway → boot ACTIVE → prove the live contract
|
||||
scripts/verify-against-host.sh --keep # ... and leave it running (prints the URL)
|
||||
HOST_JAR=/path/runway-app-<ver>-exec.jar VERIFY_TMPDIR=/dir VERIFY_LOG_DIR=/dir scripts/verify-against-host.sh
|
||||
PREVIOUS_DIR=/path/to/<previous>/target/discoverability scripts/compare-with-previous.sh # before/after diff
|
||||
```
|
||||
|
||||
The verifier checks the load (zero host-linkage and bean-name warnings), JSON-LD on `/`, `/sitemap.xml`,
|
||||
`/robots.txt`, `/llms.txt`, the settings form, the console card and fragment, and IndexNow both off (inert) and on
|
||||
(an unpublished page's old URLs reach a local fake endpoint). It never runs `mvn install`. Both scripts need
|
||||
`JAVA_HOME` set to a JDK 25 and use `mvn` from the `PATH` (or `MVN`). Without `HOST_JAR` they use the host exec
|
||||
jar under `runway-app/target/` of the kernel at the root of this repository (`HOST_TARGET` names another),
|
||||
matching the host pom's version.
|
||||
|
||||
## Try it (after installing + enabling GEO on a site)
|
||||
|
||||
- View any public page source → `<script type="application/ld+json">` with the entity graph.
|
||||
- `GET /sitemap.xml` — the whole published content surface + `hreflang` + `<lastmod>`.
|
||||
- `GET /llms.txt` — the AI-facing index (when GEO is enabled).
|
||||
|
||||
_Java package `mx.quest.discover` · plugin id `discoverability` · version 2.3.0 · built against `runway-spi`
|
||||
1.0.0 (SPI 1.0.0) · declared SPI floor 1.0.0._
|
||||
|
||||
## 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,375 @@
|
||||
# The `discoverability` plugin — design, features & verification
|
||||
|
||||
> **SEO+ and GEO in one plugin**, sharing one schema.org JSON-LD core. It enriches the head the Runway kernel
|
||||
> already fills (canonical + hreflang + the full Open Graph / Twitter social card) with the **structured-data**
|
||||
> the lean core leaves out, and **owns the crawl surfaces** the core does not ship: `/sitemap.xml`, `/llms.txt`
|
||||
> and `/robots.txt`. The second reference plugin (after `../demo`) — a real, cohesive feature.
|
||||
|
||||
- **id:** `discoverability` · **version:** `2.3.0` · **install folder:** `external/plugins/discoverability/` · **package:** `mx.quest.discover`
|
||||
- **jar:** `runway-plugin-discoverability.jar` (thin) · **links:** the Runway SPI only (`requiresSpi: ">=1.0.0"`)
|
||||
- **Verified:** 178 unit tests + 6 host-integration tests, a live run against the packaged kernel and (2.0.0) a
|
||||
before/after comparison with 1.6.0 (see §6)
|
||||
|
||||
---
|
||||
|
||||
## 1. The boundary: what the kernel does vs. what this adds
|
||||
|
||||
The lean kernel SEO core already emits, for free, on every public page (via `SeoHeadContributor` and the
|
||||
head-injection edge):
|
||||
|
||||
- `<link rel="canonical">`, `hreflang` alternates + `x-default`, and the `robots` meta directive (from the
|
||||
effective `noindex`);
|
||||
- the **full Open Graph + Twitter card** — `og:title`/`description`/`url`/`site_name`/`type`/`locale`(+alternates)
|
||||
and the mirrored `twitter:*`, **derived from the page** so a card renders even for an unconfigured site — plus
|
||||
`og:image`/verification meta from the site's stored SEO config.
|
||||
|
||||
**This plugin never re-emits any of those.** It adds the layer the core deliberately omits:
|
||||
|
||||
| Area | Surface | Seam |
|
||||
|------|---------|------|
|
||||
| **SEO+** | schema.org **JSON-LD** — one `@graph`: `WebSite` / `WebPage`\|`Article` / `Organization` / `BreadcrumbList`, a homepage `SoftwareApplication`, and per-page **typed** nodes | `HeadContributor` |
|
||||
| **SEO+** | **`/sitemap.xml`** — published content + `hreflang` alternates | `EndpointContributor` |
|
||||
| **SEO+/GEO** | **`/robots.txt`** — `Sitemap:` line + configurable AI-crawler policy | `EndpointContributor` |
|
||||
| **GEO** | **`/llms.txt`** — compact page index for LLM / answer engines | `EndpointContributor` |
|
||||
| **GEO** | `SearchAction` + `Speakable`, folded into the SAME `@graph` nodes by `@id` | (same `HeadContributor`) |
|
||||
|
||||
> **robots.txt ownership.** The kernel serves no `/robots.txt` of its own; this plugin owns the route (an
|
||||
> `EndpointContributor` route has exactly one owner, and a kernel handler reading plugin config would hard-code a
|
||||
> plugin id into core). An install **without** this plugin therefore serves no `/robots.txt`, which crawlers
|
||||
> treat as allow-all.
|
||||
|
||||
---
|
||||
|
||||
## 2. What it links, and why (2.0.0)
|
||||
|
||||
Since 2.0.0 the plugin compiles against `runway-spi` alone and links **no kernel-internal class** (the SPI
|
||||
service tier). Everything it needs from the host arrives by ordinary Spring injection of an SPI type, which the
|
||||
kernel implements:
|
||||
|
||||
| Need | SPI |
|
||||
|------|-----|
|
||||
| this plugin's per-site settings | `PluginSettings.site(site)` — bound to this plugin by the jar its code came from; the descriptor's `default:`s applied by the host |
|
||||
| the site's published content, with its URLs | `ContentCatalogView.entries(site)` → `CatalogEntry` (metadata + one `LocalizedUrl` per available locale + the `x-default` path) |
|
||||
| a site by id, off-request | `Sites.find` |
|
||||
| "something changed, tell IndexNow" | `SiteEventListener.onCatalogChanged` — with the item's URLs **before and after** the change, and whether it happened on this node |
|
||||
| an absolute base without a configured one | `RouteRequest.origin()` — the request's origin as the kernel's trusted-proxy gate left it (until 2.0.0 the plugin built it from the raw `Host` header, with a guessed `https`) |
|
||||
| the same, for the page's JSON-LD (2.1.0) | `HeadContext.origin()` — the same trusted origin, handed to every head contributor (2.0.0's head had no origin, so a host-less site's graph was root-relative) |
|
||||
|
||||
What this buys: a kernel refactor cannot break the plugin (the kernel refuses plugins that link its
|
||||
internals); the URL scheme lives in one place, the kernel, so the sitemap, `llms.txt` and the page
|
||||
`<head>` cannot disagree; and IndexNow can report deletions (2.0.0; 1.x could not). The plugin never applies the
|
||||
URL scheme itself — it only prefixes the origin to the root-relative paths the kernel computed.
|
||||
|
||||
**2.1.0: the JSON-LD of a host-less site is absolute.** A site with neither a base URL nor a host name (the
|
||||
platform's catch-all default) gets a root-relative canonical from the kernel — the kernel prefixes only a base URL it
|
||||
knows. 2.0.0 anchored the `@graph` on that canonical, so its `@id`s were root-relative (`/#website`), and with no
|
||||
base it left out the GEO `SearchAction` and the breadcrumb trail. From SPI 1.0.0 the kernel hands every head
|
||||
contributor `HeadContext.origin()` — the site's base URL, or the request's origin as the trusted-proxy gate left it
|
||||
— and the graph is built on it: absolute `@id`s and URLs, a `SearchAction`, a breadcrumb trail, an absolute
|
||||
`org.logo`. A site with a base URL or a host name is unaffected (byte for byte). The kernel's own `<link
|
||||
rel="canonical">`, `hreflang` and Open Graph tags keep their rule (root-relative on such a site); they are not this
|
||||
plugin's. Because `origin()` needs SPI 1.0.0, the descriptor declares `requiresSpi: ">=1.0.0"`: a kernel below it
|
||||
blocks 2.1.0 at startup with a reason.
|
||||
|
||||
**Bean names carry the plugin id.** Plugins share the kernel's bean namespace, so every bean is named
|
||||
`discoverability…`. Two were renamed: the console model is `discoverabilityAdminModel` (was `discoverAdminModel`;
|
||||
the dashboard card and admin fragment follow), and the app-level settings are a named `@Bean`
|
||||
`discoverabilityProperties` with `@ConfigurationProperties` on the method — `@EnableConfigurationProperties` would
|
||||
have registered them under a generated name outside the prefix.
|
||||
|
||||
**Personal data:** none. The plugin stores nothing under `sites/<id>/plugins/discoverability/`; its settings file
|
||||
(`plugins/discoverability.yml`) is configuration, so the descriptor declares no `siteData.personal`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Why one plugin (SEO+ and GEO together)
|
||||
|
||||
The two areas share one spine: **schema.org JSON-LD**, which serves *both* rich search results (SEO) and AI
|
||||
answer extraction (GEO). As of 1.2.0 there is **literally one `HeadContributor`** (`StructuredDataHead`)
|
||||
emitting **one `@graph`** — the GEO `SearchAction` and `Speakable` are folded onto the same `WebSite`/`WebPage`
|
||||
nodes (rather than a second `<script>` block that repeats the `@id`s), so every `@id` is defined exactly once
|
||||
and a consumer that parses each `<script>` independently still sees complete entities. GEO stays gated by a
|
||||
single `geo.enabled` toggle. One plugin ⇒ one config surface, one permission, one JSON-LD engine.
|
||||
|
||||
---
|
||||
|
||||
## 4. Feature → seam coverage
|
||||
|
||||
| Seam | Class | What it does |
|
||||
|------|-------|--------------|
|
||||
| `mainClass` `@Configuration` + explicit `@Bean` wiring | `DiscoverabilityConfig` | registers all beans + the `SchemaType` registry |
|
||||
| **HeadContributor** (`@Order 150`) | `StructuredDataHead` | the one JSON-LD `@graph` (SEO nodes + GEO signals + SoftwareApplication + typed nodes); skips preview/`noindex`/disabled |
|
||||
| **EndpointContributor** `/sitemap.xml` | `SitemapEndpoint` | urlset over `ContentCatalogView` entries (the kernel's URLs); `sitemap.enabled`-gated |
|
||||
| **EndpointContributor** `/robots.txt` | `RobotsTxtEndpoint` | an **explicit** named AI/LLM-crawler group (always emitted — the posture is stated, not implied) + a general allow group + `Sitemap:` line |
|
||||
| **EndpointContributor** `/llms.txt` | `LlmsTxtEndpoint` | Markdown page index over `ContentCatalogView`; `geo.enabled`-gated |
|
||||
| **EndpointContributor** `/indexnow-key.txt` | `IndexNowKeyEndpoint` | the site's IndexNow key; 404 unless both switches are on and a key is set |
|
||||
| **SiteEventListener** (`CONSUMER`) + `@Scheduled` flush | `IndexNowSubmitter` | queues each local change's previous ∪ current URLs; one batched POST per site per period |
|
||||
| **Content-type registry** (`SchemaType`) | `FaqPageSchema`, `ProductSchema`, `ArticleSchema`, `LocalBusinessSchema`, `ServiceSchema`, `PersonSchema`, `CollectionSchema` | one impl per type, dispatched by declared type token — the host stays type-blind |
|
||||
| **Advisory** (`PageQualityCheck`) | `FaqAdvisoryCheck` | edit-time: detects an on-page `<details>` FAQ not in `content.schema` and advises adding it (localized by finding code) |
|
||||
| Per-page typing | `PageSchemaConfig` + `SchemaContext` + `Schemas` | parse `content.schema`, resolve by path (exact > longest `*`-prefix) |
|
||||
| JSON-LD core (shared) | `Ld` | node/`@id`/graph builder; HTML-safe `<script>` serialization |
|
||||
| App-level settings | `DiscoverabilityProperties` (`@ConfigurationProperties` on the `discoverabilityProperties` bean) | `robots.ai-*`, the IndexNow egress switch and limits |
|
||||
| Per-tenant config | `SiteConfig` over `PluginSettings.site(...).values()` | live typed reads, 1.x's lenient rules |
|
||||
| Dashboard card + admin fragment | `DiscoverAdminModel` (bean `discoverabilityAdminModel`) + `templates/` | live status |
|
||||
| Control-point permission (`settings`) | `plugin.yml` | `discoverability\|settings` ("Manage discoverability (SEO & GEO)"): gates the per-tenant config editor and the dashboard card; `defaultRoles: []`, so only the site's superadmin and administrators hold it until it is granted on the site's Permissions screen |
|
||||
| i18n (EN/ES), static help page | `i18n/`, `static/` | console + public-facing strings |
|
||||
|
||||
---
|
||||
|
||||
## 5. Settings
|
||||
|
||||
### App-level (platform; `external/plugin-settings/discoverability.yml`; restart to apply)
|
||||
|
||||
| Key | Type | Default | Meaning |
|
||||
|-----|------|---------|---------|
|
||||
| `robots.ai-default` | enum | `allow` | the default AI/LLM-crawler policy a site inherits (`robots.ai-policy: inherit`) — `allow` (GEO-friendly) or `disallow` |
|
||||
| `robots.ai-agents-extra` | list | *(empty)* | extra AI/LLM crawler user-agent names **appended** to the built-in list. The built-in list is a compile-time constant that **goes stale silently** — an agent it does not name is simply not covered by a site's opt-out, and nothing reports the gap. This closes a newly announced agent without waiting for a plugin release. Additive only; a retired name costs one inert `User-agent:` line. Prefix a name with `training=`, `retrieval=` or `user=` to put it in that class (it then follows the site's per-class override); without a prefix it follows the site's overall `robots.ai-policy`. A misspelt class is logged and the name is kept, unclassified. One name per line or comma-separated entry; whitespace, `:` and `=` are stripped from the name, and a name already in the list (built-in included, any case) is ignored, so a built-in agent cannot be reclassified. The 22 built-in agents and their classes are listed in the help page (`#ai-agents`) |
|
||||
| `indexnow.enabled` | boolean | `false` | the operator's egress decision: lets sites turn IndexNow on (this server then makes outbound requests). Off, a site enabling it gets a WARN and its form says the platform has it off |
|
||||
| `indexnow.endpoint` / `.batch-seconds` / `.max-urls-per-submission` / `.max-queued-per-site` / `.timeout-seconds` | string / int ×4 | `https://api.indexnow.org/indexnow` / `60` / `1000` / `5000` / `10` | where and how submissions go. Ranges `5..3600` / `1..10000` / `1..100000` / `1..120`: the console form refuses a value outside them; a value set by hand (this file, `application.yml`, the environment) is not range-checked — the three limits count anything below 1 as 1, and `batch-seconds` is held to `5..3600` (2.2.0; before, it went to the scheduler as written, so `0` or a negative value made the start fail). What each does: help page `#indexnow-limits` |
|
||||
|
||||
### Per-tenant (live, no restart). **SEO+ on by default; GEO opt-in.**
|
||||
|
||||
| Key | Type | Default | Meaning |
|
||||
|-----|------|---------|---------|
|
||||
| `jsonld.enabled` | boolean | `true` | emit structured data |
|
||||
| `jsonld.type` | enum | `WebPage` | the page `@type` of every page whose `content.schema` entry declares no page type (`WebPage` or `Article`); a page type there (`Article`, `FAQPage`, `ContactPage`, …) replaces it on the pages it matches (2.2.0). As the default, `Article` carries the title as `headline` but no author, dates or image (those need an `Article`, `BlogPosting` or `NewsArticle` block in `content.schema`, which then sets the page's type). Case-sensitive: in a hand-edited file anything but exactly `Article` means `WebPage` |
|
||||
| `jsonld.breadcrumbs` | boolean | `true` | include a `BreadcrumbList` on every page but `/` and a page whose canonical points to another site (a non-default-language home such as `/es` gets one): `Home` (a fixed English label, linking to the site root) → the `content.schema` `breadcrumb` parent, if any → the page (its title, else its path) |
|
||||
| `content.schema` | text | — | **per-page typing** — YAML `path-pattern → { type, fields }` (see below) |
|
||||
| `org.name` / `org.logo` / `org.sameas` | string / string / list | — | Organization identity; a root-relative `org.logo` resolves to absolute against the base |
|
||||
| `software.*` | (group) | off | homepage-only `SoftwareApplication` (also on each non-default-language home, `/es`) — `software.enabled`, `.name`, `.description`, `.category`, `.os` (default `Web`), `.price`, `.currency` (default `USD`), `.license`, `.url`, `.screenshot`. Free text, not validated; a blank `.os`/`.currency` means its default. `.license`, `.url` and `.screenshot` are emitted as written — unlike `org.logo`, a root-relative value stays relative, so they need full URLs |
|
||||
| `sitemap.enabled` | boolean | `true` | serve `/sitemap.xml` (also gates the robots `Sitemap:` line) |
|
||||
| `robots.ai-policy` | enum | `inherit` | this site's AI-crawler policy — `inherit` (app default) / `allow` / `disallow` |
|
||||
| `robots.ai-training` / `robots.ai-retrieval` / `robots.ai-user` | enum | `inherit` | per-class overrides of the policy above (`inherit` = whatever `robots.ai-policy` says). The classes have opposite consequences: refusing training costs nothing visible, refusing retrieval removes the site from AI answers, refusing user fetches breaks a visit a person asked for |
|
||||
| `robots.extra-disallow` | list | — | extra `Disallow:` paths in the general group (and in every allowed AI group); a missing leading `/` is added, CR/LF stripped, otherwise as written — each is a robots.txt path prefix |
|
||||
| `robots.custom` | text | — | full-body override — replaces the generated `robots.txt` verbatim |
|
||||
| `geo.enabled` | boolean | `false` | **GEO master switch** (SearchAction, Speakable, `/llms.txt`) |
|
||||
| `geo.summary` | text | — | the one-line summary atop `llms.txt` |
|
||||
| `geo.speakable` | list | `h1,main` | Speakable CSS selectors (add `article` etc. if your master has them); comma- or line-separated; blank means `h1,main`. Needs `jsonld.enabled` too |
|
||||
| `search.url` | string | — | site-search URL → a machine-readable `SearchAction` (GEO and structured data both on). A path or full URL (a value starting `http` is used as is); `{query}` or `{search_term_string}` marks where the words go, else `?q=` is appended (`&q=` when the URL already has a `?`) |
|
||||
| `indexnow.enabled` | boolean | `false` | notify Bing, Yandex, Seznam, Naver and Yep (**not Google**) of changed URLs — inert unless the app-level switch is also on, and silently inert (no warning) for a site with neither a base URL nor a host name |
|
||||
| `indexnow.key` | string | — | 8–128 letters, digits or dashes (the protocol's rule, not enforced here); served at `/indexnow-key.txt`. Nothing is sent without one |
|
||||
|
||||
**How the form is laid out (1.6.0).** The per-site form is in six sections — structured data, sitemap &
|
||||
robots.txt, AI crawlers, GEO, product on the homepage, IndexNow — each field with a help line (EN + ES) and
|
||||
the longer explanations on the help page (`static/discoverability-help.html`, one anchored section per form
|
||||
section). `content.schema`, `robots.custom` and the three per-class AI overrides sit under *Advanced*;
|
||||
fields that do nothing while their switch is off (`jsonld.enabled`, `geo.enabled`, `software.enabled`,
|
||||
`indexnow.enabled`) are hidden until it is on. 2.0.0 keeps the layout unchanged (the before/after comparison in §6 diffs the rendered
|
||||
form). `SettingsDescriptorTest` (plain YAML, default build) fails the build on a dangling group, switch,
|
||||
inheritance source, help anchor or message key; `HostDescriptorTest` (the `host-it` profile) also parses the
|
||||
descriptor with the kernel's own parser. `search.url` stays under GEO rather than structured data because the
|
||||
code only emits the `SearchAction` while GEO is on.
|
||||
|
||||
**`content.schema` format** — a small YAML document keyed by URL-path pattern; an exact path wins over a
|
||||
trailing-`*` prefix, and among prefixes the longest wins. The complete reference — every type and every key it
|
||||
reads, how a page is matched (its own canonical path only: `/faq` does not match `/es/faq`, because an entry's text
|
||||
is in one language; the translated page needs its own key, and the page editor says so when the default language's
|
||||
entry does not reach it), and which types are **page types** (they replace `jsonld.type` on the page:
|
||||
`Article`/`BlogPosting`/`NewsArticle`, `FAQPage`, `CollectionPage`, `WebPage`, `AboutPage`, `ContactPage`,
|
||||
`ItemPage`, `SearchResultsPage`) versus types that add an entity (`Product`, `Service`/`ProfessionalService`,
|
||||
`LocalBusiness`/`CafeOrCoffeeShop`, `Person`, `ItemList`) — is in the operator help page
|
||||
`static/discoverability-help.html#content-schema`, which the settings form links to. `PageTypes` computes the
|
||||
answer once for the `<head>`, for the page editor's line (`PageTypeCheck`) and for the FAQ advice
|
||||
(`FaqAdvisoryCheck`); the admin fragment lists every mistake (`DiscoverAdminModel.schemaProblems`), including a
|
||||
block that applies but publishes nothing of its own (`SchemaType.gap`: an `FAQPage` with no complete question, a
|
||||
list with no item `url`). There is no `QAPage` or `ProfilePage`: Google requires a `mainEntity` on both, which a
|
||||
type with no keys cannot give.
|
||||
|
||||
```yaml
|
||||
# A pricing page that carries TWO types at once — the entry is a LIST of type-blocks:
|
||||
/pricing:
|
||||
- type: FAQPage
|
||||
faq:
|
||||
- { q: "Why ranges?", a: "Scope drives cost…" }
|
||||
- type: Service
|
||||
name: "Advisory Sprint"
|
||||
offers:
|
||||
- { name: "Sprint", price: "18000", currency: USD }
|
||||
# A collection/index page: the page is a CollectionPage whose main entity is the list:
|
||||
/coffees:
|
||||
type: CollectionPage
|
||||
items:
|
||||
- { name: "Ethiopia Guji", url: "/coffee-ethiopia-guji" }
|
||||
- { name: "Colombia Huila", url: "/coffee-colombia-huila" }
|
||||
# A product detail page — `breadcrumb:` inserts its parent collection as a middle level (Home → Coffees → …):
|
||||
/coffee-ethiopia-guji:
|
||||
type: Product
|
||||
price: "22.00"
|
||||
currency: USD
|
||||
image: ["/static/img/guji.jpg"]
|
||||
breadcrumb: { name: "Coffees", url: "/coffees" }
|
||||
/cafes:
|
||||
type: CafeOrCoffeeShop
|
||||
locations:
|
||||
- { name: "Roastery", street: "14 Lamplight Lane", locality: Portland, region: OR }
|
||||
/team:
|
||||
type: Person
|
||||
people: [{ name: "Dana Whitlock" }]
|
||||
```
|
||||
|
||||
Supported `type`s (case-sensitive; any other token is skipped and reported): the page types `Article`/`BlogPosting`/
|
||||
`NewsArticle`, `FAQPage`, `CollectionPage`, `WebPage`, `AboutPage`, `ContactPage`, `ItemPage`,
|
||||
`SearchResultsPage`, and the added entities `Product`, `Service`/`ProfessionalService`,
|
||||
`LocalBusiness`/`CafeOrCoffeeShop`, `Person`, `ItemList`. An entry is **one type-block** (a map) or
|
||||
a **list of type-blocks** when one page carries several types. Any detail entry may add `breadcrumb: {name, url}`
|
||||
to place its parent collection between Home and the page. Values are **tenant-owned**; the plugin owns the typing
|
||||
mechanism. Each typed node references the page's `WebPage`/`Organization` by `@id`, so it joins the one `@graph`;
|
||||
the `WebPage` in turn links its `BreadcrumbList` by `@id` (`breadcrumb`).
|
||||
|
||||
> **Defaults: the descriptor's, applied by the kernel — and the code's, which must match.** Since 2.0.0 the
|
||||
> settings come from `PluginSettings`, which overlays the stored values on the descriptor's declared `default:`s
|
||||
> (1.x read only the stored values and applied its code fallbacks). Every code fallback (`SiteConfig.bool(cfg,
|
||||
> key, default)`) equals its declared default, so nothing a tenant sees changed: `DescriptorDefaultsTest`
|
||||
> renders every surface with and without the declared defaults and requires identical bytes, and
|
||||
> `HostDescriptorTest` checks the unit tests' settings fake against the kernel's own merge.
|
||||
|
||||
---
|
||||
|
||||
## 6. Verification
|
||||
|
||||
**Unit (178 tests, `mvn verify`; SPI-only, on `runway-spi-testkit`'s fakes):** `LdTest`; `StructuredDataHeadTest`
|
||||
(WebSite/WebPage/Organization/Article/Breadcrumb; the GEO fold — one block, `@id`s once; SoftwareApplication
|
||||
homepage-only; the typed nodes; several type-blocks on one path; breadcrumb links; relative-logo resolution; the
|
||||
skip cases; 2.1.0: a host-less graph absolute at `origin()` with its SearchAction and trail, the base URL winning over
|
||||
the origin byte for byte, no origin rendering as 2.0.0 did); `RobotsTxtEndpointTest` (the explicit AI-crawler group on both postures, mirroring, extra-disallow,
|
||||
custom override, the Sitemap line from the base or the trusted origin); `SitemapEndpointTest` (the exact
|
||||
document, noindex and canonical rules incl. root-relative canonicals, the index/shards, conditional GET, the
|
||||
origin fallback); `LlmsTxtEndpointTest` (the exact document, the link fix for an item missing from the default locale, labels; 2.1.0: the summary, the site
|
||||
name and the base URL advance `Last-Modified`, the request origin and the summary do not move the sitemap's); `IndexNowSubmitterTest`
|
||||
(payload, both switches, bounds, and the SPI change events: deletions submit their old URLs, renames the union,
|
||||
peers' replays nothing); `CrawlConditionalTest` (2.1.0: document facts, length-prefixed, one validator per
|
||||
document); `FaqAdvisoryCheckTest`; `SettingsDescriptorTest`;
|
||||
`DescriptorDefaultsTest`; `DiscoverabilityConfigTest` (wiring over SPI services only, bean names, template bean
|
||||
references, the app-settings binding, descriptor floor/version, and a bytecode scan proving no class links
|
||||
`mx.quest.runway.*` outside `.spi`).
|
||||
|
||||
**Host integration (6 tests, `mvn -P host-it verify`):** the only build that sees `runway-app` (test scope).
|
||||
`HostDescriptorTest` (the kernel parses the descriptor; the kernel's settings merge equals the unit tests' fake);
|
||||
`HostCatalogParityTest` (over the real kernel catalog: the sitemap equals what 1.6.0's algorithm built from the
|
||||
same catalog with the kernel's URL builders, llms.txt differs only by the default-locale link fix, head and sitemap alternates
|
||||
agree, and the test fixture's URL mirror equals the kernel's entries).
|
||||
|
||||
**Live** (`scripts/verify-against-host.sh` against the packaged kernel; honours `HOST_JAR`, `VERIFY_TMPDIR`,
|
||||
`VERIFY_LOG_DIR`): 49 checks — loaded with zero host-linkage and bean-name/surface findings, IndexNow collected as an SPI listener; JSON-LD (2.1.0: absolute, with its
|
||||
SearchAction and a trail), sitemap with hreflang for a bilingual site, robots.txt and llms.txt at the trusted origin
|
||||
of a host-less site; llms.txt's `Last-Modified` advancing on a summary-only save through the console; the 1.6.0 settings layout, the admin fragment and dashboard card through the renamed
|
||||
bean; IndexNow inert by default (one WARN, key 404, nothing sent); IndexNow on (a fake endpoint): an
|
||||
**unpublished** page's old URLs are submitted, a republish once per batch.
|
||||
|
||||
**Before/after** (`scripts/compare-with-previous.sh`, `PREVIOUS_DIR=<1.6.0 install folder>`): one deployment, the
|
||||
same files, 1.6.0 then 2.0.0; a bilingual fixture (FAQ-typed About, a Spanish-only page, noindex, canonicalised,
|
||||
root-relative self canonical, draft; GEO, Organization, SoftwareApplication), each surface fetched with a
|
||||
configured base URL, a host-derived one and none. Identical — sitemap, robots.txt, llms.txt, JSON-LD of four
|
||||
pages, status codes, the settings form, the admin and dashboard values — except the three documented fixes
|
||||
(CHANGELOG 2.0.0).
|
||||
|
||||
---
|
||||
|
||||
## 7. Honest gaps & deliberate non-uses
|
||||
|
||||
- **No `<lastmod>` for an item without `updatedAt`** — pages always carry one; a content source may not.
|
||||
- **Closed in 2.1.0** (all three were listed here at 2.0.0): a host-less site's structured data is absolute
|
||||
(`HeadContext.origin()`, above); an item whose primary locale the site does not serve is linked at its first
|
||||
available locale's real address (the SPI 1.0.0 kernel's `CatalogEntry.pathFor`, which 2.1.0 requires); and
|
||||
`llms.txt`'s validator folds the site name, `geo.summary`, the default locale and the base URL, so editing any of
|
||||
them advances `Last-Modified`.
|
||||
- **The sitemap's validator does not fold the base URL.** Changing a site's base URL rewrites every `<loc>` but not
|
||||
the sitemap's `Last-Modified` until content changes (llms.txt folds it since 2.1.0). Rare (a domain move) and
|
||||
self-correcting at the next content change; a follow-up.
|
||||
- **Typing is a path map, not a per-page field** — `content.schema` keys by URL path; the cleaner long-term
|
||||
seam (a `schema-type` on the page's own metadata) needs a small additive kernel change.
|
||||
- **Per-instance / per-page config** beyond `content.schema` is not offered — configuration is per-site.
|
||||
|
||||
---
|
||||
|
||||
**Added after an SEO and GEO audit of the plugin (2026-08-19):**
|
||||
|
||||
- ~~**The AI-crawler classes are not separately controllable.**~~ **Fixed in 1.5.0.** Each agent now carries an
|
||||
`AiClass` — `TRAINING`, `RETRIEVAL`, `USER` — and a site can override the policy per class with
|
||||
`robots.ai-training` / `robots.ai-retrieval` / `robots.ai-user` (each `inherit|allow|disallow`, `inherit`
|
||||
meaning "whatever `robots.ai-policy` says"). So a publisher can decline to be *training* material while
|
||||
staying eligible for *citation*, which was the whole point.
|
||||
|
||||
**What is still a judgement call:** the classification itself. The operators' own triads are not in doubt
|
||||
(OpenAI's `GPTBot`/`OAI-SearchBot`/`ChatGPT-User`, Anthropic's `ClaudeBot`/`Claude-SearchBot`/`Claude-User`,
|
||||
Perplexity's pair), nor are the training-only opt-out agents that exist precisely to be separable from their
|
||||
search siblings (`Google-Extended`, `Applebot-Extended`). The rest is a best-effort reading of each
|
||||
operator's own description, and an agent whose role is genuinely ambiguous is classified `TRAINING` —
|
||||
the class a site opting out is most likely to mean, so a misplacement fails toward honouring the site's
|
||||
stated intent rather than around it.
|
||||
|
||||
A site that sets no per-class override gets a **byte-identical** `robots.txt` to before, single group and
|
||||
all: splitting a site that expressed no such preference into three identical groups would churn every
|
||||
crawler's copy to say the same thing.
|
||||
|
||||
An operator-added agent (`robots.ai-agents-extra`) may declare its class as `training=SomeNewBot`; without a
|
||||
prefix it follows the site's overall policy, exactly as it did before. A misspelt class is **logged** and the
|
||||
agent is still listed — folding the bad prefix into the name would emit a token matching nothing, and the
|
||||
operator would believe they had covered an agent they had not.
|
||||
- **IndexNow — built in 1.5.0, off at both ends, and honest about what it buys.** Participating engines
|
||||
(Bing, Yandex, Seznam, Naver, Yep) are told when a site's content changes, instead of waiting to be
|
||||
re-crawled. **Google does not participate**, so this changes nothing about Google's view of a site — worth
|
||||
saying plainly, because the opposite is widely implied and a tenant turning it on should know what they are
|
||||
buying. It is a *freshness* signal, never a ranking one.
|
||||
|
||||
**Two switches, both off.** This is the first thing in the plugin that makes an **outbound** request on a
|
||||
tenant's behalf, so it needs the platform operator's permission (they own the network, the egress firewall
|
||||
and the incident) *and* the tenant's (they own the URLs being disclosed). An upgrade must never start making
|
||||
network calls a deployment was not making before. A tenant who enables it while the platform has not gets a
|
||||
WARN naming both the site and the setting to flip — a feature that is silently inert is worse than one that
|
||||
is off, because from inside nobody can tell the difference.
|
||||
|
||||
**The key file lives at a fixed `/indexnow-key.txt`, not `/<key>.txt`.** The usual pattern names the file
|
||||
after the key, which cannot work here: the host matches routes by exact path and builds its table at
|
||||
startup, while the key is per-site configuration that changes at runtime. The spec's own `keyLocation` field
|
||||
exists for exactly this, so every submission points at the stable path. It is served `no-store` and outside
|
||||
the sitemap — a cached copy would keep answering with an old key after a rotation, failing verification in a
|
||||
way that looks like the engine's fault.
|
||||
|
||||
**Deletions and moves reach the engines (2.0.0).** The submitter is an SPI `SiteEventListener`; each change
|
||||
carries the item's URLs before and after it, and the union is queued — so an unpublished or deleted page's old
|
||||
address is submitted, which 1.x could not do (it looked the URLs up after the kernel had dropped the item).
|
||||
Only the node where the change happened submits; a cluster's replays on its other nodes are ignored.
|
||||
|
||||
**The flush runs on the kernel's scheduler.** It is a Spring `@Scheduled` method, and the kernel enables
|
||||
scheduling unconditionally. The plugin does not start a scheduler of its own.
|
||||
|
||||
**Batched, bounded, and never on a request thread.** A page save touching five localized URLs must not
|
||||
become five outbound requests; a bulk edit or a restore must not become thousands. Queued URLs per site and
|
||||
URLs per submission are both capped, and overflow is dropped with a WARN naming the tenant. A failed
|
||||
submission is logged and dropped rather than retried: a stale freshness ping is worthless, an unbounded
|
||||
retry queue during an outage is a liability, and the pages are still crawled the ordinary way.
|
||||
|
||||
- **`llms.txt` is not known to do anything, and the docs now say so.** It is a community proposal, not a
|
||||
standard; no major engine documents consuming it; and Google states plainly that no AI-specific file or markup
|
||||
is needed to appear in its AI features. It is emitted because it is cheap and harmless, **not** because
|
||||
visibility depends on it. Any claim to the contrary in marketing copy is unsupported.
|
||||
- ~~**No sitemap index.**~~ **Fixed in 1.5.0.** `/sitemap.xml` stays a single plain `<urlset>` while the site
|
||||
fits in one shard (10,000 URLs — which is every realistic tenant, and splitting a 40-URL site across an index
|
||||
would cost a crawler two fetches to learn nothing). Past that it becomes a `<sitemapindex>` naming
|
||||
`/sitemap-1.xml` … `/sitemap-N.xml`, each shard a conformant `<urlset>`.
|
||||
|
||||
**Why shards of 10,000 rather than the spec's 50,000:** the spec cap is not the binding constraint. This is a
|
||||
public, anonymous route, and a 50,000-URL document with `hreflang` alternates is tens of megabytes assembled
|
||||
in the heap, per concurrent request. A smaller shard stays comfortably inside both the spec and a sane memory
|
||||
envelope, and costs a crawler only round trips it makes anyway.
|
||||
|
||||
**The ceiling is real and visible:** 20 shards, so 200,000 URLs — four times the single-file limit it
|
||||
replaces. The host matches routes by exact path (no patterns, deliberately — a pattern on a public tenant
|
||||
route is a path-safety surface nobody needs), so each shard is a declared route. Past the ceiling it still
|
||||
WARNs loudly naming the tenant, rather than truncating in silence.
|
||||
|
||||
**Shard membership is derived from the sorted URL list, not from source-registration order.** The kernel's
|
||||
listing is grouped by source in an order it does not promise, which says nothing across restarts or across the nodes of a cluster —
|
||||
and if boundaries followed it, two nodes behind one load balancer would serve *different content for the
|
||||
same shard number*, so a crawler alternating between them would watch URLs appear and vanish with nothing in
|
||||
the response to explain it.
|
||||
|
||||
|
||||
## 8. Handover
|
||||
|
||||
Self-contained: the shared authoring guide ([`../../docs/PLUGIN-AUTHORING-GUIDE.md`](../../docs/PLUGIN-AUTHORING-GUIDE.md);
|
||||
the kernel's [`docs/PLUGIN-DEVELOPMENT.md`](../../../docs/PLUGIN-DEVELOPMENT.md) is the reference for the SPI
|
||||
services), a one-command verifier (`scripts/verify-against-host.sh`) and the before/after comparison
|
||||
(`scripts/compare-with-previous.sh`). A build needs `runway-spi` and `runway-spi-testkit` in `~/.m2`
|
||||
(`runway-app` too for the `host-it` profile), installed from the kernel at the root of this repository.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Writing a Runway plugin — moved
|
||||
|
||||
The authoring guide is maintained in **one place**: [`../../docs/PLUGIN-AUTHORING-GUIDE.md`](../../docs/PLUGIN-AUTHORING-GUIDE.md)
|
||||
at `plugins/docs/`.
|
||||
|
||||
This file used to hold a copy of it. The copy had drifted (it predated the SPI service tier and still told a plugin
|
||||
to inject kernel classes such as `SitePluginConfigService`, `ContentCatalog` or `SiteStore`), and a stale copy is
|
||||
worse than none. For how this plugin uses the SPI services instead, read
|
||||
[`DISCOVERABILITY-PLUGIN.md`](DISCOVERABILITY-PLUGIN.md) §2.
|
||||
@@ -0,0 +1,142 @@
|
||||
# Discoverability plugin — English. Appended add-only to the console + per-site MessageSource; keys are the
|
||||
# plugin's own (discover.*) and never override core.
|
||||
|
||||
# Control-point permission (permissions matrix + gates)
|
||||
discover.perm.settings=Manage discoverability (SEO & GEO)
|
||||
|
||||
# Settings form: sections (heading + one-line introduction)
|
||||
discover.grp.structured=Structured data for search engines
|
||||
discover.grp.structured.help=Tells search engines what each page is and who publishes the site. On by default; most sites only need to fill in the organization.
|
||||
discover.grp.sitemap=Sitemap and robots.txt
|
||||
discover.grp.sitemap.help=The list of pages offered to crawlers, and the rules for what they may fetch.
|
||||
discover.grp.ai=AI crawlers
|
||||
discover.grp.ai.help=Whether AI companies' crawlers may read the site. Ordinary search engines are not affected.
|
||||
discover.grp.geo=AI answer engines (GEO)
|
||||
discover.grp.geo.help=Optional extras that help AI assistants understand and quote this site. Off by default.
|
||||
discover.grp.software=Product on the homepage
|
||||
discover.grp.software.help=For sites that present a software product or app. Off by default.
|
||||
discover.grp.indexnow=Notify search engines of changes (IndexNow)
|
||||
discover.grp.indexnow.help=Tells Bing, Yandex, Seznam, Naver and Yep when pages change. Google does not use IndexNow.
|
||||
|
||||
# Settings form: labels (short; the explanation is the help line under each field)
|
||||
discover.set.jsonldEnabled=Structured data (JSON-LD)
|
||||
discover.set.jsonldType=Default page type
|
||||
discover.set.breadcrumbs=Breadcrumb trail
|
||||
discover.set.contentSchema=Per-page types (content.schema)
|
||||
discover.set.orgName=Organization name
|
||||
discover.set.orgLogo=Organization logo
|
||||
discover.set.orgSameAs=Official profiles
|
||||
discover.set.softwareEnabled=Describe a product on the homepage
|
||||
discover.set.softwareName=Product name
|
||||
discover.set.softwareDescription=Description
|
||||
discover.set.softwareCategory=Category
|
||||
discover.set.softwareOs=Operating systems
|
||||
discover.set.softwarePrice=Price
|
||||
discover.set.softwareCurrency=Currency
|
||||
discover.set.softwareLicense=License URL
|
||||
discover.set.softwareUrl=Product URL
|
||||
discover.set.softwareScreenshot=Screenshot URL
|
||||
discover.set.sitemapEnabled=Sitemap (/sitemap.xml)
|
||||
discover.set.robotsAiDefault=Default AI-crawler policy
|
||||
discover.set.robotsAiAgentsExtra=Additional AI crawler names
|
||||
discover.set.robotsAiPolicy=AI crawlers on this site
|
||||
discover.set.robotsAiTraining=AI training crawlers
|
||||
discover.set.robotsAiRetrieval=AI answer-engine crawlers
|
||||
discover.set.robotsAiUser=AI fetches a person asked for
|
||||
discover.set.robotsExtraDisallow=Paths crawlers should skip
|
||||
discover.set.robotsCustom=Custom robots.txt
|
||||
discover.set.geoEnabled=AI answer-engine optimization (GEO)
|
||||
discover.set.geoSummary=Site summary
|
||||
discover.set.geoSpeakable=Speakable parts of a page
|
||||
discover.set.searchUrl=Site search URL
|
||||
discover.set.indexnowEnabled=Notify search engines of changes
|
||||
discover.set.indexnowKey=IndexNow key
|
||||
discover.set.indexnowAppEnabled=Allow sites to use IndexNow
|
||||
discover.set.indexnowEndpoint=Submission endpoint
|
||||
discover.set.indexnowBatch=Seconds to gather changes
|
||||
discover.set.indexnowMaxUrls=Maximum URLs per submission
|
||||
discover.set.indexnowMaxQueued=Maximum URLs queued per site
|
||||
discover.set.indexnowTimeout=Submission timeout (seconds)
|
||||
|
||||
# Settings form: help lines (one short line, always visible under the field)
|
||||
discover.help.jsonldEnabled=Adds schema.org structured data to every page so search engines understand what it is. Leave it on: everything else in this section needs it.
|
||||
discover.help.jsonldType=Article for blogs and news sites, WebPage for everything else. Every page is described as this type unless Advanced → Per-page types gives it its own: a page type there (Article, AboutPage, ContactPage, FAQPage, CollectionPage, …) replaces this one on the pages it matches, and any other type (a product, a service, a local business) is added to the page. The page editor shows each page's type and where it comes from.
|
||||
discover.help.breadcrumbs=Adds a Home \u203a Page trail to search results. A middle level appears where content.schema declares one (breadcrumb: {name, url}).
|
||||
discover.help.orgName=Who publishes this site. Leave blank to publish no organization.
|
||||
discover.help.orgLogo=A square image: a full URL, or a path on this site such as /img/logo.png.
|
||||
discover.help.orgSameAs=Your official profiles (LinkedIn, GitHub, …). Links this site to them.
|
||||
discover.help.contentSchema=Declares page types (FAQ, product, service, local business…) per URL path, in YAML. See the examples in the help.
|
||||
discover.help.sitemapEnabled=Serves /sitemap.xml and announces it in robots.txt. Leave it on.
|
||||
discover.help.robotsExtraDisallow=Paths every crawler should skip, for example /drafts/.
|
||||
discover.help.robotsCustom=Replaces the ENTIRE generated robots.txt, including the sitemap line and the AI rules. Use it only if you know you need it.
|
||||
discover.help.robotsAiPolicy=Allow or refuse AI crawlers. inherit follows the platform's default.
|
||||
discover.help.robotsAiTraining=Crawlers that collect text to train AI models. Refusing them costs this site nothing visible.
|
||||
discover.help.robotsAiRetrieval=Crawlers behind AI answers (ChatGPT search, Perplexity…). Refusing them removes this site from those answers.
|
||||
discover.help.robotsAiUser=A visit a person asked an AI assistant to make. Refusing it breaks that visit.
|
||||
discover.help.robotsAiDefault=What a site set to inherit gets. allow keeps sites visible to AI answer engines.
|
||||
discover.help.robotsAiAgentsExtra=AI crawler names the plugin does not know yet, one per line. Write training=Name, retrieval=Name or user=Name to put one in a class; without it, a name follows each site's overall AI policy.
|
||||
discover.help.geoEnabled=Publishes /llms.txt and marks up pages for AI assistants. The search URL and speakable parts also need structured data on.
|
||||
discover.help.geoSummary=A plain-language paragraph about the site, placed at the top of /llms.txt.
|
||||
discover.help.geoSpeakable=CSS selectors for the parts of a page worth reading aloud or quoting. The default suits most sites.
|
||||
discover.help.searchUrl=Your search-results page, e.g. /search?q={query}. Without {query}, ?q= is added. Published as a schema.org SearchAction; Google no longer shows a search box from it.
|
||||
discover.help.softwareEnabled=Describes your product as a SoftwareApplication, on the homepage only. Needs structured data on.
|
||||
discover.help.softwareName=Blank uses the organization name, or else the site name.
|
||||
discover.help.softwareDescription=Blank uses the homepage's description.
|
||||
discover.help.softwareCategory=A schema.org category, e.g. WebApplication, BusinessApplication, DeveloperApplication.
|
||||
discover.help.softwareOs=Where it runs, e.g. Web, or Windows, macOS, Linux.
|
||||
discover.help.softwarePrice=A number; 0 means free. Blank publishes no price.
|
||||
discover.help.softwareCurrency=A three-letter currency code, e.g. USD, MXN, EUR.
|
||||
discover.help.softwareLicense=A link to the product's license.
|
||||
discover.help.softwareUrl=Blank uses the homepage.
|
||||
discover.help.softwareScreenshot=A full URL to an image of the product.
|
||||
discover.help.indexnowEnabled=Sends changed page addresses to the engines that use IndexNow. Google does not.
|
||||
discover.help.indexnowKey=A random string of 8 to 128 letters, digits or dashes (IndexNow's rule). Published at /indexnow-key.txt to prove the site is yours.
|
||||
discover.help.indexnowAppEnabled=Lets each site turn IndexNow on for itself. When on, this server makes outbound requests to the IndexNow endpoint.
|
||||
discover.help.indexnowEndpoint=Where submissions go. The shared endpoint forwards to every participating engine.
|
||||
discover.help.indexnowBatch=Changes are gathered for this long and sent together.
|
||||
discover.help.indexnowMaxUrls=URLs beyond this in one submission are not sent (a warning is logged); those pages are still crawled the ordinary way.
|
||||
discover.help.indexnowMaxQueued=Once a site has this many changes waiting, further ones are not queued until the next submission (a warning is logged).
|
||||
discover.help.indexnowTimeout=How long to wait for the endpoint before giving up on a submission.
|
||||
|
||||
# Dashboard card
|
||||
discover.card.title=Discoverability
|
||||
discover.card.pages=Pages
|
||||
|
||||
# Admin status fragment
|
||||
discover.admin.title=Discoverability status
|
||||
discover.admin.jsonld=Structured data
|
||||
discover.admin.sitemap=Sitemap
|
||||
discover.admin.geo=GEO · llms.txt
|
||||
discover.admin.pages=Pages in sitemap
|
||||
discover.admin.note=These surfaces enrich the head/response layer; the kernel already emits canonical, hreflang and robots.
|
||||
discover.admin.help=Discoverability help & reference
|
||||
|
||||
# Shared
|
||||
discover.on=on
|
||||
discover.off=off
|
||||
|
||||
# Advisory quality-check finding (resolved by the host as quality.<finding-code> in the operator UI locale)
|
||||
quality.discoverability.faq.unmarked=This page has an on-page FAQ (a <details>/<summary> block) that isn't emitting FAQPage structured data — declare it in the discoverability plugin's content.schema for this path.
|
||||
|
||||
# Page editor: what the page is described as (PageTypeCheck, 2.2.0)
|
||||
discover.pagetype.off=Structured data is switched off for this site, so this page is not described to search engines.
|
||||
discover.pagetype.default=Structured data: this page is a {0}, the site''s Default page type.
|
||||
discover.pagetype.schema=Structured data: this page is a {0}, set by Per-page types (pattern {1}).
|
||||
discover.pagetype.added=Per-page types also add: {0}.
|
||||
discover.pagetype.unknown=Per-page types name {0} for this page, which this plugin does not know; it is ignored.
|
||||
discover.pagetype.extra=Per-page types give this page more than one page type; only the first ({0}) applies, {1} is ignored.
|
||||
discover.pagetype.noindex=Structured data: this page is excluded from search engines (noindex), so it carries no structured data.
|
||||
discover.pagetype.otherLanguage=Per-page types: {0} describes the default language''s page, not this one; a page in another language is matched only by its own path. To describe this page, add {1}.
|
||||
# A block that applies but publishes nothing of its own ({0} = its type); shown in the editor and, after the pattern, in the check below the form
|
||||
discover.gap.faq={0} has no question with both q: and a:, so the page is an {0} with no questions.
|
||||
discover.gap.items={0} has no item with a url:, so no list is published.
|
||||
|
||||
# Admin fragment: Per-page types check (2.2.0)
|
||||
discover.schema.title=Per-page types check
|
||||
discover.schema.ok=No problems found.
|
||||
discover.schema.syntax=Per-page types cannot be read, so no page gets a per-page type: {0}
|
||||
discover.schema.notBlock={0}: the value must be a type block (type: ...) or a list of them; ignored.
|
||||
discover.schema.slash={0}: a pattern starts with / and matches page paths.
|
||||
discover.schema.star={0}: * works only at the end of a pattern; here it is matched as a character.
|
||||
discover.schema.unknown={0}: {1} is not a type this plugin knows; ignored.
|
||||
discover.schema.twoPageTypes={0}: more than one page type; only the first applies.
|
||||
@@ -0,0 +1,141 @@
|
||||
# Discoverability plugin — Español. Añadido de forma aditiva al MessageSource de consola + por-sitio.
|
||||
|
||||
# Permiso de punto de control
|
||||
discover.perm.settings=Gestionar visibilidad (SEO y GEO)
|
||||
|
||||
# Formulario de configuración: secciones (título + una línea de introducción)
|
||||
discover.grp.structured=Datos estructurados para buscadores
|
||||
discover.grp.structured.help=Indica a los buscadores qué es cada página y quién publica el sitio. Activado por defecto; a la mayoría de los sitios solo les falta completar la organización.
|
||||
discover.grp.sitemap=Mapa del sitio y robots.txt
|
||||
discover.grp.sitemap.help=La lista de páginas que se ofrece a los rastreadores y las reglas de lo que pueden descargar.
|
||||
discover.grp.ai=Rastreadores de IA
|
||||
discover.grp.ai.help=Si los rastreadores de las empresas de IA pueden leer el sitio. No afecta a los buscadores normales.
|
||||
discover.grp.geo=Motores de respuesta de IA (GEO)
|
||||
discover.grp.geo.help=Extras opcionales que ayudan a los asistentes de IA a entender y citar este sitio. Desactivado por defecto.
|
||||
discover.grp.software=Producto en la página de inicio
|
||||
discover.grp.software.help=Para sitios que presentan un producto de software o una aplicación. Desactivado por defecto.
|
||||
discover.grp.indexnow=Avisar a los buscadores de los cambios (IndexNow)
|
||||
discover.grp.indexnow.help=Avisa a Bing, Yandex, Seznam, Naver y Yep cuando cambian las páginas. Google no usa IndexNow.
|
||||
|
||||
# Formulario de configuración: etiquetas (cortas; la explicación es la línea de ayuda de cada campo)
|
||||
discover.set.jsonldEnabled=Datos estructurados (JSON-LD)
|
||||
discover.set.jsonldType=Tipo de página predeterminado
|
||||
discover.set.breadcrumbs=Ruta de migas
|
||||
discover.set.contentSchema=Tipos por página (content.schema)
|
||||
discover.set.orgName=Nombre de la organización
|
||||
discover.set.orgLogo=Logotipo de la organización
|
||||
discover.set.orgSameAs=Perfiles oficiales
|
||||
discover.set.softwareEnabled=Describir un producto en la página de inicio
|
||||
discover.set.softwareName=Nombre del producto
|
||||
discover.set.softwareDescription=Descripción
|
||||
discover.set.softwareCategory=Categoría
|
||||
discover.set.softwareOs=Sistemas operativos
|
||||
discover.set.softwarePrice=Precio
|
||||
discover.set.softwareCurrency=Moneda
|
||||
discover.set.softwareLicense=URL de la licencia
|
||||
discover.set.softwareUrl=URL del producto
|
||||
discover.set.softwareScreenshot=URL de captura de pantalla
|
||||
discover.set.sitemapEnabled=Mapa del sitio (/sitemap.xml)
|
||||
discover.set.robotsAiDefault=Política predeterminada de rastreadores de IA
|
||||
discover.set.robotsAiAgentsExtra=Nombres adicionales de rastreadores de IA
|
||||
discover.set.robotsAiPolicy=Rastreadores de IA en este sitio
|
||||
discover.set.robotsAiTraining=Rastreadores de IA de entrenamiento
|
||||
discover.set.robotsAiRetrieval=Rastreadores de motores de respuesta
|
||||
discover.set.robotsAiUser=Visitas de IA pedidas por una persona
|
||||
discover.set.robotsExtraDisallow=Rutas que los rastreadores deben omitir
|
||||
discover.set.robotsCustom=robots.txt personalizado
|
||||
discover.set.geoEnabled=Optimización para motores de respuesta (GEO)
|
||||
discover.set.geoSummary=Resumen del sitio
|
||||
discover.set.geoSpeakable=Partes «speakable» de una página
|
||||
discover.set.searchUrl=URL de búsqueda del sitio
|
||||
discover.set.indexnowEnabled=Avisar a los buscadores de los cambios
|
||||
discover.set.indexnowKey=Clave IndexNow
|
||||
discover.set.indexnowAppEnabled=Permitir que los sitios usen IndexNow
|
||||
discover.set.indexnowEndpoint=Punto de envío
|
||||
discover.set.indexnowBatch=Segundos para agrupar cambios
|
||||
discover.set.indexnowMaxUrls=Máximo de URLs por envío
|
||||
discover.set.indexnowMaxQueued=Máximo de URLs en cola por sitio
|
||||
discover.set.indexnowTimeout=Tiempo límite del envío (segundos)
|
||||
|
||||
# Formulario de configuración: líneas de ayuda (una línea corta, siempre visible bajo el campo)
|
||||
discover.help.jsonldEnabled=Añade datos estructurados de schema.org a cada página para que los buscadores entiendan qué es. Déjalo activado: todo lo demás de esta sección lo necesita.
|
||||
discover.help.jsonldType=Article para blogs y sitios de noticias, WebPage para todo lo demás. Toda página se describe con este tipo, salvo que Avanzado → Tipos por página le dé uno propio: un tipo de página ahí (Article, AboutPage, ContactPage, FAQPage, CollectionPage, …) sustituye a este en las páginas que coinciden, y cualquier otro tipo (un producto, un servicio, un negocio local) se añade a la página. El editor de páginas muestra el tipo de cada página y de dónde viene.
|
||||
discover.help.breadcrumbs=Añade a los resultados de búsqueda una ruta Inicio \u203a Página. Aparece un nivel intermedio donde content.schema lo declara (breadcrumb: {name, url}).
|
||||
discover.help.orgName=Quién publica este sitio. Déjalo en blanco para no publicar ninguna organización.
|
||||
discover.help.orgLogo=Una imagen cuadrada: una URL completa o una ruta de este sitio, como /img/logo.png.
|
||||
discover.help.orgSameAs=Tus perfiles oficiales (LinkedIn, GitHub, …). Vincula este sitio con ellos.
|
||||
discover.help.contentSchema=Declara tipos de página (FAQ, producto, servicio, negocio local…) por ruta, en YAML. Consulta los ejemplos en la ayuda.
|
||||
discover.help.sitemapEnabled=Sirve /sitemap.xml y lo anuncia en robots.txt. Déjalo activado.
|
||||
discover.help.robotsExtraDisallow=Rutas que todos los rastreadores deben omitir, por ejemplo /borradores/.
|
||||
discover.help.robotsCustom=Reemplaza TODO el robots.txt generado, incluida la línea del mapa del sitio y las reglas de IA. Úsalo solo si sabes que lo necesitas.
|
||||
discover.help.robotsAiPolicy=Permite (allow) o rechaza (disallow) los rastreadores de IA. «inherit» sigue el valor predeterminado de la plataforma.
|
||||
discover.help.robotsAiTraining=Rastreadores que recopilan texto para entrenar modelos de IA. Rechazarlos no le cuesta nada visible a este sitio.
|
||||
discover.help.robotsAiRetrieval=Rastreadores detrás de las respuestas de IA (búsqueda de ChatGPT, Perplexity…). Rechazarlos saca a este sitio de esas respuestas.
|
||||
discover.help.robotsAiUser=Una visita que una persona pidió a un asistente de IA. Rechazarla rompe esa visita.
|
||||
discover.help.robotsAiDefault=Lo que recibe un sitio configurado en «inherit». «allow» mantiene los sitios visibles para los motores de respuesta.
|
||||
discover.help.robotsAiAgentsExtra=Nombres de rastreadores de IA que el complemento aún no conoce, uno por línea. Escribe training=Nombre, retrieval=Nombre o user=Nombre para asignarle una clase; sin ello, el nombre sigue la política general de IA de cada sitio.
|
||||
discover.help.geoEnabled=Publica /llms.txt y marca las páginas para asistentes de IA. La URL de búsqueda y las partes «speakable» también necesitan los datos estructurados activados.
|
||||
discover.help.geoSummary=Un párrafo en lenguaje sencillo sobre el sitio, al principio de /llms.txt.
|
||||
discover.help.geoSpeakable=Selectores CSS de las partes de una página que vale la pena leer en voz alta o citar. El valor predeterminado sirve para la mayoría de los sitios.
|
||||
discover.help.searchUrl=Tu página de resultados de búsqueda, p. ej. /buscar?q={query}. Sin {query} se añade ?q=. Se publica como SearchAction de schema.org; Google ya no muestra un cuadro de búsqueda a partir de él.
|
||||
discover.help.softwareEnabled=Describe tu producto como SoftwareApplication, solo en la página de inicio. Necesita los datos estructurados activados.
|
||||
discover.help.softwareName=En blanco usa el nombre de la organización o, si no hay, el del sitio.
|
||||
discover.help.softwareDescription=En blanco usa la descripción de la página de inicio.
|
||||
discover.help.softwareCategory=Una categoría de schema.org, p. ej. WebApplication, BusinessApplication, DeveloperApplication.
|
||||
discover.help.softwareOs=Dónde funciona, p. ej. Web, o Windows, macOS, Linux.
|
||||
discover.help.softwarePrice=Un número; 0 significa gratis. En blanco no publica precio.
|
||||
discover.help.softwareCurrency=Un código de moneda de tres letras, p. ej. USD, MXN, EUR.
|
||||
discover.help.softwareLicense=Un enlace a la licencia del producto.
|
||||
discover.help.softwareUrl=En blanco usa la página de inicio.
|
||||
discover.help.softwareScreenshot=Una URL completa a una imagen del producto.
|
||||
discover.help.indexnowEnabled=Envía las direcciones de las páginas que cambian a los buscadores que usan IndexNow. Google no lo usa.
|
||||
discover.help.indexnowKey=Una cadena aleatoria de 8 a 128 letras, dígitos o guiones (la regla de IndexNow). Se publica en /indexnow-key.txt para demostrar que el sitio es tuyo.
|
||||
discover.help.indexnowAppEnabled=Permite que cada sitio active IndexNow por su cuenta. Activado, este servidor hace peticiones salientes al punto de envío de IndexNow.
|
||||
discover.help.indexnowEndpoint=A dónde van los envíos. El punto compartido reenvía a todos los buscadores participantes.
|
||||
discover.help.indexnowBatch=Los cambios se agrupan durante este tiempo y se envían juntos.
|
||||
discover.help.indexnowMaxUrls=Las URLs que excedan este límite en un envío no se envían (se registra una advertencia); esas páginas se siguen rastreando de la forma habitual.
|
||||
discover.help.indexnowMaxQueued=Cuando un sitio tiene esta cantidad de cambios en espera, los siguientes no se encolan hasta el próximo envío (se registra una advertencia).
|
||||
discover.help.indexnowTimeout=Cuánto esperar al punto de envío antes de abandonar un envío.
|
||||
|
||||
# Tarjeta del panel
|
||||
discover.card.title=Visibilidad
|
||||
discover.card.pages=Páginas
|
||||
|
||||
# Fragmento de estado (admin)
|
||||
discover.admin.title=Estado de visibilidad
|
||||
discover.admin.jsonld=Datos estructurados
|
||||
discover.admin.sitemap=Mapa del sitio
|
||||
discover.admin.geo=GEO · llms.txt
|
||||
discover.admin.pages=Páginas en el mapa del sitio
|
||||
discover.admin.note=Estas superficies enriquecen la capa de cabecera/respuesta; el núcleo ya emite canonical, hreflang y robots.
|
||||
discover.admin.help=Ayuda y referencia de visibilidad
|
||||
|
||||
# Compartido
|
||||
discover.on=activado
|
||||
discover.off=desactivado
|
||||
|
||||
# Hallazgo de la verificación de calidad (el host lo resuelve como quality.<código> en el idioma del operador)
|
||||
quality.discoverability.faq.unmarked=Esta página tiene un FAQ en la propia página (un bloque <details>/<summary>) que no emite datos estructurados FAQPage — decláralo en el content.schema del complemento de descubribilidad para esta ruta.
|
||||
|
||||
# Editor de páginas: cómo se describe la página (PageTypeCheck, 2.2.0)
|
||||
discover.pagetype.off=Los datos estructurados están desactivados en este sitio, así que esta página no se describe a los buscadores.
|
||||
discover.pagetype.default=Datos estructurados: esta página es un {0}, el tipo de página predeterminado del sitio.
|
||||
discover.pagetype.schema=Datos estructurados: esta página es un {0}, fijado en Tipos por página (patrón {1}).
|
||||
discover.pagetype.added=Tipos por página también añade: {0}.
|
||||
discover.pagetype.unknown=Tipos por página nombra {0} para esta página, un tipo que este complemento no conoce; se ignora.
|
||||
discover.pagetype.extra=Tipos por página da a esta página más de un tipo de página; solo se aplica el primero ({0}), {1} se ignora.
|
||||
discover.pagetype.noindex=Datos estructurados: esta página está excluida de los buscadores (noindex), así que no lleva datos estructurados.
|
||||
discover.pagetype.otherLanguage=Tipos por página: {0} describe la página del idioma predeterminado, no esta; una página en otro idioma solo coincide con su propia ruta. Para describir esta página, añade {1}.
|
||||
# Un bloque que se aplica pero no publica nada propio ({0} = su tipo); se muestra en el editor y, tras el patrón, en la revisión bajo el formulario
|
||||
discover.gap.faq={0} no tiene ninguna pregunta con q: y a:, así que la página es un {0} sin preguntas.
|
||||
discover.gap.items={0} no tiene ningún elemento con url:, así que no se publica ninguna lista.
|
||||
|
||||
# Fragmento de administración: revisión de Tipos por página (2.2.0)
|
||||
discover.schema.title=Revisión de Tipos por página
|
||||
discover.schema.ok=No se encontraron problemas.
|
||||
discover.schema.syntax=No se puede leer Tipos por página, así que ninguna página recibe un tipo por página: {0}
|
||||
discover.schema.notBlock={0}: el valor debe ser un bloque de tipo (type: ...) o una lista de ellos; se ignora.
|
||||
discover.schema.slash={0}: un patrón empieza con / y se compara con las rutas de las páginas.
|
||||
discover.schema.star={0}: * solo funciona al final de un patrón; aquí se toma como un carácter.
|
||||
discover.schema.unknown={0}: {1} no es un tipo que este complemento conozca; se ignora.
|
||||
discover.schema.twoPageTypes={0}: más de un tipo de página; solo se aplica el primero.
|
||||
@@ -0,0 +1,176 @@
|
||||
# =============================================================================
|
||||
# Runway Discoverability Plugin — descriptor
|
||||
# SEO+ (structured data + sitemap) and GEO (llms.txt + answer schema) in one
|
||||
# plugin. The install folder name MUST equal this `id`: external/plugins/discoverability/.
|
||||
# =============================================================================
|
||||
id: discoverability
|
||||
name: Discoverability (SEO+ & GEO)
|
||||
version: 2.3.0
|
||||
|
||||
# The kernel SPI level this plugin needs. It links ONLY the SPI and uses its service tier: PluginSettings, Sites
|
||||
# and RouteRequest#origin, ContentCatalogView / CatalogEntry / LocalizedUrl, the SiteEventListener change events
|
||||
# with before-and-after URLs, and — since 2.1.0 — HeadContext#origin (SPI 1.0.0), which makes a host-less site's
|
||||
# JSON-LD absolute. A kernel below the floor BLOCKS this release at startup with a reason instead of failing on
|
||||
# the first page that reaches the missing method.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# The @Configuration registered into the host context before refresh. Its package (mx.quest.discover) lives
|
||||
# OUTSIDE mx.quest.runway so the host never double-scans it. Beans are wired EXPLICITLY (no @ComponentScan).
|
||||
mainClass: mx.quest.discover.DiscoverabilityConfig
|
||||
|
||||
# This plugin has no hard dependency (always loads) and is NOT essential. It enriches the head the kernel already
|
||||
# fills (canonical + hreflang + Open Graph + Twitter cards) with the structured-data it leaves out, and OWNS the
|
||||
# crawl surfaces the lean core does not ship: /sitemap.xml, /llms.txt and /robots.txt. It never duplicates a tag
|
||||
# the kernel already emits. (An install without this plugin serves no /robots.txt, which crawlers treat as
|
||||
# allow-all.)
|
||||
|
||||
# --- Grantable control-point permission -----------------------------------------------------------------
|
||||
# `settings` is the reserved id that gates this plugin's per-tenant config editor. defaultRoles is EMPTY: the
|
||||
# control point starts ungranted — admins hold it via the wildcard tier; a tenant superadmin grants it to
|
||||
# OPERATOR or a custom role. A reserved/master tier in defaultRoles is a hard fail.
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: discover.perm.settings, defaultRoles: [] }
|
||||
|
||||
# --- Settings-form layout (presentation only). Sections in this order; each field below names its `group`. Every field has a
|
||||
# `help` line shown under it; `helpAnchor` links into the help page for what does not fit in one line;
|
||||
# `advanced` fields sit in a collapsed "Advanced" part of their section (opened automatically when one is
|
||||
# set); `showWhen` hides a field while the named switch is off (it is still saved). ---------------------
|
||||
helpUrl: /__plugin/discoverability/static/discoverability-help.html
|
||||
settingGroups:
|
||||
- { id: structured, label: discover.grp.structured, help: discover.grp.structured.help, helpAnchor: structured-data }
|
||||
- { id: sitemap, label: discover.grp.sitemap, help: discover.grp.sitemap.help, helpAnchor: sitemap-robots }
|
||||
- { id: ai, label: discover.grp.ai, help: discover.grp.ai.help, helpAnchor: ai-crawlers }
|
||||
- { id: geo, label: discover.grp.geo, help: discover.grp.geo.help, helpAnchor: geo }
|
||||
- { id: software, label: discover.grp.software, help: discover.grp.software.help, helpAnchor: software }
|
||||
- { id: indexnow, label: discover.grp.indexnow, help: discover.grp.indexnow.help, helpAnchor: indexnow }
|
||||
|
||||
# --- App-level settings (PLATFORM concerns; over external/plugin-settings/discoverability.yml as
|
||||
# runway.plugin.discoverability.*; applied on RESTART; bound via DiscoverabilityProperties). ----------
|
||||
settings:
|
||||
# The default AI/LLM-crawler posture a site inherits when its per-tenant robots.ai-policy is `inherit`:
|
||||
# `allow` (GEO-friendly, the platform default) or `disallow` (opt every un-overriding site out of AI crawling).
|
||||
- { key: robots.ai-default, type: enum, default: allow, range: "allow,disallow", label: discover.set.robotsAiDefault,
|
||||
group: ai, help: discover.help.robotsAiDefault }
|
||||
# Extra AI/LLM crawler user-agent names appended to the plugin's built-in list. The built-in list is a
|
||||
# compile-time constant and goes STALE SILENTLY — an agent it does not name is simply not covered by a
|
||||
# site's opt-out, and nothing reports that. This closes a newly announced agent without a plugin release.
|
||||
# Additive only; a retired name costs one inert User-agent line.
|
||||
- { key: robots.ai-agents-extra, type: list, default: "", label: discover.set.robotsAiAgentsExtra,
|
||||
group: ai, help: discover.help.robotsAiAgentsExtra, advanced: true }
|
||||
# IndexNow — the operator's egress decision. OFF by default: an upgrade must never start making network calls
|
||||
# a deployment was not making before. With this off, a tenant enabling IndexNow gets a WARN naming the setting.
|
||||
- { key: indexnow.enabled, type: boolean, default: false, label: discover.set.indexnowAppEnabled,
|
||||
group: indexnow, help: discover.help.indexnowAppEnabled }
|
||||
- { key: indexnow.endpoint, type: string, default: "https://api.indexnow.org/indexnow", label: discover.set.indexnowEndpoint,
|
||||
group: indexnow, help: discover.help.indexnowEndpoint, showWhen: indexnow.enabled, advanced: true }
|
||||
- { key: indexnow.batch-seconds, type: int, default: 60, range: "5..3600", label: discover.set.indexnowBatch,
|
||||
group: indexnow, help: discover.help.indexnowBatch, showWhen: indexnow.enabled, advanced: true }
|
||||
- { key: indexnow.max-urls-per-submission, type: int, default: 1000, range: "1..10000", label: discover.set.indexnowMaxUrls,
|
||||
group: indexnow, help: discover.help.indexnowMaxUrls, showWhen: indexnow.enabled, advanced: true }
|
||||
- { key: indexnow.max-queued-per-site, type: int, default: 5000, range: "1..100000", label: discover.set.indexnowMaxQueued,
|
||||
group: indexnow, help: discover.help.indexnowMaxQueued, showWhen: indexnow.enabled, advanced: true }
|
||||
- { key: indexnow.timeout-seconds, type: int, default: 10, range: "1..120", label: discover.set.indexnowTimeout,
|
||||
group: indexnow, help: discover.help.indexnowTimeout, showWhen: indexnow.enabled, advanced: true }
|
||||
|
||||
# --- Per-tenant settings (tenant-owned BEHAVIOUR; over sites/<id>/plugins/discoverability.yml; applied ----
|
||||
# IMMEDIATELY — the host evicts its cache on save; read live via the SPI's PluginSettings, which overlays
|
||||
# the stored values on the `default:`s declared here, so each code fallback must equal its default).
|
||||
# Declared in display order, section by section. Changing the ORDER or the layout keys never changes a
|
||||
# stored value: the keys themselves are the contract.
|
||||
siteSettings:
|
||||
# -- Structured data (schema.org JSON-LD). Everything structured — organization, the homepage product, the
|
||||
# per-page types, and GEO's SearchAction/Speakable — is emitted only while jsonld.enabled is on. --
|
||||
- { key: jsonld.enabled, type: boolean, default: true, label: discover.set.jsonldEnabled,
|
||||
group: structured, help: discover.help.jsonldEnabled }
|
||||
- { key: jsonld.type, type: enum, default: WebPage, range: "WebPage,Article", label: discover.set.jsonldType,
|
||||
group: structured, help: discover.help.jsonldType, showWhen: jsonld.enabled }
|
||||
- { key: jsonld.breadcrumbs, type: boolean, default: true, label: discover.set.breadcrumbs,
|
||||
group: structured, help: discover.help.breadcrumbs, showWhen: jsonld.enabled }
|
||||
- { key: org.name, type: string, label: discover.set.orgName,
|
||||
group: structured, help: discover.help.orgName, showWhen: jsonld.enabled }
|
||||
- { key: org.logo, type: string, label: discover.set.orgLogo,
|
||||
group: structured, help: discover.help.orgLogo, showWhen: jsonld.enabled }
|
||||
- { key: org.sameas, type: list, default: "", label: discover.set.orgSameAs,
|
||||
group: structured, help: discover.help.orgSameAs, showWhen: jsonld.enabled }
|
||||
# Per-page/section typed structured data: a small YAML doc keyed by URL-path pattern (exact, else the longest
|
||||
# trailing-* prefix; matched on the page's own path, so /faq does not reach /es/faq), each entry declaring a `type`
|
||||
# + its fields. A PAGE TYPE replaces the Default page type (jsonld.type) as the page's own @type (2.2.0):
|
||||
# Article/BlogPosting/NewsArticle, FAQPage, CollectionPage, WebPage, AboutPage, ContactPage, ItemPage,
|
||||
# SearchResultsPage; the first one applies. The other types ADD an entity beside the page: Product,
|
||||
# Service/ProfessionalService, LocalBusiness/CafeOrCoffeeShop, Person, ItemList. An entry may also be a LIST of
|
||||
# type-blocks when a single page carries several types (e.g. a pricing page that is both FAQPage and Service). A
|
||||
# detail entry may carry `breadcrumb: {name, url}` to insert its parent collection as a middle breadcrumb level.
|
||||
# Values are tenant-owned; the plugin owns the typing. Full reference: static/discoverability-help.html.
|
||||
- { key: content.schema, type: text, label: discover.set.contentSchema,
|
||||
group: structured, help: discover.help.contentSchema, helpAnchor: content-schema, advanced: true }
|
||||
# -- Sitemap & robots.txt (the plugin owns /robots.txt; its Sitemap: line follows sitemap.enabled) --
|
||||
- { key: sitemap.enabled, type: boolean, default: true, label: discover.set.sitemapEnabled,
|
||||
group: sitemap, help: discover.help.sitemapEnabled }
|
||||
- { key: robots.extra-disallow, type: list, label: discover.set.robotsExtraDisallow,
|
||||
group: sitemap, help: discover.help.robotsExtraDisallow }
|
||||
- { key: robots.custom, type: text, label: discover.set.robotsCustom,
|
||||
group: sitemap, help: discover.help.robotsCustom, helpAnchor: robots-custom, advanced: true }
|
||||
# -- AI crawlers. `inherit` on the policy = the platform's robots.ai-default. --
|
||||
- { key: robots.ai-policy, type: enum, default: inherit, range: "inherit,allow,disallow", label: discover.set.robotsAiPolicy,
|
||||
group: ai, help: discover.help.robotsAiPolicy, inheritsFrom: "app:robots.ai-default" }
|
||||
# Per-CLASS overrides of the AI posture above. `inherit` (the default) means "whatever robots.ai-policy says",
|
||||
# so a site that sets none of these behaves exactly as before these keys existed. The point of splitting them
|
||||
# is that the three classes have opposite consequences: declining TRAINING costs the site nothing it can see,
|
||||
# declining RETRIEVAL removes it from generated answers, and declining USER breaks a fetch a person asked for.
|
||||
# Key names are robots.ai-<class>, not robots.ai-policy.<class>: the latter would make one key both a scalar
|
||||
# and a map prefix.
|
||||
- { key: robots.ai-training, type: enum, default: inherit, range: "inherit,allow,disallow", label: discover.set.robotsAiTraining,
|
||||
group: ai, help: discover.help.robotsAiTraining, inheritsFrom: robots.ai-policy, advanced: true }
|
||||
- { key: robots.ai-retrieval, type: enum, default: inherit, range: "inherit,allow,disallow", label: discover.set.robotsAiRetrieval,
|
||||
group: ai, help: discover.help.robotsAiRetrieval, inheritsFrom: robots.ai-policy, advanced: true }
|
||||
- { key: robots.ai-user, type: enum, default: inherit, range: "inherit,allow,disallow", label: discover.set.robotsAiUser,
|
||||
group: ai, help: discover.help.robotsAiUser, inheritsFrom: robots.ai-policy, advanced: true }
|
||||
# -- GEO : opt-in Generative Engine Optimization. search.url and geo.speakable also need structured data on. --
|
||||
- { key: geo.enabled, type: boolean, default: false, label: discover.set.geoEnabled,
|
||||
group: geo, help: discover.help.geoEnabled }
|
||||
- { key: geo.summary, type: text, label: discover.set.geoSummary,
|
||||
group: geo, help: discover.help.geoSummary, showWhen: geo.enabled }
|
||||
- { key: geo.speakable, type: list, default: "h1,main", label: discover.set.geoSpeakable,
|
||||
group: geo, help: discover.help.geoSpeakable, showWhen: geo.enabled }
|
||||
- { key: search.url, type: string, label: discover.set.searchUrl,
|
||||
group: geo, help: discover.help.searchUrl, showWhen: geo.enabled }
|
||||
# -- SoftwareApplication (homepage product/app entity; configure here INSTEAD of hand-authoring JSON-LD in
|
||||
# seo.yml's extraHead — that leaked onto every page with a wrong url; this emits once, @id-linked). --
|
||||
- { key: software.enabled, type: boolean, default: false, label: discover.set.softwareEnabled,
|
||||
group: software, help: discover.help.softwareEnabled }
|
||||
- { key: software.name, type: string, label: discover.set.softwareName,
|
||||
group: software, help: discover.help.softwareName, showWhen: software.enabled }
|
||||
- { key: software.description, type: text, label: discover.set.softwareDescription,
|
||||
group: software, help: discover.help.softwareDescription, showWhen: software.enabled }
|
||||
- { key: software.category, type: string, label: discover.set.softwareCategory,
|
||||
group: software, help: discover.help.softwareCategory, showWhen: software.enabled }
|
||||
- { key: software.os, type: string, default: Web, label: discover.set.softwareOs,
|
||||
group: software, help: discover.help.softwareOs, showWhen: software.enabled }
|
||||
- { key: software.price, type: string, label: discover.set.softwarePrice,
|
||||
group: software, help: discover.help.softwarePrice, showWhen: software.enabled }
|
||||
- { key: software.currency, type: string, default: USD, label: discover.set.softwareCurrency,
|
||||
group: software, help: discover.help.softwareCurrency, showWhen: software.enabled }
|
||||
- { key: software.license, type: string, label: discover.set.softwareLicense,
|
||||
group: software, help: discover.help.softwareLicense, showWhen: software.enabled }
|
||||
- { key: software.url, type: string, label: discover.set.softwareUrl,
|
||||
group: software, help: discover.help.softwareUrl, showWhen: software.enabled }
|
||||
- { key: software.screenshot, type: string, label: discover.set.softwareScreenshot,
|
||||
group: software, help: discover.help.softwareScreenshot, showWhen: software.enabled }
|
||||
# -- IndexNow: tell participating engines (Bing, Yandex, Seznam, Naver, Yep) that content changed. NOT Google.
|
||||
# OFF by default, and inert unless the PLATFORM operator has also permitted it (indexnow.enabled at the app
|
||||
# level) — this is the one feature that makes an outbound request on the tenant's behalf, so it needs both
|
||||
# the operator's permission (they own the network) and the tenant's (they own the URLs being disclosed).
|
||||
- { key: indexnow.enabled, type: boolean, default: false, label: discover.set.indexnowEnabled,
|
||||
group: indexnow, help: discover.help.indexnowEnabled, requiresPlatform: indexnow.enabled }
|
||||
- { key: indexnow.key, type: string, label: discover.set.indexnowKey,
|
||||
group: indexnow, help: discover.help.indexnowKey, showWhen: indexnow.enabled }
|
||||
|
||||
# --- No top-level tenant-console menu entry --------------------------------------------------------------
|
||||
# The plugin does NOT contribute its own menu link. The host now surfaces this plugin's per-tenant config as a
|
||||
# "Discoverability (SEO+ & GEO)" entry inside the console's Settings menu (any plugin with a siteSettings schema
|
||||
# gets one), and the help/reference page is linked from within that settings form (opens in a new tab). Adding a
|
||||
# separate menu item would duplicate that entry point.
|
||||
|
||||
# --- Tenant dashboard card (fragment resolves to __plugin__/discoverability/dashboard = templates/dashboard.*) --
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 30, fragment: dashboard, permission: "discoverability|settings" }
|
||||
@@ -0,0 +1,198 @@
|
||||
<?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 dependency versions the Runway kernel uses (Spring Boot 4.0.6), so every
|
||||
`provided` Spring / Jackson type the plugin compiles against is byte-identical to the class the host
|
||||
loads. A plugin is NOT a Spring Boot application — there is NO spring-boot-maven-plugin repackage;
|
||||
`mvn package` produces a THIN jar of only this plugin's own classes.
|
||||
-->
|
||||
<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-discoverability</artifactId>
|
||||
<version>2.3.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Discoverability 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>
|
||||
SEO+ and GEO for Runway: schema.org JSON-LD structured data (WebSite / WebPage / Organization /
|
||||
BreadcrumbList), a per-site sitemap.xml with hreflang alternates, and — opt-in — Generative Engine
|
||||
Optimization (llms.txt, WebSite SearchAction, Speakable). It enriches the head/response layer the
|
||||
kernel already fills with canonical + hreflang + Open Graph + Twitter cards, adding the structured-data and
|
||||
crawl-surface layer the lean core leaves out. One plugin, two capability areas, one JSON-LD core.
|
||||
</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>
|
||||
<!-- The Runway SPI this plugin compiles against (installed in ~/.m2 by the host's `mvn install`): the
|
||||
in-development kernel while developing, a released tag for a release build. The SPI LEVEL it needs at
|
||||
runtime is declared separately, as plugin.yml's requiresSpi. -->
|
||||
<runway.version>1.0.0</runway.version>
|
||||
<!-- The host-integration tests (Host*Test, which link runway-app) are left out of the default build; the
|
||||
host-it profile below clears this. -->
|
||||
<host-it.excludes>**/Host*Test.java</host-it.excludes>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- The dependency-free extension API (SPI interfaces + immutable model records). COMPILE scope —
|
||||
the host's own stable artifact, resolved parent-first at runtime. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- NO runway-app dependency in the default build, 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. Host services (PluginSettings, ContentCatalogView, Sites) arrive by injection of SPI types.
|
||||
runway-app appears ONLY in the `host-it` profile below, test-scoped. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring context/Boot for @Configuration/@Bean at compile time; host-provided at runtime. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- Jackson 3 (tools.jackson) — used to serialize JSON-LD safely (transitively brings databind's
|
||||
JsonMapper). BOM-managed; host-provided at runtime (do NOT bundle). -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Wiring/unit tests run against the compiled classes (NEVER spring-boot:run — DevTools' restart
|
||||
classloader loads ZERO plugins). -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- Stable deployed filename (no version/classifier): target/runway-plugin-discoverability.jar. -->
|
||||
<finalName>runway-plugin-discoverability</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<testExcludes>
|
||||
<testExclude>${host-it.excludes}</testExclude>
|
||||
</testExcludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>${host-it.excludes}</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!--
|
||||
After the jar is built, assemble BOTH installable forms the platform accepts:
|
||||
1. target/discoverability/ — the install-ready folder for a FILESYSTEM install
|
||||
(`cp -r target/discoverability <runway-external>/plugins/` + restart).
|
||||
2. target/runway-plugin-discoverability-<version>.zip — the archive the MANAGEMENT UI upload
|
||||
expects (/__app/plugins → install): plugin.yml under a single wrapping dir (discoverability/)
|
||||
alongside the jar + static/ templates/ i18n/.
|
||||
-->
|
||||
<plugin>
|
||||
<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}/discoverability"/>
|
||||
<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-discoverability.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/static">
|
||||
<fileset dir="${project.basedir}/static"/>
|
||||
</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="discoverability"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-discoverability-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="discoverability/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder: ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-discoverability-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<!--
|
||||
Host-integration tests: `mvn -P host-it verify`. They build REAL kernel objects —
|
||||
the kernel's own descriptor parser and settings merge, its content catalog and URL authority — to prove
|
||||
the plugin's descriptor and its output agree with the kernel it runs on. The only place runway-app may
|
||||
appear, and only test-scoped: the shipped jar never links it. The tests are src/test/java/**/Host*Test.java;
|
||||
the default build neither compiles nor runs them (the `host-it.excludes` property, above).
|
||||
-->
|
||||
<profile>
|
||||
<id>host-it</id>
|
||||
<properties>
|
||||
<host-it.excludes>**/none-excluded</host-it.excludes>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-app</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env bash
|
||||
# Before/after proof for a release: boot ONE throwaway Runway deployment with the PREVIOUS release of this plugin,
|
||||
# fetch every surface it produces for a fixture site, swap in THIS build (same deployment, same files, same
|
||||
# mtimes), fetch again, and diff. For an unchanged site the two must be byte-identical except for the changes the
|
||||
# CHANGELOG documents as fixes.
|
||||
#
|
||||
# The fixture (the wizard's default site, made bilingual en + es): Home; About at /about and /es/acerca with an FAQ
|
||||
# typed in content.schema; a page published in Spanish only; a noindex page; a page canonicalised to About; a page
|
||||
# whose canonical is its own path written root-relative ("/selfrel"); a draft. GEO on, an Organization, a
|
||||
# SoftwareApplication on the home page. Each surface is fetched in three set-ups: "configured" (a base URL in
|
||||
# site.yml), "derived" (no base URL; the host derives https://<host name> — the common production case) and
|
||||
# "origin" (no base URL and no host name: the site is reached as the platform's catch-all default, and the absolute
|
||||
# URLs come from the request).
|
||||
#
|
||||
# Compared, as bodies: /sitemap.xml, /sitemap-1.xml (status), /robots.txt, /llms.txt, /indexnow-key.txt (status),
|
||||
# the JSON-LD block of /, /about, /es/acerca and /selfrel; signed in as the owner: the plugin's settings form (the
|
||||
# CSRF token masked) and the values of its admin fragment and dashboard card.
|
||||
#
|
||||
# Usage: PREVIOUS_DIR=/path/to/<previous>/target/discoverability scripts/compare-with-previous.sh [--port N]
|
||||
# PREVIOUS_DIR the previous release's install folder (plugin.yml + jar + static/ templates/ i18n/), built
|
||||
# from its tag; required
|
||||
# JAVA_HOME required: the JDK 25 that builds the plugin and runs the host
|
||||
# MVN Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR the kernel to run both on (default: the host checkout's jar matching its pom version)
|
||||
# VERIFY_TMPDIR where the throwaway deployment goes (default: $TMPDIR or /tmp)
|
||||
# VERIFY_LOG_DIR keep both captures, the diff and the host logs there (evidence)
|
||||
# Exit status: 0 when the only differences are the expected ones listed in EXPECTED below, 1 otherwise.
|
||||
# Never runs `mvn install`.
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
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
|
||||
PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
[ -n "${PREVIOUS_DIR:-}" ] && [ -f "$PREVIOUS_DIR/plugin.yml" ] || { echo "set PREVIOUS_DIR to the previous release's install folder"; exit 2; }
|
||||
|
||||
APP_USER=root; APP_PW=Disco-Admin-2026; SITE_USER=owner; SITE_PW=Disco-Site-2026
|
||||
[ -n "$PORT" ] || PORT="$(python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()')"
|
||||
BASE="http://localhost:$PORT"
|
||||
CONFIGURED="https://acme.example"
|
||||
|
||||
echo "[compare] building this plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "plugin build failed"; exit 1; }
|
||||
if [ -n "${HOST_JAR:-}" ]; then JAR="$HOST_JAR"; else
|
||||
JAR="$HOST_TARGET/runway-app-$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)-exec.jar"; fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR"; exit 1; }
|
||||
echo "[compare] host jar: $JAR"
|
||||
echo "[compare] previous: $(grep -m1 '^version' "$PREVIOUS_DIR/plugin.yml") this: $(grep -m1 '^version' "$HERE/plugin.yml")"
|
||||
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/discover-compare.XXXXXX")"
|
||||
cleanup() {
|
||||
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" && cp -r "$SCRATCH"/before "$SCRATCH"/after \
|
||||
"$SCRATCH"/*.log "$SCRATCH"/*.diff "$VERIFY_LOG_DIR"/ 2>/dev/null; }
|
||||
kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
EXT="$SCRATCH/external"; S="$EXT/sites/default"
|
||||
mkdir -p "$EXT/plugins"
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) \
|
||||
>"$1" 2>&1 & PID=$!; wait_for "$1" "Started RunwayApplication" 90 || { echo "boot failed: $1"; tail -20 "$1"; exit 1; }; }
|
||||
stop() { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; }
|
||||
|
||||
boot "$SCRATCH/wizard.log"
|
||||
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 fixture -----------------------------------------------------------------------------------------------
|
||||
T="$S/templates"
|
||||
perl -0pi -e 's/\nlocales:\n- "en"\n/\nlocales:\n- "en"\n- "es"\n/' "$S/site.yml"
|
||||
perl -0pi -e 's/\n en: About\n/\n en: About\n es: Acerca\n/' "$T/about.meta.yml"
|
||||
printf 'locales: [en, es]\nlocalizedPaths:\n es: /acerca\n' >> "$T/about.meta.yml"
|
||||
page() { # slug meta-yaml
|
||||
cp "$T/about.html" "$T/$1.html"; cp "$T/about.th.xml" "$T/$1.th.xml"; printf '%s\n' "$2" > "$T/$1.meta.yml"
|
||||
}
|
||||
page solo $'path: /solo\ntemplate: _master\nlocales: [es]\nlocalizedPaths:\n es: /solo-es\ntitle:\n es: Sólo en español\ndescription:\n es: "Una página que sólo existe en español."'
|
||||
page hidden $'path: /hidden\ntemplate: _master\ntitle:\n en: Hidden\nnoindex: true'
|
||||
page copy $'path: /copy\ntemplate: _master\ntitle:\n en: A copy of About\ncanonical: "'"$CONFIGURED"'/about"'
|
||||
page selfrel $'path: /selfrel\ntemplate: _master\ntitle:\n en: Self, root-relative\ndescription:\n en: "Its canonical is its own path."\ncanonical: /selfrel'
|
||||
page wip $'path: /wip\ntemplate: _master\ntitle:\n en: Work in progress\ndraft: true'
|
||||
mkdir -p "$S/plugins"
|
||||
cat > "$S/plugins/discoverability.yml" <<'YML'
|
||||
org.name: Acme Corp
|
||||
org.logo: /favicon.svg
|
||||
org.sameas:
|
||||
- https://social.example/acme
|
||||
geo.enabled: true
|
||||
geo.summary: We build things and write about it.
|
||||
search.url: /search
|
||||
software.enabled: true
|
||||
software.name: Acme App
|
||||
software.price: "0"
|
||||
content.schema: |
|
||||
/about:
|
||||
type: FAQPage
|
||||
faq:
|
||||
- { q: "Why?", a: "Because." }
|
||||
YML
|
||||
touch -d '2026-10-01 12:00:00 UTC' "$T"/* "$S/plugins/discoverability.yml" # fixed mtimes: <lastmod> is stable
|
||||
|
||||
JAR_C="$SCRATCH/cookies.txt"
|
||||
c() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; }
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
ld() { python3 -I -c 'import re,sys; h=sys.stdin.read(); print("\n".join(re.findall(r"<script type=\"application/ld\+json\">(.*?)</script>", h, re.S)))'; }
|
||||
capture() { # dir
|
||||
local d="$1"; mkdir -p "$d"
|
||||
curl -s "$BASE/sitemap.xml" > "$d/sitemap.xml"
|
||||
curl -s -o /dev/null -w '%{http_code}\n' "$BASE/sitemap-1.xml" > "$d/sitemap-1.status"
|
||||
curl -s "$BASE/robots.txt" > "$d/robots.txt"
|
||||
curl -s "$BASE/llms.txt" > "$d/llms.txt"
|
||||
curl -s -o /dev/null -w '%{http_code}\n' "$BASE/indexnow-key.txt" > "$d/indexnow-key.status"
|
||||
for p in / /about /es/acerca /selfrel; do curl -s "$BASE$p" | ld > "$d/jsonld$(echo "$p" | tr / _).json"; done
|
||||
}
|
||||
capture_console() { # dir
|
||||
local d="$1" t
|
||||
rm -f "$JAR_C"; t="$(c "$BASE/login" | token)"
|
||||
c -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" --data-urlencode "_csrf=$t"
|
||||
c "$BASE/__admin/plugins/discoverability/settings" > "$d/settings.page"
|
||||
python3 -I - "$d/settings.page" > "$d/settings-form.html" <<'PY'
|
||||
import re, sys
|
||||
h = open(sys.argv[1], encoding="utf-8").read()
|
||||
forms = re.findall(r"<form\b.*?</form>", h, re.S)
|
||||
print(re.sub(r'(name="_csrf" value=")[^"]*', r"\1MASKED", max(forms, key=len) if forms else "NO FORM"))
|
||||
PY
|
||||
c "$BASE/__admin" > "$d/dashboard.page"
|
||||
for f in settings dashboard; do grep -oE 'id="d[ac]-[a-z-]+"[^>]*>[^<]*<' "$d/$f.page"; done > "$d/console-values.txt"
|
||||
rm -f "$d"/*.page
|
||||
}
|
||||
cp "$S/site.yml" "$SCRATCH/site.yml.orig"
|
||||
setup() { # configured | derived | origin
|
||||
cp "$SCRATCH/site.yml.orig" "$S/site.yml"
|
||||
case "$1" in
|
||||
configured) perl -pi -e "s#^baseUrl: .*#baseUrl: \"$CONFIGURED\"#" "$S/site.yml" ;;
|
||||
origin) perl -0pi -e 's/\nhosts:\n- "localhost"\n/\nhosts: []\n/' "$S/site.yml" ;;
|
||||
esac
|
||||
}
|
||||
round() { # plugin-dir label
|
||||
rm -rf "$EXT/plugins/discoverability"; cp -r "$1" "$EXT/plugins/discoverability"
|
||||
for mode in configured derived origin; do
|
||||
setup "$mode"
|
||||
boot "$SCRATCH/$2-$mode.log"; capture "$SCRATCH/$2/$mode"
|
||||
[ "$mode" != configured ] || capture_console "$SCRATCH/$2/$mode"
|
||||
stop
|
||||
done
|
||||
}
|
||||
round "$PREVIOUS_DIR" before
|
||||
round "$HERE/target/discoverability" after
|
||||
|
||||
( cd "$SCRATCH" && diff -ru before after ) > "$SCRATCH/before-after.diff"
|
||||
echo "== differences (before = previous release, after = this build) =="
|
||||
cat "$SCRATCH/before-after.diff"
|
||||
|
||||
# The documented fixes, and nothing else:
|
||||
# - llms.txt links the Spanish-only page at its real address;
|
||||
# - a root-relative self canonical no longer drops /selfrel from the sitemap;
|
||||
# - for a site with no base URL and no host name, the trusted origin (http here) instead of the Host header with a
|
||||
# guessed https.
|
||||
python3 -I - "$SCRATCH" "$BASE" "$CONFIGURED" <<'PY'
|
||||
import os, re, sys
|
||||
root, base, configured = sys.argv[1:]
|
||||
guessed = base.replace("http://", "https://")
|
||||
problems = []
|
||||
def read(side, mode, name):
|
||||
with open(os.path.join(root, side, mode, name), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
def split(xml):
|
||||
items = re.findall(r" <url>\n.*? </url>\n", xml, re.S)
|
||||
head = xml[:xml.index(items[0])] if items else xml
|
||||
tail = xml[xml.rindex(items[-1]) + len(items[-1]):] if items else ""
|
||||
return head, items, tail
|
||||
def loc(item):
|
||||
return re.search(r"<loc>(.*?)</loc>", item).group(1)
|
||||
for mode, origin in (("configured", configured), ("derived", "https://localhost"), ("origin", base)):
|
||||
for name in sorted(os.listdir(os.path.join(root, "before", mode))):
|
||||
before, after = read("before", mode, name), read("after", mode, name)
|
||||
expected = before
|
||||
if mode == "origin":
|
||||
expected = expected.replace(guessed, base) # the trusted origin, not a guessed https
|
||||
if name == "llms.txt":
|
||||
expected = expected.replace("(" + origin + "/solo)", "(" + origin + "/es/solo-es)") # the Spanish-only page's real address
|
||||
if name == "sitemap.xml":
|
||||
# The root-relative self canonical: /selfrel's <url> is listed now, in its sorted place.
|
||||
head, items, tail = split(expected)
|
||||
added = [i for i in split(after)[1] if loc(i) == origin + "/selfrel" and i not in items]
|
||||
expected = head + "".join(sorted(items + added, key=loc)) + tail
|
||||
if expected != after:
|
||||
problems.append(mode + "/" + name)
|
||||
if problems:
|
||||
print("UNEXPECTED differences in: " + ", ".join(problems))
|
||||
sys.exit(1)
|
||||
print("RESULT: identical except the documented fixes (llms.txt link, root-relative self canonical, trusted origin)")
|
||||
PY
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# install-into.sh — copy the assembled discoverability plugin into a Runway deployment's external tree.
|
||||
# The host must be RESTARTED afterwards for the plugin to load (restart-to-install; no hot reload).
|
||||
#
|
||||
# Usage: scripts/install-into.sh <runway-external-dir>
|
||||
# e.g. scripts/install-into.sh /opt/runway-data/external
|
||||
set -euo pipefail
|
||||
|
||||
EXTERNAL="${1:?usage: install-into.sh <runway-external-dir>}"
|
||||
PROJECT_DIR="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
STAGE="$PROJECT_DIR/target/discoverability"
|
||||
|
||||
[ -d "$STAGE" ] || { echo "ERROR: $STAGE not built — run 'mvn package' first"; exit 1; }
|
||||
[ -d "$EXTERNAL" ] || { echo "ERROR: not a directory: $EXTERNAL"; exit 1; }
|
||||
|
||||
mkdir -p "$EXTERNAL/plugins"
|
||||
rm -rf "$EXTERNAL/plugins/discoverability"
|
||||
cp -a "$STAGE" "$EXTERNAL/plugins/discoverability"
|
||||
echo "installed discoverability → $EXTERNAL/plugins/discoverability"
|
||||
echo "RESTART the Runway host for it to load (plugins load only in ACTIVE mode)."
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove the
|
||||
# discoverability contract end to end (SPI 1.0.0):
|
||||
# - it loads with ZERO host-linkage and bean-name/surface findings (a 1.0 kernel blocks on either), and its IndexNow
|
||||
# submitter is collected as an SPI event listener;
|
||||
# - the public surfaces: JSON-LD on the home page (valid, one @graph), /sitemap.xml with hreflang alternates for a
|
||||
# bilingual site, /robots.txt, /llms.txt (GEO on), the help page; for a site with neither a base URL nor a host
|
||||
# name (the catch-all default site here) the absolute URLs use the request's trusted origin
|
||||
# (http://localhost:<port> — 1.x read the Host header and guessed https) — since 2.1.0 the page JSON-LD too
|
||||
# (HeadContext.origin(): absolute @ids, a breadcrumb trail and the GEO SearchAction, none of which 2.0.0 had there);
|
||||
# - llms.txt's Last-Modified advances when only geo.summary changes (2.0.0 kept it, so a crawler kept the old copy);
|
||||
# - signed in as the site owner: the settings form keeps the 1.6.0 layout (sections, help lines, Advanced,
|
||||
# the platform-off notice) and the admin fragment + dashboard card render through the renamed bean
|
||||
# (`discoverabilityAdminModel`);
|
||||
# - IndexNow, platform switch at its default (OFF): a tenant's opt-in only logs the inert WARN once, the key file
|
||||
# is 404 and nothing is sent;
|
||||
# - IndexNow, platform switch ON (second boot, local fake endpoint): an UNPUBLISHED page's old URLs are submitted
|
||||
# (1.6.0 submitted nothing), a republish submits them again, with the key and keyLocation.
|
||||
# The flush is a Spring @Scheduled method run by the HOST's scheduler, which the kernel enables unconditionally; the
|
||||
# second boot keeps automatic backups OFF, so it also proves that.
|
||||
# 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)
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp)
|
||||
# VERIFY_LOG_DIR=/dir keep copies of the host logs, the fake endpoint's log and the
|
||||
# fetched documents there (evidence)
|
||||
# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against
|
||||
# whatever runway-spi 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
|
||||
|
||||
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=Disco-Admin-2026; SITE_USER=owner; SITE_PW=Disco-Site-2026; KEY=disco-verify-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)"
|
||||
FAKE_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 jar from the build 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}}/discover-verify.XXXXXX")"
|
||||
cleanup() {
|
||||
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
|
||||
&& cp "$SCRATCH"/*.log "$SCRATCH"/*.txt "$SCRATCH"/*.xml "$SCRATCH"/*.html "$VERIFY_LOG_DIR"/ 2>/dev/null; }
|
||||
kill "${FAKE_PID:-0}" 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/discoverability" "$EXT/plugins/discoverability"
|
||||
|
||||
# Accurate JSON-LD check: exactly one <script type=application/ld+json> block (one @graph), VALID JSON, with no raw
|
||||
# angle brackets (a real </script> breakout would truncate the block or leave a bare '<'/'>').
|
||||
cat > "$SCRATCH/ldcheck.py" <<'PY'
|
||||
import re, json, sys
|
||||
html = open(sys.argv[1], encoding='utf-8', errors='replace').read()
|
||||
blocks = re.findall(r'<script type="application/ld\+json">(.*?)</script>', html, re.S)
|
||||
if len(blocks) != 1:
|
||||
sys.exit(1)
|
||||
for b in blocks:
|
||||
if '<' in b or '>' in b:
|
||||
sys.exit(1)
|
||||
json.loads(b)
|
||||
sys.exit(0)
|
||||
PY
|
||||
# Re-submits the settings form exactly as the browser would (every field with its current value; a checkbox only when
|
||||
# checked), with KEY=VALUE overrides — prints the urlencoded body. A partial POST would switch unchecked flags off.
|
||||
cat > "$SCRATCH/resave.py" <<'PY'
|
||||
import html.parser, sys, urllib.parse
|
||||
class F(html.parser.HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(); self.inform = False; self.fields = []; self.select = None; self.area = None
|
||||
def handle_starttag(self, tag, attrs):
|
||||
a = dict(attrs)
|
||||
if tag == 'form' and a.get('id') == 'st-form': self.inform = True
|
||||
if not self.inform: return
|
||||
if tag == 'input' and a.get('name'):
|
||||
t = (a.get('type') or 'text').lower()
|
||||
if t in ('checkbox', 'radio'):
|
||||
if 'checked' in a: self.fields.append([a['name'], a.get('value') or 'on'])
|
||||
elif t not in ('submit', 'button', 'file'):
|
||||
self.fields.append([a['name'], a.get('value') or ''])
|
||||
elif tag == 'select' and a.get('name'): self.select = [a['name'], None]
|
||||
elif tag == 'option' and self.select is not None and ('selected' in a or self.select[1] is None):
|
||||
if 'selected' in a or self.select[1] is None: self.select[1] = a.get('value', '')
|
||||
elif tag == 'textarea' and a.get('name'): self.area = [a['name'], '']
|
||||
def handle_data(self, d):
|
||||
if self.area is not None: self.area[1] += d
|
||||
def handle_endtag(self, tag):
|
||||
if tag == 'form' and self.inform: self.inform = False
|
||||
if tag == 'select' and self.select is not None: self.fields.append([self.select[0], self.select[1] or '']); self.select = None
|
||||
if tag == 'textarea' and self.area is not None: self.fields.append(self.area); self.area = None
|
||||
f = F(); f.feed(open(sys.argv[1], encoding='utf-8').read())
|
||||
over = dict(kv.split('=', 1) for kv in sys.argv[2:])
|
||||
print(urllib.parse.urlencode([(k, over.get(k, v)) for k, v in f.fields]))
|
||||
PY
|
||||
# A local IndexNow endpoint: records every POST body, answers 200.
|
||||
cat > "$SCRATCH/fake_indexnow.py" <<'PY'
|
||||
import http.server, sys
|
||||
out = sys.argv[2]
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
body = self.rfile.read(int(self.headers.get('Content-Length', 0))).decode('utf-8', 'replace')
|
||||
with open(out, 'a') as f:
|
||||
f.write(body + '\n')
|
||||
self.send_response(200); self.end_headers()
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
http.server.HTTPServer(('127.0.0.1', int(sys.argv[1])), H).serve_forever()
|
||||
PY
|
||||
|
||||
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
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
# The host reads spring.config.import: optional:file:external/application.yml RELATIVE to cwd, so run with cwd=root.
|
||||
boot() { local log="$1"; shift; ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" \
|
||||
--runway.storage.external="$EXT" "$@" ) >"$log" 2>&1 & PID=$!; }
|
||||
stop() { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; }
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
|
||||
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 fixture: the wizard's default site made bilingual (en + es; About also at /es/acerca), GEO on, an
|
||||
# Organization, and the tenant's IndexNow opt-in with a key. Boot A: NO base URL and NO host name — the site is
|
||||
# reached as the platform's catch-all default — so the host has no base to offer and the origin fallback runs.
|
||||
# (A site with a host name gets https://<host> from the host as its base, exactly as under 1.x.)
|
||||
S="$EXT/sites/default"
|
||||
[ -f "$S/site.yml" ] || { echo "the wizard did not seed $S"; exit 1; }
|
||||
perl -0pi -e 's/\nhosts:\n- "localhost"\n/\nhosts: []\n/' "$S/site.yml"
|
||||
perl -0pi -e 's/\nlocales:\n- "en"\n/\nlocales:\n- "en"\n- "es"\n/' "$S/site.yml"
|
||||
perl -0pi -e 's/\n en: About\n/\n en: About\n es: Acerca\n/' "$S/templates/about.meta.yml"
|
||||
printf 'locales: [en, es]\nlocalizedPaths:\n es: /acerca\n' >> "$S/templates/about.meta.yml"
|
||||
mkdir -p "$S/plugins"
|
||||
cat > "$S/plugins/discoverability.yml" <<YML
|
||||
org.name: Acme Corp
|
||||
org.sameas:
|
||||
- https://social.example/acme
|
||||
geo.enabled: true
|
||||
geo.summary: We build things and write about it.
|
||||
search.url: /search
|
||||
indexnow.enabled: true
|
||||
indexnow.key: $KEY
|
||||
YML
|
||||
|
||||
echo "[verify] booting host (ACTIVE, IndexNow platform switch at its default: OFF) ..."
|
||||
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"
|
||||
|
||||
echo "== plugin load (SPI 1.0.0 contract) =="
|
||||
ck "plugin registered (1 registered, 0 blocked)" "grep -qE 'plugins: 1 registered, 0 blocked' '$LOG'"
|
||||
ck "not blocked / quarantined" "! grep -qE \"plugin 'discoverability' is blocked|plugin-quarantine\" '$LOG'"
|
||||
# The kernel's linkage and surface findings in every wording it has logged them ("linkage scan: <reason>", "uses
|
||||
# host internals", …): a grep for one wording alone could never fail on a kernel that logs another.
|
||||
LINKAGE="plugin 'discoverability' (uses host internals|linkage scan)|uses host internals"
|
||||
SURFACE="plugin 'discoverability'.*(allowed until Runway 1.0|bean name|may not contribute)"
|
||||
ck "ZERO host-linkage findings" "! grep -qE \"$LINKAGE\" '$LOG'"
|
||||
ck "ZERO bean-name/surface findings" "! grep -qE \"$SURFACE\" '$LOG'"
|
||||
ck "IndexNow collected as an SPI listener (1 consumer)" "grep -q 'SPI event listeners: 0 source-phase, 1 consumer-phase' '$LOG'"
|
||||
ck "no startup WARN/ERROR names the plugin" "! sed -n '1,/Started RunwayApplication/p' '$LOG' | grep -E ' (WARN|ERROR) ' | grep -qi 'discover'"
|
||||
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
|
||||
|
||||
echo "== SEO+ : structured data on the public home page =="
|
||||
curl -s "$BASE/" > "$SCRATCH/home.html"
|
||||
ck "JSON-LD script present" "grep -q 'application/ld+json' '$SCRATCH/home.html'"
|
||||
ck "WebSite + WebPage emitted" "grep -q '\"@type\":\"WebSite\"' '$SCRATCH/home.html' && grep -q '\"@type\":\"WebPage\"' '$SCRATCH/home.html'"
|
||||
ck "Organization from config" "grep -q '\"@type\":\"Organization\"' '$SCRATCH/home.html' && grep -q 'Acme Corp' '$SCRATCH/home.html'"
|
||||
ck "ONE JSON-LD block, valid, no raw <>" "python3 -I '$SCRATCH/ldcheck.py' '$SCRATCH/home.html'"
|
||||
# No base URL and no host name: the graph is anchored on HeadContext.origin() (2.1.0) — 2.0.0 emitted "/#website".
|
||||
ck "host-less JSON-LD is absolute at the trusted origin" "grep -q '\"@id\":\"$BASE/#website\"' '$SCRATCH/home.html' && grep -q '\"@id\":\"$BASE/#webpage\"' '$SCRATCH/home.html' && ! grep -q '\"@id\":\"/' '$SCRATCH/home.html'"
|
||||
ck "…and carries the GEO SearchAction (none in 2.0.0)" "grep -q '\"urlTemplate\":\"$BASE/search?q={search_term_string}\"' '$SCRATCH/home.html'"
|
||||
curl -s "$BASE/about" > "$SCRATCH/about.html"
|
||||
ck "…a deep page gains its absolute breadcrumb trail" "grep -q '\"@type\":\"BreadcrumbList\"' '$SCRATCH/about.html' && grep -q '\"item\":\"$BASE/about\"' '$SCRATCH/about.html' && python3 -I '$SCRATCH/ldcheck.py' '$SCRATCH/about.html'"
|
||||
|
||||
echo "== SEO+ : /sitemap.xml over the host's listing (no base URL, no host name: the trusted origin) =="
|
||||
ck "sitemap -> 200 application/xml" "curl -s -D - -o '$SCRATCH/sitemap.xml' '$BASE/sitemap.xml' | grep -qi '^content-type: application/xml'"
|
||||
ck "lists the pages at the request's origin (http, port kept)" "grep -q '<loc>$BASE/about</loc>' '$SCRATCH/sitemap.xml' && grep -q '<loc>$BASE/</loc>' '$SCRATCH/sitemap.xml'"
|
||||
ck "never a guessed https://" "! grep -q 'https://localhost' '$SCRATCH/sitemap.xml'"
|
||||
ck "the Spanish address and its hreflang alternates" "grep -q '<loc>$BASE/es/acerca</loc>' '$SCRATCH/sitemap.xml' && grep -q 'hreflang=\"es\" href=\"$BASE/es/acerca\"' '$SCRATCH/sitemap.xml' && grep -q 'hreflang=\"x-default\" href=\"$BASE/about\"' '$SCRATCH/sitemap.xml'"
|
||||
ck "every item carries a <lastmod>" "[ \"\$(grep -c '<lastmod>' '$SCRATCH/sitemap.xml')\" = \"\$(grep -c '<loc>' '$SCRATCH/sitemap.xml')\" ]"
|
||||
LM="$(curl -s -D - -o /dev/null "$BASE/sitemap.xml" | sed -n 's/^[Ll]ast-[Mm]odified: //p' | tr -d '\r')"
|
||||
ck "conditional GET: 304 for an unchanged sitemap" "[ -n '$LM' ] && [ \"\$(code -H 'If-Modified-Since: $LM' '$BASE/sitemap.xml')\" = 304 ]"
|
||||
ck "a small site's shard path is 404" "[ \"\$(code '$BASE/sitemap-1.xml')\" = 404 ]"
|
||||
|
||||
echo "== /robots.txt and GEO /llms.txt =="
|
||||
curl -s "$BASE/robots.txt" > "$SCRATCH/robots.txt"
|
||||
ck "robots.txt: general group + AI group + Sitemap line at the origin" "grep -q '^User-agent: \\*' '$SCRATCH/robots.txt' && grep -q '^User-agent: GPTBot' '$SCRATCH/robots.txt' && grep -qx 'Sitemap: $BASE/sitemap.xml' '$SCRATCH/robots.txt'"
|
||||
curl -s -o "$SCRATCH/llms.txt" "$BASE/llms.txt"
|
||||
ck "llms.txt served (H1 + summary)" "head -1 '$SCRATCH/llms.txt' | grep -q '^# ' && grep -q 'We build things' '$SCRATCH/llms.txt'"
|
||||
ck "llms.txt lists the pages at the origin" "grep -q '## Pages' '$SCRATCH/llms.txt' && grep -q '($BASE/about)' '$SCRATCH/llms.txt'"
|
||||
LLM_LM="$(curl -s -D - -o /dev/null "$BASE/llms.txt" | sed -n 's/^[Ll]ast-[Mm]odified: //p' | tr -d '\r')"
|
||||
ck "llms.txt: 304 while nothing changed" "[ -n '$LLM_LM' ] && [ \"\$(code -H 'If-Modified-Since: $LLM_LM' '$BASE/llms.txt')\" = 304 ]"
|
||||
ck "GEO answer-schema (Speakable)" "grep -q 'SpeakableSpecification' '$SCRATCH/home.html'"
|
||||
ck "help page served" "[ \"\$(code '$BASE/__plugin/discoverability/static/discoverability-help.html')\" = 200 ]"
|
||||
|
||||
echo "== console: settings form layout (1.6.0), admin fragment and dashboard card (renamed bean) =="
|
||||
JAR_C="$SCRATCH/cookies.txt"
|
||||
c() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; }
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
login_site() { rm -f "$JAR_C"; local t; t="$(c "$BASE/login" | token)"; c -o /dev/null -X POST "$BASE/login" \
|
||||
--data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" --data-urlencode "_csrf=$t"; }
|
||||
page_action() { local t; t="$(c "$BASE/__admin/pages" | token)"; c -o /dev/null -w '%{http_code}' -X POST \
|
||||
"$BASE/__admin/pages/$1/$2" --data-urlencode "_csrf=$t"; }
|
||||
login_site
|
||||
c "$BASE/__admin/plugins/discoverability/settings" > "$SCRATCH/settings.html"
|
||||
ck "settings page with the six sections" "grep -q 'Structured data for search engines' '$SCRATCH/settings.html' && grep -q 'Notify search engines of changes (IndexNow)' '$SCRATCH/settings.html'"
|
||||
ck "…help lines and an Advanced part" "grep -q 'Google does not' '$SCRATCH/settings.html' && grep -qi 'advanced' '$SCRATCH/settings.html'"
|
||||
ck "admin fragment rendered by discoverabilityAdminModel (GEO on, page count)" "grep -q 'id=\"da-geo\">on<' '$SCRATCH/settings.html' && grep -qE 'id=\"da-pages\">[1-9][0-9]*<' '$SCRATCH/settings.html'"
|
||||
ck "…and its Per-page types check (2.2.0)" "grep -q 'Per-page types check' '$SCRATCH/settings.html'"
|
||||
c "$BASE/__admin/pages/about/edit" > "$SCRATCH/editor.html"
|
||||
ck "the page editor says what the page is described as (2.2.0)" "grep -q 'Structured data: this page is a' '$SCRATCH/editor.html'"
|
||||
c "$BASE/__admin" > "$SCRATCH/dashboard.html"
|
||||
ck "dashboard card rendered (page count, GEO on)" "grep -qE 'id=\"dc-pages\">[1-9][0-9]*<' '$SCRATCH/dashboard.html' && grep -q 'id=\"dc-geo\">on<' '$SCRATCH/dashboard.html'"
|
||||
ck "no template error in the log" "! grep -qiE 'TemplateProcessingException|SpelEvaluationException' '$LOG'"
|
||||
|
||||
echo "== llms.txt's validator folds the summary (2.1.0) =="
|
||||
# Save the form unchanged except geo.summary (the console path: the kernel caches per-site settings and evicts on save,
|
||||
# so a hand edit of the YAML would not be seen). 2.0.0 kept Last-Modified, so a crawler kept the old summary.
|
||||
sleep 2 # HTTP dates are whole seconds: the advance must land in a later second than the validator it replaces
|
||||
python3 -I "$SCRATCH/resave.py" "$SCRATCH/settings.html" "geo.summary=We build better things now." > "$SCRATCH/resave.txt"
|
||||
RS="$(c -o /dev/null -w '%{http_code}' -X POST "$BASE/__admin/plugins/discoverability/settings" \
|
||||
-H 'Content-Type: application/x-www-form-urlencoded' --data-binary "@$SCRATCH/resave.txt")"
|
||||
ck "settings saved through the console (summary only)" "[ '$RS' = 302 ] || [ '$RS' = 303 ]"
|
||||
ck "…and nothing else changed in the stored file" "grep -q '^geo.enabled: true' '$S/plugins/discoverability.yml' && grep -q 'Acme Corp' '$S/plugins/discoverability.yml' && grep -q 'We build better things now.' '$S/plugins/discoverability.yml'"
|
||||
ck "llms.txt: the old validator now gets a 200 with the new summary" \
|
||||
"[ \"\$(code -H 'If-Modified-Since: $LLM_LM' '$BASE/llms.txt')\" = 200 ] && curl -s '$BASE/llms.txt' | grep -q '^> We build better things now.'"
|
||||
LLM_LM2="$(curl -s -D - -o /dev/null "$BASE/llms.txt" | sed -n 's/^[Ll]ast-[Mm]odified: //p' | tr -d '\r')"
|
||||
ck "…and its new validator revalidates to 304" "[ -n '$LLM_LM2' ] && [ '$LLM_LM2' != '$LLM_LM' ] && [ \"\$(code -H 'If-Modified-Since: $LLM_LM2' '$BASE/llms.txt')\" = 304 ]"
|
||||
|
||||
echo "== IndexNow, platform switch OFF (the default): inert =="
|
||||
ck "key file is 404" "[ \"\$(code '$BASE/indexnow-key.txt')\" = 404 ]"
|
||||
CODE="$(page_action about disable)"
|
||||
ck "unpublish via the console (redirect)" "[ '$CODE' = 302 ] || [ '$CODE' = 303 ]"
|
||||
ck "the inert WARN, once, naming the site" "[ \"\$(grep -c \"site 'default' has IndexNow enabled, but the platform has not permitted it\" '$LOG')\" = 1 ]"
|
||||
ck "nothing attempted" "! grep -q 'IndexNow submission' '$LOG'"
|
||||
page_action about enable >/dev/null
|
||||
stop
|
||||
|
||||
echo "[verify] booting host (ACTIVE, IndexNow ON, fake endpoint :$FAKE_PORT, 2 s batches, base URL configured) ..."
|
||||
perl -pi -e "s#^baseUrl: .*#baseUrl: \"$BASE\"#" "$S/site.yml"
|
||||
python3 -I "$SCRATCH/fake_indexnow.py" "$FAKE_PORT" "$SCRATCH/indexnow-posts.txt" & FAKE_PID=$!
|
||||
boot "$SCRATCH/active2.log" --runway.plugin.discoverability.indexnow.enabled=true \
|
||||
--runway.plugin.discoverability.indexnow.endpoint="http://127.0.0.1:$FAKE_PORT/indexnow" \
|
||||
--runway.plugin.discoverability.indexnow.batch-seconds=2
|
||||
wait_for "$SCRATCH/active2.log" "Started RunwayApplication" 90 || { echo "second ACTIVE boot failed"; tail -20 "$SCRATCH/active2.log"; exit 1; }
|
||||
LOG2="$SCRATCH/active2.log"
|
||||
echo "== IndexNow, platform switch ON =="
|
||||
ck "still 1 registered, 0 blocked, zero findings" "grep -q 'plugins: 1 registered, 0 blocked' '$LOG2' && ! grep -qE \"$LINKAGE\" '$LOG2' && ! grep -qE \"$SURFACE\" '$LOG2'"
|
||||
ck "app-level settings bound: key file served" "curl -s '$BASE/indexnow-key.txt' | grep -qx '$KEY'"
|
||||
# With a base URL the graph is anchored on that base (never the request origin), with the GEO SearchAction.
|
||||
curl -s "$BASE/" > "$SCRATCH/home-based.html"
|
||||
ck "GEO SearchAction on the anchored graph" "grep -q '\"potentialAction\":{\"@type\":\"SearchAction\"' '$SCRATCH/home-based.html' && grep -q '\"@id\":\"$BASE/#website\"' '$SCRATCH/home-based.html' && python3 -I '$SCRATCH/ldcheck.py' '$SCRATCH/home-based.html'"
|
||||
curl -s -o /dev/null "$BASE/sitemap.xml" # the host lists the site once, so a change can report previous URLs
|
||||
login_site
|
||||
page_action about disable >/dev/null
|
||||
for _ in $(seq 1 15); do [ -s "$SCRATCH/indexnow-posts.txt" ] && break; sleep 1; done
|
||||
echo " fake endpoint received after the unpublish:"; sed 's/^/ /' "$SCRATCH/indexnow-posts.txt" 2>/dev/null
|
||||
ck "an UNPUBLISHED page's old URLs are submitted (1.6.0 sent nothing)" \
|
||||
"grep -qF '\"urlList\":[\"$BASE/about\",\"$BASE/es/acerca\"]' '$SCRATCH/indexnow-posts.txt'"
|
||||
ck "…with the key and the fixed keyLocation" "grep -qF '\"key\":\"$KEY\",\"keyLocation\":\"$BASE/indexnow-key.txt\"' '$SCRATCH/indexnow-posts.txt'"
|
||||
cp "$SCRATCH/indexnow-posts.txt" "$SCRATCH/indexnow-posts-unpublish.txt"
|
||||
: > "$SCRATCH/indexnow-posts.txt"
|
||||
page_action about enable >/dev/null
|
||||
for _ in $(seq 1 15); do [ -s "$SCRATCH/indexnow-posts.txt" ] && break; sleep 1; done
|
||||
sleep 3 # one more batch period: a second submission for the same change would land now
|
||||
echo " fake endpoint received after the republish:"; sed 's/^/ /' "$SCRATCH/indexnow-posts.txt" 2>/dev/null
|
||||
ck "a republish submits the page's URLs again" "grep -qF '\"urlList\":[\"$BASE/about\",\"$BASE/es/acerca\"]' '$SCRATCH/indexnow-posts.txt'"
|
||||
ck "one submission per batch (not one per URL)" "[ \"\$(grep -c urlList '$SCRATCH/indexnow-posts.txt')\" = 1 ]"
|
||||
ck "no inert WARN while permitted" "! grep -q 'has not permitted it' '$LOG2'"
|
||||
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG2' | grep -qi 'discover'"
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,110 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code Article} (or {@code BlogPosting} — the subtype the entry declares as its
|
||||
* {@code type}) from a post's {@code content.schema} entry: {@code headline} (falls back to the page title),
|
||||
* description, image, {@code author} (a {@code Person}), {@code datePublished}/{@code dateModified},
|
||||
* {@code publisher}→Organization. The declared type <b>is</b> the page's own type (since 2.2.0): the properties go on
|
||||
* the page's {@code #webpage} node, which takes the declared {@code @type}, instead of a second node beside it.
|
||||
*
|
||||
* <h2>Where author and dates come from, and why the order matters</h2>
|
||||
* Each of {@code author}, {@code datePublished} and {@code dateModified} is taken from <b>the page's own
|
||||
* provenance first</b> ({@link mx.quest.runway.spi.model.PageMeta#provenance()}), and only then from the
|
||||
* hand-written {@code content.schema} block.
|
||||
*
|
||||
* <p>That order is the whole point of the change. {@code content.schema} matches by exact path or {@code *}
|
||||
* prefix, so a blog is typed by a single {@code /blog/*} block shared by <b>every</b> entry. When these fields
|
||||
* could only come from there, a site had exactly two honest options: omit dates and authorship entirely, or
|
||||
* assert <i>one</i> date and <i>one</i> author identically on every post — a statement that is false of nearly
|
||||
* every page it appears on. Asserting content that is not true of the page is precisely what structured-data
|
||||
* policy prohibits, so the configuration-only design pushed a conscientious operator toward a violation.
|
||||
*
|
||||
* <p>Per-item provenance removes the dilemma: a source that knows its own publication date (a blog entry does)
|
||||
* now supplies it, and the shared block is left to cover only what is genuinely shared. The config path is kept
|
||||
* as a fallback so existing sites keep working unchanged, and so a source that has no provenance can still be
|
||||
* annotated by hand.
|
||||
*/
|
||||
final class ArticleSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Article";
|
||||
}
|
||||
|
||||
/** Every token is a page type: an article (or blog post, or news article) is what the page is. */
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Nothing as a separate node: the article is the page itself ({@link #describePage}). */
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the article's properties to the page's own node: {@code headline} in place of {@code name}, and
|
||||
* author, dates and image. Without a headline (no page title and none configured) the page keeps its name.
|
||||
*/
|
||||
@Override
|
||||
public void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
Map<String, Object> fields = fields(ctx, sc);
|
||||
if (fields.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
page.remove("name");
|
||||
page.putAll(fields);
|
||||
}
|
||||
|
||||
/** The article's own properties, or an empty map when it has no headline. */
|
||||
private static Map<String, Object> fields(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String headline = Schemas.str(cfg, "headline", ctx.page().title());
|
||||
if (headline == null || headline.isBlank()) {
|
||||
return Map.of(); // no headline — leave the page node as it is
|
||||
}
|
||||
Map<String, Object> article = new LinkedHashMap<>();
|
||||
Ld.put(article, "headline", headline);
|
||||
Ld.put(article, "description", Schemas.str(cfg, "description", ctx.page().description()));
|
||||
Ld.putList(article, "image", Schemas.absolute(Schemas.strings(cfg, "image"), sc.base()));
|
||||
// Per-item provenance WINS over the shared content.schema block — see the class contract.
|
||||
mx.quest.runway.spi.model.Provenance prov = ctx.page().provenance();
|
||||
Ld.put(article, "datePublished", isoDate(prov.publishedAt(), Schemas.str(cfg, "datePublished")));
|
||||
Ld.put(article, "dateModified", isoDate(prov.updatedAt(), Schemas.str(cfg, "dateModified")));
|
||||
Ld.put(article, "inLanguage", ctx.locale().toLanguageTag());
|
||||
String author = prov.author() != null ? prov.author() : Schemas.str(cfg, "author");
|
||||
if (author != null) {
|
||||
Map<String, Object> person = new LinkedHashMap<>();
|
||||
person.put("@type", "Person");
|
||||
person.put("name", author);
|
||||
article.put("author", person);
|
||||
}
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(article, "publisher", sc.organizationId());
|
||||
}
|
||||
return article;
|
||||
}
|
||||
|
||||
/**
|
||||
* The item's own instant as a schema.org date, else the configured fallback.
|
||||
*
|
||||
* <p>Rendered as {@code yyyy-MM-dd} (UTC) rather than a full timestamp: schema.org accepts either, and a
|
||||
* publication date is an editorial fact at day granularity. Emitting a second-precision instant would imply
|
||||
* a precision the platform does not actually have — {@code dateModified} in particular is derived from a
|
||||
* file mtime, which moves for reasons that are not editorial.
|
||||
*/
|
||||
private static String isoDate(java.time.Instant instant, String fallback) {
|
||||
if (instant == null) {
|
||||
return fallback;
|
||||
}
|
||||
return java.time.format.DateTimeFormatter.ISO_LOCAL_DATE
|
||||
.format(instant.atZone(java.time.ZoneOffset.UTC));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code ItemList} for a collection / index page (a coffee listing, a services or blog index)
|
||||
* from an {@code items:} list of {@code {name, url}}. Without it a listing page is invisible <em>as a list</em> to
|
||||
* crawlers (no carousel eligibility) and answer engines. Registered under both {@code ItemList} and
|
||||
* {@code CollectionPage}; the node is {@code @id}'d and {@code mainEntityOfPage}-linked to the page. Declared as
|
||||
* {@code CollectionPage} it also makes the page itself a {@code CollectionPage} whose {@code mainEntity} is the list
|
||||
* (since 2.2.0; until then the page stayed the site default and only the list was emitted).
|
||||
*/
|
||||
final class CollectionSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "ItemList";
|
||||
}
|
||||
|
||||
/** {@code CollectionPage} names what the page is; {@code ItemList} only adds the list. */
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return "CollectionPage".equals(token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
for (Map<String, Object> list : nodes(ctx, sc)) {
|
||||
graph.add(list);
|
||||
Ld.ref(page, "mainEntity", (String) list.get("@id"));
|
||||
}
|
||||
}
|
||||
|
||||
/** No item with a {@code url}: no list is published (a CollectionPage is still a CollectionPage). */
|
||||
@Override
|
||||
public Gap gap(String token, Map<String, Object> block) {
|
||||
for (Map<String, Object> member : Schemas.maps(block, "items")) {
|
||||
if (Schemas.str(member, "url") != null) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return new Gap("discover.gap.items", "{0} has no item with a url:, so no list is published.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
List<Map<String, Object>> members = Schemas.maps(sc.pageConfig(), "items");
|
||||
List<Map<String, Object>> elements = new ArrayList<>();
|
||||
int position = 1;
|
||||
for (Map<String, Object> member : members) {
|
||||
String url = Schemas.str(member, "url");
|
||||
if (url == null) {
|
||||
continue; // a list item without a target URL is not useful
|
||||
}
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("@type", "ListItem");
|
||||
item.put("position", position++);
|
||||
Ld.put(item, "name", Schemas.str(member, "name"));
|
||||
item.put("url", url.startsWith("/") ? sc.base() + url : url);
|
||||
elements.add(item);
|
||||
}
|
||||
if (elements.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, Object> list = Ld.node("ItemList", sc.canonical() + "#itemlist");
|
||||
Ld.ref(list, "mainEntityOfPage", sc.webpageId());
|
||||
list.put("itemListElement", elements);
|
||||
return List.of(list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
|
||||
/**
|
||||
* Conditional-GET support for the crawl surfaces (sitemap.xml, llms.txt): crawlers hit these often, and the
|
||||
* content only changes when the site's content does — so both endpoints emit {@code Last-Modified} with
|
||||
* {@code Cache-Control: no-cache} (cache it, but REVALIDATE every time), and answer {@code If-Modified-Since}
|
||||
* with an empty {@code 304} instead of re-serializing the whole document.
|
||||
*
|
||||
* <p><b>The validator must reflect MEMBERSHIP, not just member mtimes.</b> These documents are lists: deleting
|
||||
* or unpublishing an item only <em>removes</em> an {@code updatedAt} from the pool, so a naive
|
||||
* {@code max(updatedAt)} stays the same (or moves backward) and a revalidating crawler would keep its cached
|
||||
* copy — still advertising the removed URL — indefinitely. The validator therefore combines a per-site
|
||||
* <b>fingerprint</b> of the document-shaping facts (item identity, paths, {@code updatedAt}, {@code noindex},
|
||||
* and the host-computed URLs: every locale's address and canonical, and the {@code x-default}) — plus, per
|
||||
* document, the <b>document-level facts</b> it prints that no item carries (llms.txt's site name and
|
||||
* {@code geo.summary}) — with a <b>monotonic</b> emitted instant: while the fingerprint is unchanged the emitted value is stable; any
|
||||
* change advances it to {@code max(newest updatedAt, previous)} — or to <em>now</em> when the change carries no
|
||||
* newer mtime (a removal, an addition with a null {@code updatedAt}). A future-dated {@code updatedAt} (clock
|
||||
* skew, a touched file) is clamped to now so it cannot pin the validator and mask later real changes.
|
||||
*
|
||||
* <p>State is in-memory only. On restart the first request per site seeds the emitted instant with <em>now</em>
|
||||
* — deliberately: seeding with the content mtime would resurrect the removal blind spot for any membership
|
||||
* change that happened around the restart. The cost is one full {@code 200} per crawler after a restart; the
|
||||
* value then stabilizes until content actually changes. HTTP dates are second-granular, so instants are
|
||||
* truncated before comparing.
|
||||
*/
|
||||
final class CrawlConditional {
|
||||
|
||||
private static final DateTimeFormatter HTTP_DATE =
|
||||
DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC);
|
||||
|
||||
/** What the site's crawl documents last looked like (fingerprint) and the validator emitted for it. */
|
||||
private record Validator(String fingerprint, Instant emitted) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validator state per site <b>and document</b>. Until 2.1.0 the sitemap and llms.txt shared one record per site
|
||||
* (both derive from the same catalog list); llms.txt now also folds facts the sitemap does not print, and two
|
||||
* documents with different fingerprints sharing one record would advance each other's validator on every
|
||||
* alternate request.
|
||||
*/
|
||||
private static final ConcurrentMap<String, Validator> STATE = new ConcurrentHashMap<>();
|
||||
|
||||
/** The sitemap's document name — its validator folds the catalog only. */
|
||||
static final String SITEMAP = "sitemap.xml";
|
||||
/** The llms.txt document name — its validator also folds the site name and summary it prints. */
|
||||
static final String LLMS = "llms.txt";
|
||||
|
||||
/** The time source — a test hook ({@link #reset} restores it); production always uses the system clock. */
|
||||
static java.util.function.Supplier<Instant> clock = Instant::now;
|
||||
|
||||
private CrawlConditional() {
|
||||
}
|
||||
|
||||
/** Test hook: forget all per-site validator state (simulates a restart) and restore the system clock. */
|
||||
static void reset() {
|
||||
STATE.clear();
|
||||
clock = Instant::now;
|
||||
}
|
||||
|
||||
/** The sitemap's validator: {@link #lastModified(String, String, List, List)} with no document-level facts. */
|
||||
static Instant lastModified(String siteId, List<CatalogEntry> items) {
|
||||
return lastModified(siteId, SITEMAP, items, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code Last-Modified} validator for {@code siteId}'s crawl document {@code document} built from
|
||||
* {@code items} and the document-level {@code facts} it prints besides them (in a fixed order; a {@code null}
|
||||
* fact folds as empty) — membership-aware and monotonic per the class contract (never in the future, never moves
|
||||
* backward). A change to a fact advances the validator to <em>now</em>: it carries no mtime of its own.
|
||||
*/
|
||||
static Instant lastModified(String siteId, String document, List<CatalogEntry> items, List<String> facts) {
|
||||
Instant now = clock.get().truncatedTo(ChronoUnit.SECONDS);
|
||||
Instant newest = newestUpdatedAt(items, now);
|
||||
String fingerprint = fingerprint(items, facts);
|
||||
// A printable separator ('|' is never part of a site id), never a control character.
|
||||
Validator computed = STATE.compute(siteId + '|' + document, (id, prev) -> {
|
||||
if (prev == null) {
|
||||
return new Validator(fingerprint, now); // restart seed: now, per the class contract
|
||||
}
|
||||
if (prev.fingerprint().equals(fingerprint)) {
|
||||
return prev; // unchanged document keeps its validator — this is what makes 304s possible
|
||||
}
|
||||
Instant advanced = (newest != null && newest.isAfter(prev.emitted())) ? newest : now;
|
||||
if (!advanced.isAfter(prev.emitted())) {
|
||||
// Cannot advance within HTTP-date granularity (a change in the same second as the previous
|
||||
// advance, or a backward clock). Keep the OLD state — fingerprint included — so a later
|
||||
// request re-detects the change and advances once the clock has moved; committing the new
|
||||
// fingerprint now would absorb the change at the old validator forever.
|
||||
return prev;
|
||||
}
|
||||
return new Validator(fingerprint, advanced);
|
||||
});
|
||||
return computed.emitted();
|
||||
}
|
||||
|
||||
/** The newest {@code updatedAt} across {@code items} clamped to {@code now}, or null when none carries one. */
|
||||
private static Instant newestUpdatedAt(List<CatalogEntry> items, Instant now) {
|
||||
Instant newest = null;
|
||||
for (CatalogEntry item : items) {
|
||||
Instant updated = item.ref().updatedAt();
|
||||
if (updated != null && (newest == null || updated.isAfter(newest))) {
|
||||
newest = updated;
|
||||
}
|
||||
}
|
||||
if (newest == null) {
|
||||
return null;
|
||||
}
|
||||
newest = newest.truncatedTo(ChronoUnit.SECONDS);
|
||||
return newest.isAfter(now) ? now : newest; // a future mtime must not pin the validator
|
||||
}
|
||||
|
||||
/**
|
||||
* A digest of the document-shaping facts: identity, paths, mtime, indexability, and the URLs the host computed —
|
||||
* order-sensitive. The URLs are folded in because they change without any item changing: a site that starts
|
||||
* serving another locale gains alternates, and a canonical override moves an item in or out of the sitemap.
|
||||
* (Until 2.0.0 they were not, so a crawler revalidating after such a change kept its old copy.) The document-level
|
||||
* facts come first, each length-prefixed so no fact can shift characters into the next (until 2.1.0 there were
|
||||
* none, so editing the site name or {@code geo.summary} changed llms.txt without advancing its validator).
|
||||
*/
|
||||
private static String fingerprint(List<CatalogEntry> items, List<String> facts) {
|
||||
MessageDigest digest;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException("SHA-256 unavailable", impossible);
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(128);
|
||||
sb.append("facts#").append(facts.size()).append(';');
|
||||
for (String fact : facts) {
|
||||
String value = fact == null ? "" : fact;
|
||||
sb.append(value.length()).append(':').append(value);
|
||||
}
|
||||
sb.append('\n');
|
||||
digest.update(sb.toString().getBytes(StandardCharsets.UTF_8));
|
||||
for (CatalogEntry item : items) {
|
||||
sb.setLength(0);
|
||||
sb.append(item.compositeId()).append('|').append(item.ref().path()).append('|')
|
||||
.append(item.ref().localizedPaths()).append('|').append(item.ref().updatedAt()).append('|')
|
||||
.append(item.ref().noindex()).append('|').append(item.xDefaultPath());
|
||||
for (LocalizedUrl url : item.urls()) {
|
||||
sb.append('|').append(url.locale().toLanguageTag()).append('=').append(url.path())
|
||||
.append('>').append(url.canonical());
|
||||
}
|
||||
sb.append('\n');
|
||||
digest.update(sb.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return java.util.HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
|
||||
/** Whether the request's {@code If-Modified-Since} already covers {@code lastModified} (null ⇒ no). */
|
||||
static boolean notModified(RouteRequest req, Instant lastModified) {
|
||||
if (lastModified == null) {
|
||||
return false;
|
||||
}
|
||||
String header = header(req, "If-Modified-Since");
|
||||
if (header == null || header.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Instant since = Instant.from(HTTP_DATE.parse(header.trim()));
|
||||
return !lastModified.truncatedTo(ChronoUnit.SECONDS).isAfter(since);
|
||||
} catch (RuntimeException unparseable) {
|
||||
return false; // an invalid date = an unconditional request
|
||||
}
|
||||
}
|
||||
|
||||
/** The empty {@code 304} carrying the same validator/caching headers as the {@code 200} would. */
|
||||
static RouteResponse notModifiedResponse(Instant lastModified) {
|
||||
return new RouteResponse(304, cacheHeaders(lastModified, null), new byte[0]);
|
||||
}
|
||||
|
||||
/** The response headers for a fresh {@code 200}: content type + validator + revalidate-always caching. */
|
||||
static Map<String, String> cacheHeaders(Instant lastModified, String contentType) {
|
||||
Map<String, String> headers = new java.util.LinkedHashMap<>();
|
||||
if (contentType != null) {
|
||||
headers.put("Content-Type", contentType);
|
||||
}
|
||||
if (lastModified != null) {
|
||||
headers.put("Last-Modified", HTTP_DATE.format(lastModified.truncatedTo(ChronoUnit.SECONDS)));
|
||||
}
|
||||
headers.put("Cache-Control", "no-cache");
|
||||
return headers;
|
||||
}
|
||||
|
||||
private static String header(RouteRequest req, String name) {
|
||||
for (var entry : req.headers().entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(name)) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* Backs the tenant <b>dashboard card</b> and the <b>admin fragment</b> rendered below the plugin's per-tenant
|
||||
* settings form. The templates call it as {@code ${@discoverabilityAdminModel.<method>(tenantSiteId)}} (the bean
|
||||
* name carries the plugin id, as every plugin bean must) to show the plugin's live state for the current site
|
||||
* (which surfaces are on, how many items the sitemap draws from).
|
||||
*
|
||||
* <p>Read-only. A missing or malformed site id (the fragments are only rendered for a tenant, so neither happens in
|
||||
* practice) answers the defaults and a count of {@code 0} rather than failing the console page.
|
||||
*/
|
||||
public class DiscoverAdminModel {
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final ContentCatalogView catalog;
|
||||
private final Map<String, SchemaType> types;
|
||||
private final Messages messages;
|
||||
|
||||
public DiscoverAdminModel(PluginSettings settings, ContentCatalogView catalog) {
|
||||
this(settings, catalog, DiscoverabilityConfig.schemaTypes(), null);
|
||||
}
|
||||
|
||||
DiscoverAdminModel(PluginSettings settings, ContentCatalogView catalog, Map<String, SchemaType> types,
|
||||
Messages messages) {
|
||||
this.settings = settings;
|
||||
this.catalog = catalog;
|
||||
this.types = types;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* What is wrong with the site's Per-page types ({@code content.schema}), one line each, in the operator's UI
|
||||
* language; empty when nothing is. Shown below the settings form after every save.
|
||||
*
|
||||
* <h2>Why</h2>
|
||||
* A mistake there never breaks a page: unreadable YAML turns typing off, and an unknown type or a misplaced
|
||||
* {@code *} is skipped. That is the right behaviour for visitors and the wrong one for the person who typed it,
|
||||
* who until 2.2.0 had no way to see it. A block that applies but publishes nothing of its own (an
|
||||
* {@code FAQPage} with no complete question: {@link SchemaType#gap}) is listed too; an ignored second page type
|
||||
* is reported once, not also for its gaps.
|
||||
*/
|
||||
public List<String> schemaProblems(String siteId) {
|
||||
String text = SiteConfig.str(cfg(siteId), "content.schema", "");
|
||||
List<String> out = new ArrayList<>();
|
||||
String syntax = PageSchemaConfig.syntaxProblem(text);
|
||||
if (syntax != null) {
|
||||
out.add(text("discover.schema.syntax",
|
||||
"Per-page types cannot be read, so no page gets a per-page type: {0}", syntax));
|
||||
return out;
|
||||
}
|
||||
for (String pattern : PageSchemaConfig.ignoredPatterns(text)) {
|
||||
out.add(text("discover.schema.notBlock",
|
||||
"{0}: the value must be a type block (type: ...) or a list of them; ignored.", pattern));
|
||||
}
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(text);
|
||||
for (Map.Entry<String, Object> entry : patterns.entrySet()) {
|
||||
String pattern = entry.getKey();
|
||||
if (!pattern.startsWith("/")) {
|
||||
out.add(text("discover.schema.slash", "{0}: a pattern starts with / and matches page paths.",
|
||||
pattern));
|
||||
}
|
||||
int star = pattern.indexOf('*');
|
||||
if (star >= 0 && star < pattern.length() - 1) {
|
||||
out.add(text("discover.schema.star",
|
||||
"{0}: * works only at the end of a pattern; here it is matched as a character.", pattern));
|
||||
}
|
||||
int pageTypes = 0;
|
||||
for (Map<String, Object> block : PageSchemaConfig.blocks(entry.getValue())) {
|
||||
String token = Schemas.str(block, "type", "");
|
||||
if (token.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
SchemaType handler = types.get(token);
|
||||
if (handler == null) {
|
||||
out.add(text("discover.schema.unknown",
|
||||
"{0}: {1} is not a type this plugin knows; ignored.", pattern, token));
|
||||
} else if (handler.describesPage(token) && ++pageTypes > 1) {
|
||||
if (pageTypes == 2) {
|
||||
out.add(text("discover.schema.twoPageTypes",
|
||||
"{0}: more than one page type; only the first applies.", pattern));
|
||||
}
|
||||
} else {
|
||||
SchemaType.Gap gap = handler.gap(token, block);
|
||||
if (gap != null) {
|
||||
out.add(pattern + ": " + text(gap.code(), gap.fallback(), token));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private String text(String code, String fallback, Object... args) {
|
||||
return messages == null ? java.text.MessageFormat.format(fallback, args)
|
||||
: messages.console(code, fallback, args);
|
||||
}
|
||||
|
||||
public boolean jsonldEnabled(String siteId) {
|
||||
return SiteConfig.bool(cfg(siteId), "jsonld.enabled", true);
|
||||
}
|
||||
|
||||
public String jsonldType(String siteId) {
|
||||
return PageTypes.defaultType(cfg(siteId));
|
||||
}
|
||||
|
||||
public boolean sitemapEnabled(String siteId) {
|
||||
return SiteConfig.bool(cfg(siteId), "sitemap.enabled", true);
|
||||
}
|
||||
|
||||
public boolean geoEnabled(String siteId) {
|
||||
return SiteConfig.bool(cfg(siteId), "geo.enabled", false);
|
||||
}
|
||||
|
||||
public boolean orgConfigured(String siteId) {
|
||||
return !SiteConfig.str(cfg(siteId), "org.name", "").isBlank();
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of published content items the sitemap draws from — kernel pages AND plugin content alike, through
|
||||
* the same host listing the sitemap itself serves from (so this count is always truthful). Items marked
|
||||
* {@code noindex} are included, as before: the count is of the published surface.
|
||||
*/
|
||||
public long pageCount(String siteId) {
|
||||
if (siteId == null) {
|
||||
return 0L;
|
||||
}
|
||||
try {
|
||||
return catalog.entries(siteId).size();
|
||||
} catch (IllegalArgumentException malformedId) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> cfg(String siteId) {
|
||||
if (siteId == null) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return settings.site(siteId).values();
|
||||
} catch (IllegalArgumentException malformedId) {
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
|
||||
* refresh. It wires every bean EXPLICITLY (no {@code @ComponentScan}: scanning a plugin's own package across the
|
||||
* shared child classloader is fragile). The plugin package ({@code mx.quest.discover}) is deliberately OUTSIDE
|
||||
* {@code mx.quest.runway} so the host never double-scans it.
|
||||
*
|
||||
* <p>The {@link HeadContributor} and {@link EndpointContributor}s are list-collected SPIs — plain
|
||||
* {@code @Bean}s, NEVER {@code @Primary}. The head contributor is ordered AFTER the kernel's own SEO
|
||||
* ({@code @Order 100}) and icon ({@code @Order 90}) head contributors, so the plugin's structured data is
|
||||
* spliced last.
|
||||
*
|
||||
* <p><b>Links only the Runway SPI</b> (since 2.0.0). Every host service arrives by ordinary injection of an SPI
|
||||
* type: {@link PluginSettings} (this plugin's per-site settings, bound to this plugin by the jar its code was
|
||||
* loaded from), {@link ContentCatalogView} (the site's published content surface with host-computed URLs) and
|
||||
* {@link Sites}. Every bean name starts with the plugin id ({@code discoverability…}): plugins share the host's
|
||||
* bean namespace.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class DiscoverabilityConfig {
|
||||
|
||||
// --- app-level (platform) settings ----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The app-level settings, bound from {@code runway.plugin.discoverability.*}. Declared as a named {@code @Bean}
|
||||
* rather than through {@code @EnableConfigurationProperties}, which would register it under the generated name
|
||||
* {@code runway.plugin.discoverability-mx.quest.discover.DiscoverabilityProperties} — outside the plugin's bean
|
||||
* prefix.
|
||||
*/
|
||||
@Bean
|
||||
@ConfigurationProperties("runway.plugin.discoverability")
|
||||
public DiscoverabilityProperties discoverabilityProperties() {
|
||||
return new DiscoverabilityProperties();
|
||||
}
|
||||
|
||||
// --- head contributor (SEO+ and GEO in one @graph) ------------------------------------------------
|
||||
|
||||
@Bean
|
||||
@Order(150)
|
||||
public HeadContributor discoverabilityStructuredData(PluginSettings settings) {
|
||||
return new StructuredDataHead(settings, schemaTypes());
|
||||
}
|
||||
|
||||
/**
|
||||
* The content-type registry (item 5), indexed by the type token a tenant declares in {@code content.schema}.
|
||||
* Subtypes are registered under aliases that share one implementation (e.g. {@code BlogPosting}→Article).
|
||||
* Fails fast on a duplicate key so a wiring mistake never silently shadows a type.
|
||||
*/
|
||||
static Map<String, SchemaType> schemaTypes() {
|
||||
Map<String, SchemaType> types = new LinkedHashMap<>();
|
||||
register(types, new FaqPageSchema());
|
||||
register(types, new ProductSchema());
|
||||
register(types, new ArticleSchema(), "BlogPosting", "NewsArticle");
|
||||
register(types, new LocalBusinessSchema(), "CafeOrCoffeeShop");
|
||||
register(types, new ServiceSchema(), "ProfessionalService");
|
||||
register(types, new PersonSchema());
|
||||
register(types, new CollectionSchema(), "CollectionPage");
|
||||
for (String key : SimplePageType.KEYS) {
|
||||
register(types, new SimplePageType(key));
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
private static void register(Map<String, SchemaType> types, SchemaType type, String... aliases) {
|
||||
put(types, type.key(), type);
|
||||
for (String alias : aliases) {
|
||||
put(types, alias, type);
|
||||
}
|
||||
}
|
||||
|
||||
private static void put(Map<String, SchemaType> types, String key, SchemaType type) {
|
||||
if (types.putIfAbsent(key, type) != null) {
|
||||
throw new IllegalStateException("duplicate schema type key: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
// --- crawl-surface endpoints ----------------------------------------------------------------------
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilitySitemap(ContentCatalogView catalog, PluginSettings settings) {
|
||||
return new SitemapEndpoint(catalog, settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilityLlms(ContentCatalogView catalog, PluginSettings settings) {
|
||||
return new LlmsTxtEndpoint(catalog, settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilityRobots(PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
return new RobotsTxtEndpoint(settings, properties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor discoverabilityIndexNowKey(PluginSettings settings,
|
||||
DiscoverabilityProperties properties) {
|
||||
return new IndexNowKeyEndpoint(settings, properties);
|
||||
}
|
||||
|
||||
// --- IndexNow (outbound: OFF unless the platform operator AND the tenant both enable it) -----------
|
||||
|
||||
/** A {@code SiteEventListener} (collected by type by the host) that queues changed URLs, plus the flush. */
|
||||
@Bean
|
||||
public IndexNowSubmitter discoverabilityIndexNow(Sites sites, PluginSettings settings,
|
||||
DiscoverabilityProperties properties) {
|
||||
return new IndexNowSubmitter(sites, settings, properties);
|
||||
}
|
||||
|
||||
// --- advisory quality check (edit-time detect-and-lift for on-page FAQs) --------------------------
|
||||
|
||||
@Bean
|
||||
public PageQualityCheck discoverabilityFaqAdvisory(PluginSettings settings) {
|
||||
return new FaqAdvisoryCheck(settings, schemaTypes());
|
||||
}
|
||||
|
||||
/** The page editor's line saying what each page is described as, and where that comes from. */
|
||||
@Bean
|
||||
public PageQualityCheck discoverabilityPageType(PluginSettings settings, Messages messages) {
|
||||
return new PageTypeCheck(settings, schemaTypes(), messages);
|
||||
}
|
||||
|
||||
// --- console surface (dashboard card + admin fragment) --------------------------------------------
|
||||
|
||||
/** Read by the templates as {@code ${@discoverabilityAdminModel…}} (renamed from {@code discoverAdminModel}). */
|
||||
@Bean
|
||||
public DiscoverAdminModel discoverabilityAdminModel(PluginSettings settings, ContentCatalogView catalog,
|
||||
Messages messages) {
|
||||
return new DiscoverAdminModel(settings, catalog, schemaTypes(), messages);
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* App-level settings for the discoverability plugin, bound from {@code runway.plugin.discoverability.*}
|
||||
* (the host loads {@code external/plugin-settings/discoverability.yml} as a property source). These are
|
||||
* <b>platform</b> concerns — the default AI/LLM-crawler posture a site inherits, the IndexNow egress switch — never
|
||||
* per-tenant behaviour (which lives in the descriptor's {@code siteSettings} and is read live via
|
||||
* {@code PluginSettings}). Bound by {@code @ConfigurationProperties} on its {@code @Bean} method in
|
||||
* {@link DiscoverabilityConfig#discoverabilityProperties()}; applied on restart.
|
||||
*/
|
||||
public class DiscoverabilityProperties {
|
||||
|
||||
private Robots robots = new Robots();
|
||||
private IndexNow indexnow = new IndexNow();
|
||||
|
||||
public Robots getRobots() {
|
||||
return robots;
|
||||
}
|
||||
|
||||
public void setRobots(Robots robots) {
|
||||
this.robots = robots;
|
||||
}
|
||||
|
||||
public IndexNow getIndexnow() {
|
||||
return indexnow;
|
||||
}
|
||||
|
||||
public void setIndexnow(IndexNow indexnow) {
|
||||
this.indexnow = indexnow == null ? new IndexNow() : indexnow;
|
||||
}
|
||||
|
||||
/**
|
||||
* IndexNow platform settings — the operator's control over whether this deployment talks to third parties
|
||||
* at all.
|
||||
*
|
||||
* <h2>Why the platform switch exists and why it is OFF</h2>
|
||||
* IndexNow is the first thing in this plugin that makes an <b>outbound</b> request on a tenant's behalf: a
|
||||
* tenant enabling it causes this server to POST that tenant's URLs to an external service. Who this
|
||||
* deployment is allowed to talk to is the <b>platform operator's</b> decision — they own the network, the
|
||||
* egress firewall and the incident if it misbehaves — so a tenant cannot switch it on unilaterally.
|
||||
*
|
||||
* <p>Off by default because an upgrade must never start making network calls a deployment was not making
|
||||
* before. A tenant who enables it while the platform has not gets a WARN naming the tenant and the setting
|
||||
* to flip, rather than silence.
|
||||
*/
|
||||
public static class IndexNow {
|
||||
|
||||
/** Whether tenants of this deployment may use IndexNow at all. Off until the operator permits it. */
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* The submission endpoint. Configurable so an operator can point at a specific engine's endpoint or an
|
||||
* internal proxy that carries their egress policy; the default is the shared endpoint, which forwards
|
||||
* to every participating engine.
|
||||
*/
|
||||
private String endpoint = "https://api.indexnow.org/indexnow";
|
||||
|
||||
/**
|
||||
* Seconds to gather changes before submitting. Batching is not an optimisation here — a page save
|
||||
* touching five URLs must not become five outbound requests, and an editor working through a section
|
||||
* would otherwise generate one per keystroke-to-save.
|
||||
*/
|
||||
private int batchSeconds = 60;
|
||||
|
||||
/**
|
||||
* Most URLs in one submission. The spec allows 10,000; a lower cap bounds both the request body and how
|
||||
* much a single misbehaving tenant can send. Overflow is dropped with a WARN, never silently.
|
||||
*/
|
||||
private int maxUrlsPerSubmission = 1000;
|
||||
|
||||
/** Most URLs queued per site between submissions. A bound on memory during a bulk edit or a restore. */
|
||||
private int maxQueuedPerSite = 5000;
|
||||
|
||||
/** Connect/read timeout for the submission. Short: nothing waits on it, and a hung call helps nobody. */
|
||||
private int timeoutSeconds = 10;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public void setEndpoint(String endpoint) {
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public int getBatchSeconds() {
|
||||
return batchSeconds;
|
||||
}
|
||||
|
||||
public void setBatchSeconds(int batchSeconds) {
|
||||
this.batchSeconds = batchSeconds;
|
||||
}
|
||||
|
||||
public int getMaxUrlsPerSubmission() {
|
||||
return maxUrlsPerSubmission;
|
||||
}
|
||||
|
||||
public void setMaxUrlsPerSubmission(int maxUrlsPerSubmission) {
|
||||
this.maxUrlsPerSubmission = maxUrlsPerSubmission;
|
||||
}
|
||||
|
||||
public int getMaxQueuedPerSite() {
|
||||
return maxQueuedPerSite;
|
||||
}
|
||||
|
||||
public void setMaxQueuedPerSite(int maxQueuedPerSite) {
|
||||
this.maxQueuedPerSite = maxQueuedPerSite;
|
||||
}
|
||||
|
||||
public int getTimeoutSeconds() {
|
||||
return timeoutSeconds;
|
||||
}
|
||||
|
||||
public void setTimeoutSeconds(int timeoutSeconds) {
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code /robots.txt} platform defaults. */
|
||||
public static class Robots {
|
||||
|
||||
/**
|
||||
* The default AI/LLM-crawler policy a site inherits when its per-tenant {@code robots.ai-policy} is
|
||||
* {@code inherit} (the default): {@code allow} (GEO-friendly — the platform default) or {@code disallow}
|
||||
* (opt every un-overriding site out of AI crawling). Bound from {@code robots.ai-default}.
|
||||
*/
|
||||
private String aiDefault = "allow";
|
||||
|
||||
public String getAiDefault() {
|
||||
return aiDefault;
|
||||
}
|
||||
|
||||
public void setAiDefault(String aiDefault) {
|
||||
this.aiDefault = aiDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra AI/LLM crawler user-agent names to cover, <b>appended</b> to the plugin's built-in list. Bound
|
||||
* from {@code robots.ai-agents-extra}; empty by default, so the shipped behaviour is unchanged.
|
||||
*
|
||||
* <p>This exists because the built-in list is a compile-time constant that goes stale silently: when an
|
||||
* operator announces a new agent, every site set to {@code disallow} is un-covered for it until a plugin
|
||||
* release ships — and nothing reports the gap. This setting closes it the same day, without a release.
|
||||
*
|
||||
* <p>It is <b>app-level, not per-tenant</b>, deliberately: the set of agents that exist in the world is a
|
||||
* platform fact, not tenant-owned behaviour. What a tenant chooses to <i>do</i> about them stays
|
||||
* per-tenant, in {@code robots.ai-policy}.
|
||||
*
|
||||
* <p>Additive only, by design — there is no removal list. Naming an agent that has been retired costs one
|
||||
* inert {@code User-agent:} line; being unable to add one that exists costs an un-covered opt-out.
|
||||
*/
|
||||
private List<String> aiAgentsExtra = new ArrayList<>();
|
||||
|
||||
public List<String> getAiAgentsExtra() {
|
||||
return aiAgentsExtra;
|
||||
}
|
||||
|
||||
public void setAiAgentsExtra(List<String> aiAgentsExtra) {
|
||||
this.aiAgentsExtra = aiAgentsExtra == null ? new ArrayList<>() : aiAgentsExtra;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* An <b>advisory</b> {@link PageQualityCheck} that closes the loop on the type-aware structured data: the plugin
|
||||
* <em>emits</em> {@code FAQPage} from {@code content.schema}, and this check <em>detects</em> when a page has an
|
||||
* on-page FAQ (a cluster of {@code <details><summary>…</summary>…</details>} disclosures) that <b>isn't</b>
|
||||
* declared in {@code content.schema} yet, and nudges the author to add it — the "detect & lift" the audit
|
||||
* asked for. FAQ is the single highest-leverage GEO win, so surfacing an unmarked one is worth an INFO finding.
|
||||
*
|
||||
* <p>It runs at <b>edit/advisory time</b> (the host passes the freshly-rendered {@link PageView#resolvedHtml()}),
|
||||
* never at render, and it never edits the page — it only reports. It is <b>quiet when there's nothing to say</b>:
|
||||
* it stays silent unless the page has at least two disclosure clusters (a single {@code <details>} is usually a
|
||||
* "read more", not an FAQ), when the page is <b>already typed</b> {@code FAQPage} (the head renders it as one; no
|
||||
* nagging about a FAQ that's already marked up), and on a noindex page, which carries no structured data. The
|
||||
* finding is localized by its {@code code} via the host's message source
|
||||
* ({@code quality.discoverability.faq.unmarked}); the string here is only the English fallback.
|
||||
*/
|
||||
public class FaqAdvisoryCheck implements PageQualityCheck {
|
||||
|
||||
/** A {@code <details>} disclosure carrying a {@code <summary>} — i.e. a question/answer cluster. */
|
||||
private static final Pattern DISCLOSURE = Pattern.compile(
|
||||
"<details\\b[^>]*>.*?<summary\\b[^>]*>.*?</summary>.*?</details>",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
|
||||
/** Below this many disclosures a page is unlikely to be an FAQ (avoids flagging a lone "read more"). */
|
||||
private static final int MIN_DISCLOSURES = 2;
|
||||
|
||||
private static final String FALLBACK =
|
||||
"This page has an on-page FAQ (a <details>/<summary> block) that isn't emitting FAQPage structured "
|
||||
+ "data. Add it to the discoverability plugin's content.schema for this path (see the plugin help).";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Map<String, SchemaType> types;
|
||||
|
||||
public FaqAdvisoryCheck(PluginSettings settings) {
|
||||
this(settings, DiscoverabilityConfig.schemaTypes());
|
||||
}
|
||||
|
||||
FaqAdvisoryCheck(PluginSettings settings, Map<String, SchemaType> types) {
|
||||
this.settings = settings;
|
||||
this.types = types;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/faq-advisory";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Finding> inspect(PageView page) {
|
||||
if (page == null || page.resolvedHtml().isBlank() || countDisclosures(page.resolvedHtml()) < MIN_DISCLOSURES) {
|
||||
return List.of();
|
||||
}
|
||||
if (page.page() != null && page.page().noindex()) {
|
||||
return List.of(); // a noindex page carries no structured data, so FAQPage would do nothing there
|
||||
}
|
||||
if (!SiteConfig.bool(settings.site(page.site().id()).values(), "jsonld.enabled", true)) {
|
||||
return List.of(); // structured data is off for the site, so FAQPage markup would never be published
|
||||
}
|
||||
if (alreadyTypedFaq(page)) {
|
||||
return List.of(); // already marked up as FAQPage — nothing to advise
|
||||
}
|
||||
return List.of(Finding.info("discoverability.faq.unmarked", FALLBACK));
|
||||
}
|
||||
|
||||
private static int countDisclosures(String html) {
|
||||
Matcher m = DISCLOSURE.matcher(html);
|
||||
int count = 0;
|
||||
while (m.find()) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the head renders this page as an {@code FAQPage}: the same {@link PageTypes} answer the head and the
|
||||
* editor's line use. So a misspelt {@code faqpage} (an unknown type) or an {@code FAQPage} block after another
|
||||
* page type (ignored) does not count as typed, as the page served does not carry it either.
|
||||
*/
|
||||
private boolean alreadyTypedFaq(PageView page) {
|
||||
String canonical = page.canonical();
|
||||
if (canonical == null || canonical.isBlank()) {
|
||||
return false; // no canonical to derive a path from — advise rather than assume it's typed
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(page.site().id()).values();
|
||||
return "FAQPage".equals(PageTypes.describe(cfg, PageTypes.pathOf(page), types).type());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("quality.advisory", "quality.geo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code FAQPage} from a {@code faq:} list of question/answer pairs in the page's
|
||||
* {@code content.schema} entry. FAQ is the highest-leverage GEO type — answer engines lift Q&A directly —
|
||||
* so it is the first built-in {@link SchemaType}. The node is {@code mainEntityOfPage}-linked to this page's
|
||||
* {@code WebPage} {@code @id}; each entry becomes a {@code Question} with an {@code acceptedAnswer}.
|
||||
*/
|
||||
final class FaqPageSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "FAQPage";
|
||||
}
|
||||
|
||||
/** An FAQ page is what the page is: the questions become its own {@code mainEntity} (since 2.2.0). */
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
return List.of(); // describes the page itself; see describePage
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
List<Map<String, Object>> questions = questions(sc);
|
||||
if (!questions.isEmpty()) {
|
||||
page.put("mainEntity", questions);
|
||||
}
|
||||
}
|
||||
|
||||
/** No pair with both {@code q} and {@code a}: the page is an FAQPage with no questions. */
|
||||
@Override
|
||||
public Gap gap(String token, Map<String, Object> block) {
|
||||
return questions(block).isEmpty() ? new Gap("discover.gap.faq",
|
||||
"{0} has no question with both q: and a:, so the page is an {0} with no questions.") : null;
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> questions(SchemaContext sc) {
|
||||
return questions(sc.pageConfig());
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> questions(Map<String, Object> block) {
|
||||
List<Map<String, Object>> questions = new ArrayList<>();
|
||||
for (Map<String, Object> qa : Schemas.maps(block, "faq")) {
|
||||
String question = Schemas.str(qa, "q");
|
||||
String answer = Schemas.str(qa, "a");
|
||||
if (question == null || answer == null) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> node = new LinkedHashMap<>();
|
||||
node.put("@type", "Question");
|
||||
node.put("name", question);
|
||||
Map<String, Object> accepted = new LinkedHashMap<>();
|
||||
accepted.put("@type", "Answer");
|
||||
accepted.put("text", answer);
|
||||
node.put("acceptedAnswer", accepted);
|
||||
questions.add(node);
|
||||
}
|
||||
return questions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* Serves the site's IndexNow key file — the proof of ownership the protocol requires.
|
||||
*
|
||||
* <h2>Why a fixed path rather than {@code /<key>.txt}</h2>
|
||||
* IndexNow's usual pattern is a file named after the key itself. That cannot work here: the host matches
|
||||
* routes by exact path and builds the table at startup, while the key is per-site configuration that changes
|
||||
* at runtime. The spec's own {@code keyLocation} field exists for exactly this — a submission may name any URL
|
||||
* on the host as the key's location — so the file lives at a stable path and every submission points there.
|
||||
*
|
||||
* <h2>Not indexable, not in the sitemap, not cached</h2>
|
||||
* It is a verification artifact, not content: it should never appear in search results, and a cached copy
|
||||
* would keep answering with an old key after a tenant rotates it — which fails verification for as long as the
|
||||
* cache lives, in a way that looks like the engine's fault.
|
||||
*/
|
||||
public class IndexNowKeyEndpoint implements EndpointContributor {
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final DiscoverabilityProperties properties;
|
||||
|
||||
public IndexNowKeyEndpoint(PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
this.settings = settings;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/indexnow-key";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
return List.of(new Route("GET", IndexNowSubmitter.KEY_PATH, Realm.TENANT,
|
||||
new SurfacePosture(false, false, false)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
String key = SiteConfig.str(cfg, "indexnow.key", "").trim();
|
||||
|
||||
// 404 unless the platform permits IndexNow AND this site turned it on AND a key is set. Serving a key
|
||||
// for a site that is not using the feature would publish a value that only exists to be verified.
|
||||
if (!properties.getIndexnow().isEnabled()
|
||||
|| !SiteConfig.bool(cfg, "indexnow.enabled", false)
|
||||
|| key.isEmpty()) {
|
||||
return new RouteResponse(404, Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
return new RouteResponse(200,
|
||||
Map.of("Content-Type", "text/plain; charset=utf-8", "Cache-Control", "no-store"),
|
||||
key.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.indexnow-key");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
/**
|
||||
* Tells the IndexNow-participating search engines that a site's content changed, instead of waiting for them
|
||||
* to come back and find out.
|
||||
*
|
||||
* <h2>What this is, and what it is not</h2>
|
||||
* IndexNow is a published protocol (Bing, Yandex, Seznam, Naver, Yep). It is a <b>freshness</b> signal, not a
|
||||
* ranking one: it shortens the gap between publishing and being re-crawled by those engines. <b>Google does
|
||||
* not participate</b>, so this changes nothing about Google's view of a site — worth saying plainly, because
|
||||
* the opposite is widely implied and a tenant who turns this on should know what they are buying.
|
||||
*
|
||||
* <h2>Two switches, both off by default, and why</h2>
|
||||
* This is the first thing in the product that makes an <b>outbound</b> request on a tenant's behalf. So it
|
||||
* needs the <b>platform operator's</b> permission (they own the network and the egress policy) <i>and</i> the
|
||||
* tenant's (they own the URLs being disclosed). An upgrade must never start making network calls a deployment
|
||||
* was not making before, so neither switch defaults on. A tenant who enables it while the platform has not
|
||||
* gets a WARN naming both the tenant and the setting to flip — a feature that is silently inert is worse than
|
||||
* one that is off, because nobody can tell the difference from inside.
|
||||
*
|
||||
* <h2>What a change submits: where the item was, and where it is now</h2>
|
||||
* The submitter is a {@link SiteEventListener} in the {@code CONSUMER} phase. Each page write or content change
|
||||
* arrives as a {@link CatalogChange} carrying the item's URLs <b>before</b> the change (as the host last listed
|
||||
* them) and <b>after</b> it; the submitter queues the union. So a <b>deleted</b>, unpublished or moved item reports
|
||||
* its old address — the change most worth telling an engine about, and the one 1.x could not report, because it
|
||||
* resolved the URLs after the host had already dropped the item from its listing. Only the node where the change
|
||||
* happened submits ({@link CatalogChange#local()}): a cluster replays every change on its other nodes, and N nodes
|
||||
* must not send N submissions.
|
||||
*
|
||||
* <h2>Batched, bounded, and off every request thread</h2>
|
||||
* Changes accumulate per site and are submitted by a scheduled flush ({@link #flush()}, a Spring
|
||||
* {@code @Scheduled} method — it runs only while the host has scheduling enabled; see the method). A page save touching five localized URLs
|
||||
* must not become five outbound requests, and a bulk edit or a site restore must not become thousands.
|
||||
* Everything is bounded — queued URLs per site, URLs per submission — and overflow is dropped with a WARN
|
||||
* naming the tenant, never silently. No save ever waits on the network, and a failed submission is logged and
|
||||
* dropped rather than retried indefinitely: a stale IndexNow ping is worthless, and an unbounded retry queue
|
||||
* during an outage is a liability.
|
||||
*
|
||||
* <p>The HTTP call is injected as an {@link Exchange} seam (the same pattern the protection plugin's captcha
|
||||
* verifier uses), so the payload building, the gating and the bounds are unit-testable with no network at all.
|
||||
*/
|
||||
public class IndexNowSubmitter implements SiteEventListener {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(IndexNowSubmitter.class);
|
||||
|
||||
/** The fixed path the site's key file is served at — see {@link IndexNowKeyEndpoint}. */
|
||||
static final String KEY_PATH = "/indexnow-key.txt";
|
||||
|
||||
private final Sites sites;
|
||||
private final PluginSettings settings;
|
||||
private final DiscoverabilityProperties properties;
|
||||
private final Exchange exchange;
|
||||
|
||||
/** siteId → the URLs changed since the last flush. Bounded per site; insertion-ordered for stable batches. */
|
||||
private final Map<String, Set<String>> pending = new ConcurrentHashMap<>();
|
||||
|
||||
/** Sites already warned that they turned IndexNow on while the platform has it off — once per site per run. */
|
||||
private final Set<String> warnedInert = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public IndexNowSubmitter(Sites sites, PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
this(sites, settings, properties, defaultExchange(properties));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param exchange the HTTP seam that performs the submission POST — injectable so the payload, the gating
|
||||
* and the bounds are exercised without a real network call
|
||||
*/
|
||||
IndexNowSubmitter(Sites sites, PluginSettings settings, DiscoverabilityProperties properties, Exchange exchange) {
|
||||
this.sites = sites;
|
||||
this.settings = settings;
|
||||
this.properties = properties;
|
||||
this.exchange = exchange;
|
||||
}
|
||||
|
||||
// --- collecting -----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A page was created, saved, renamed, deleted, published or unpublished, or a content source announced a change:
|
||||
* every URL the item answered on before the change and every URL it answers on now is stale upstream.
|
||||
*
|
||||
* <p>Acts only on {@link CatalogChange#local() local} changes — the node where the change happened submits; a
|
||||
* peer's replay is ignored. A change that names no item (a site lifecycle event, a settings save, a whole-site
|
||||
* page reload) carries no URLs and is ignored, as 1.x ignored the events without an id. Runs on the writer's
|
||||
* thread, so it only enqueues: the network call happens in {@link #flush()}.
|
||||
*/
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
if (!change.local() || change.id() == null) {
|
||||
return;
|
||||
}
|
||||
enqueue(change.siteId(), change.previousUrls(), change.currentUrls());
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues the item's URLs from before and after the change — {@code previous ∪ current}, in that order,
|
||||
* duplicates dropped — if the site has IndexNow on.
|
||||
*
|
||||
* <p>Gated before doing any work, so a deployment with the feature off pays nothing per save.
|
||||
*/
|
||||
void enqueue(String siteId, List<LocalizedUrl> previous, List<LocalizedUrl> current) {
|
||||
if (siteId == null) {
|
||||
return;
|
||||
}
|
||||
if (!properties.getIndexnow().isEnabled()) {
|
||||
warnIfInert(siteId);
|
||||
return;
|
||||
}
|
||||
SiteView site = siteView(siteId);
|
||||
if (site == null || key(siteId).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<String> urls = urlsOf(site, previous, current);
|
||||
if (urls.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int cap = Math.max(1, properties.getIndexnow().getMaxQueuedPerSite());
|
||||
Set<String> queue = pending.computeIfAbsent(siteId, k -> java.util.Collections.synchronizedSet(
|
||||
new LinkedHashSet<>()));
|
||||
synchronized (queue) {
|
||||
for (String url : urls) {
|
||||
if (queue.size() >= cap) {
|
||||
log.warn("IndexNow queue for site '{}' is full ({} URLs) — dropping further changes until "
|
||||
+ "the next submission. Raise indexnow.max-queued-per-site if this is routine.",
|
||||
siteId, cap);
|
||||
return;
|
||||
}
|
||||
queue.add(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- submitting -----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Submits each site's accumulated URLs.
|
||||
*
|
||||
* <p>The fixed rate is the platform's {@code indexnow.batch-seconds}; Spring cannot read a bean field for
|
||||
* {@code @Scheduled}, so the annotation names the property and the default matches
|
||||
* {@link DiscoverabilityProperties.IndexNow#getBatchSeconds()}. The value is kept inside the settings form's
|
||||
* range, 5 to 3600 seconds, because a value set by hand (in the host's configuration or the settings file)
|
||||
* never passes the form: 0 or a negative value made the start fail (the scheduler refuses a delay of 0 or less).
|
||||
* A site with nothing queued costs one map lookup.
|
||||
*
|
||||
* <p><b>Scheduling is the host's.</b> The method runs only while the host application has Spring scheduling
|
||||
* enabled, which the kernel does unconditionally. This plugin deliberately does not start a scheduler of its own
|
||||
* (a plugin thread the host neither knows about nor stops).
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "#{T(java.lang.Math).max(5, T(java.lang.Math).min(3600, "
|
||||
+ "${runway.plugin.discoverability.indexnow.batch-seconds:60})) * 1000}")
|
||||
public void flush() {
|
||||
if (!properties.getIndexnow().isEnabled() || pending.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (String siteId : List.copyOf(pending.keySet())) {
|
||||
Set<String> queue = pending.remove(siteId);
|
||||
if (queue == null || queue.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
List<String> urls;
|
||||
synchronized (queue) {
|
||||
urls = List.copyOf(queue);
|
||||
}
|
||||
submit(siteId, urls);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits {@code urls} for one site, trimming to the per-submission cap and logging what was dropped.
|
||||
*
|
||||
* <p>Re-checks the platform switch even though every caller already has. A gate on outbound traffic is not
|
||||
* a place to rely on "no caller can reach here without checking" — the check costs a field read, and the
|
||||
* failure mode of getting it wrong is a deployment making network calls its operator refused.
|
||||
*/
|
||||
void submit(String siteId, List<String> urls) {
|
||||
if (!properties.getIndexnow().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
SiteView site = siteView(siteId);
|
||||
String key = key(siteId);
|
||||
if (site == null || key.isEmpty() || site.baseUrl() == null || site.baseUrl().isBlank()) {
|
||||
return;
|
||||
}
|
||||
int cap = Math.max(1, properties.getIndexnow().getMaxUrlsPerSubmission());
|
||||
List<String> batch = urls;
|
||||
if (urls.size() > cap) {
|
||||
// Named, counted, and attributed to the tenant: a silent trim is indistinguishable from a site
|
||||
// that simply changed less than it did.
|
||||
log.warn("IndexNow submission for site '{}' has {} URLs, over the {} cap — submitting the first {} "
|
||||
+ "and DROPPING {}. The dropped pages are still crawled normally.",
|
||||
siteId, urls.size(), cap, cap, urls.size() - cap);
|
||||
batch = urls.subList(0, cap);
|
||||
}
|
||||
String host = hostOf(site.baseUrl());
|
||||
String payload = payload(host, key, site.baseUrl() + KEY_PATH, batch);
|
||||
try {
|
||||
Exchange.Response response = exchange.post(properties.getIndexnow().getEndpoint(), payload);
|
||||
if (response.status() >= 200 && response.status() < 300) {
|
||||
log.debug("IndexNow: submitted {} URL(s) for site '{}' ({})", batch.size(), siteId,
|
||||
response.status());
|
||||
} else {
|
||||
// 403 means the key file did not verify — the single most likely misconfiguration, and one the
|
||||
// tenant can fix, so say what it means rather than only what happened.
|
||||
log.warn("IndexNow submission for site '{}' was refused ({}): {}{}", siteId, response.status(),
|
||||
abbreviate(response.body()),
|
||||
response.status() == 403
|
||||
? " — the engine could not verify " + site.baseUrl() + KEY_PATH
|
||||
+ "; check the key matches and the path is publicly reachable." : "");
|
||||
}
|
||||
} catch (IOException | RuntimeException failed) {
|
||||
// Dropped, not retried: a stale freshness ping is worthless, and an unbounded retry queue during an
|
||||
// outage is a liability. The pages are still crawled the ordinary way.
|
||||
log.warn("IndexNow submission for site '{}' failed ({} URL(s) not submitted): {}",
|
||||
siteId, batch.size(), failed.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The IndexNow JSON body.
|
||||
*
|
||||
* <p>Hand-built rather than through a mapper because it is four fields and a string list, and the plugin
|
||||
* has no JSON dependency of its own. Every value is escaped — {@code host} and {@code keyLocation} derive
|
||||
* from tenant-controlled configuration, so an unescaped quote would be a payload-injection hole, not a
|
||||
* formatting bug.
|
||||
*/
|
||||
static String payload(String host, String key, String keyLocation, List<String> urls) {
|
||||
StringBuilder json = new StringBuilder(128 + urls.size() * 64);
|
||||
json.append("{\"host\":\"").append(escape(host))
|
||||
.append("\",\"key\":\"").append(escape(key))
|
||||
.append("\",\"keyLocation\":\"").append(escape(keyLocation))
|
||||
.append("\",\"urlList\":[");
|
||||
for (int i = 0; i < urls.size(); i++) {
|
||||
if (i > 0) {
|
||||
json.append(',');
|
||||
}
|
||||
json.append('"').append(escape(urls.get(i))).append('"');
|
||||
}
|
||||
return json.append("]}").toString();
|
||||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder out = new StringBuilder(value.length());
|
||||
for (char c : value.toCharArray()) {
|
||||
switch (c) {
|
||||
case '"' -> out.append("\\\"");
|
||||
case '\\' -> out.append("\\\\");
|
||||
case '\n' -> out.append("\\n");
|
||||
case '\r' -> out.append("\\r");
|
||||
case '\t' -> out.append("\\t");
|
||||
default -> {
|
||||
if (c < 0x20) {
|
||||
out.append(String.format("\\u%04x", (int) c));
|
||||
} else {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
// --- helpers --------------------------------------------------------------------------------------
|
||||
|
||||
/** The absolute form of every URL in {@code previous} then {@code current}, without duplicates. */
|
||||
private static Set<String> urlsOf(SiteView site, List<LocalizedUrl> previous, List<LocalizedUrl> current) {
|
||||
String base = site.baseUrl();
|
||||
Set<String> urls = new LinkedHashSet<>();
|
||||
if (base == null || base.isBlank()) {
|
||||
return urls;
|
||||
}
|
||||
for (List<LocalizedUrl> list : List.of(previous, current)) {
|
||||
for (LocalizedUrl url : list) {
|
||||
urls.add(url.absolute(base.trim()));
|
||||
}
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
/** The site's IndexNow key, or empty when unset — which is how a tenant leaves the feature off. */
|
||||
/**
|
||||
* The promise in the class Javadoc: a site that turned IndexNow on while the platform has it off is told, in
|
||||
* the log, which setting to flip — once per site per run (the platform switch only changes on restart), and
|
||||
* after that at no cost per save. The site's settings form says the same thing to the tenant.
|
||||
*/
|
||||
private void warnIfInert(String siteId) {
|
||||
if (warnedInert.contains(siteId)) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(siteId).values();
|
||||
if (SiteConfig.bool(cfg, "indexnow.enabled", false) && warnedInert.add(siteId)) {
|
||||
log.warn("site '{}' has IndexNow enabled, but the platform has not permitted it — nothing is submitted. "
|
||||
+ "The platform operator turns it on with discoverability's app-level indexnow.enabled.", siteId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the inert-site warning has been logged for this site (tests). */
|
||||
boolean warnedInert(String siteId) {
|
||||
return warnedInert.contains(siteId);
|
||||
}
|
||||
|
||||
private String key(String siteId) {
|
||||
Map<String, Object> cfg = settings.site(siteId).values();
|
||||
if (!SiteConfig.bool(cfg, "indexnow.enabled", false)) {
|
||||
return "";
|
||||
}
|
||||
String key = SiteConfig.str(cfg, "indexnow.key", "").trim();
|
||||
if (key.isEmpty()) {
|
||||
log.warn("site '{}' has IndexNow enabled but no indexnow.key — nothing is submitted. Generate a "
|
||||
+ "random key and set it, then confirm {} serves it.", siteId, KEY_PATH);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
private SiteView siteView(String siteId) {
|
||||
return sites.find(siteId).orElse(null);
|
||||
}
|
||||
|
||||
/** The bare host of a base URL — what IndexNow's {@code host} field expects (no scheme, no path). */
|
||||
static String hostOf(String baseUrl) {
|
||||
try {
|
||||
String host = URI.create(baseUrl).getHost();
|
||||
return host == null ? "" : host;
|
||||
} catch (IllegalArgumentException notAUrl) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String abbreviate(String body) {
|
||||
if (body == null) {
|
||||
return "";
|
||||
}
|
||||
String flat = body.replaceAll("[\\r\\n]+", " ").trim();
|
||||
return flat.length() <= 200 ? flat : flat.substring(0, 200) + "…";
|
||||
}
|
||||
|
||||
// --- the HTTP seam --------------------------------------------------------------------------------
|
||||
|
||||
/** The outbound call, isolated so everything around it is testable without a network. */
|
||||
public interface Exchange {
|
||||
|
||||
/**
|
||||
* POSTs {@code json} ({@code application/json}) to {@code url}.
|
||||
*
|
||||
* @return the endpoint's response (status + body)
|
||||
* @throws IOException if the request cannot be completed
|
||||
*/
|
||||
Response post(String url, String json) throws IOException;
|
||||
|
||||
/** A minimal HTTP response view — the status and body this submitter needs to log an outcome. */
|
||||
record Response(int status, String body) {
|
||||
}
|
||||
}
|
||||
|
||||
private static Exchange defaultExchange(DiscoverabilityProperties properties) {
|
||||
Duration timeout = Duration.ofSeconds(Math.max(1, properties.getIndexnow().getTimeoutSeconds()));
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(timeout).build();
|
||||
return (url, json) -> {
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(timeout)
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return new Exchange.Response(response.statusCode(), response.body());
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("IndexNow submission interrupted", interrupted);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The schema.org <b>JSON-LD builder</b> — the shared spine of both SEO+ and GEO. It builds ordered node maps,
|
||||
* serializes them into a single {@code @graph}, and wraps that in a {@code <script type="application/ld+json">}
|
||||
* block escaped so it can never break out of the {@code <head>}. Pure and stateless.
|
||||
*
|
||||
* <p>The {@code @id} conventions are the seam between the two capability areas: the SEO contributor defines the
|
||||
* {@code WebSite}/{@code WebPage}/{@code Organization} nodes, and the GEO contributor <b>enriches those same
|
||||
* nodes by @id reference</b> (adding {@code potentialAction}/{@code speakable}) rather than redefining them —
|
||||
* so a crawler merges them into one entity graph with no duplication.
|
||||
*/
|
||||
final class Ld {
|
||||
|
||||
static final String CONTEXT = "https://schema.org";
|
||||
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||
|
||||
private Ld() {
|
||||
}
|
||||
|
||||
// --- stable @id conventions (shared by SEO + GEO) ----------------------
|
||||
|
||||
static String websiteId(String base) {
|
||||
return base + "/#website";
|
||||
}
|
||||
|
||||
static String organizationId(String base) {
|
||||
return base + "/#organization";
|
||||
}
|
||||
|
||||
static String webpageId(String canonical) {
|
||||
return canonical + "#webpage";
|
||||
}
|
||||
|
||||
static String softwareId(String base) {
|
||||
return base + "/#software";
|
||||
}
|
||||
|
||||
/** The {@code scheme://host} origin of an absolute URL, or {@code ""} if it is not absolute. */
|
||||
static String origin(String url) {
|
||||
if (url == null) {
|
||||
return "";
|
||||
}
|
||||
int scheme = url.indexOf("://");
|
||||
if (scheme < 0) {
|
||||
return "";
|
||||
}
|
||||
int slash = url.indexOf('/', scheme + 3);
|
||||
return slash < 0 ? url : url.substring(0, slash);
|
||||
}
|
||||
|
||||
// --- node building -----------------------------------------------------
|
||||
|
||||
/** A new node with its {@code @type} (and {@code @id} when non-null). */
|
||||
static Map<String, Object> node(String type, String id) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("@type", type);
|
||||
if (id != null && !id.isBlank()) {
|
||||
m.put("@id", id);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Sets {@code key} to {@code value} only when the value is non-blank (empty properties are never emitted). */
|
||||
static void put(Map<String, Object> node, String key, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
node.put(key, value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets {@code key} to a single value or an array (schema.org accepts either), omitting an empty list. */
|
||||
static void putList(Map<String, Object> node, String key, List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
node.put(key, values.size() == 1 ? values.get(0) : values);
|
||||
}
|
||||
|
||||
/** Sets {@code key} to an {@code @id} reference to another node. */
|
||||
static void ref(Map<String, Object> node, String key, String id) {
|
||||
if (id != null && !id.isBlank()) {
|
||||
node.put(key, Map.of("@id", id));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a {@code @graph} of nodes into an escaped {@code <script type="application/ld+json">} block,
|
||||
* or {@code ""} when the graph is empty. {@code <}, {@code >} and {@code &} are unicode-escaped so the JSON
|
||||
* can never terminate the surrounding {@code <script>} element.
|
||||
*/
|
||||
static String script(List<Map<String, Object>> nodes) {
|
||||
List<Map<String, Object>> present = nodes.stream().filter(n -> n != null && !n.isEmpty()).toList();
|
||||
if (present.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
Map<String, Object> graph = new LinkedHashMap<>();
|
||||
graph.put("@context", CONTEXT);
|
||||
graph.put("@graph", present);
|
||||
String json = JSON.writeValueAsString(graph)
|
||||
.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026");
|
||||
return "\n<script type=\"application/ld+json\">" + json + "</script>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* GEO — serves a per-site <b>{@code /llms.txt}</b>, the emerging convention for exposing a site's content to
|
||||
* large-language-model / answer engines in a compact, machine-friendly form: an {@code H1} of the site name, a
|
||||
* one-line summary (the tenant's {@code geo.summary}), then the site's whole published content surface —
|
||||
* kernel pages AND every content source's items (blog entries, any plugin content) — as Markdown links with
|
||||
* their descriptions, in the site's default locale. Built from the host's {@link ContentCatalogView}
|
||||
* (kernel-re-filtered, metadata-only: no item's body is ever read serving this route).
|
||||
*
|
||||
* <p>Each item is linked at {@link CatalogEntry#pathFor(Locale) its address in the default locale}, or — for an
|
||||
* item that does not exist in the default locale — at its primary locale's real address. (Until 2.0.0 such an item
|
||||
* was linked at its unprefixed default path, which the site answers with a 404.)
|
||||
*
|
||||
* <p>Part of the opt-in GEO area: gated by the per-tenant {@code geo.enabled} flag — disabled ⇒ {@code 404}.
|
||||
*/
|
||||
public class LlmsTxtEndpoint implements EndpointContributor {
|
||||
|
||||
private final ContentCatalogView catalog;
|
||||
private final PluginSettings settings;
|
||||
|
||||
public LlmsTxtEndpoint(ContentCatalogView catalog, PluginSettings settings) {
|
||||
this.catalog = catalog;
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/llms";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// Cacheable: this endpoint manages its own caching (Last-Modified + no-cache revalidation).
|
||||
return List.of(new Route("GET", "/llms.txt", Realm.TENANT, new SurfacePosture(true, true, true)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "geo.enabled", false)) {
|
||||
// The route posture is cacheable (so the 200/304 carry their own validators), which means the
|
||||
// dispatcher no longer stamps a fail-safe no-store — so this disabled-path 404 must forbid caching
|
||||
// itself, or a heuristically-cacheable 404 could outlive the tenant re-enabling the surface.
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
String base = PageUrls.base(req.site(), req);
|
||||
Locale def = req.site().defaultLocale();
|
||||
|
||||
List<CatalogEntry> items = catalog.entries(req.site().id());
|
||||
String summary = SiteConfig.str(cfg, "geo.summary", "");
|
||||
// The validator folds what this document prints besides the items: the H1 (the site name), the summary,
|
||||
// the locale every title and link is chosen in, and the site's base URL every link starts with — so editing
|
||||
// any of them advances Last-Modified and a revalidating crawler refetches (until 2.1.0 it kept the old copy).
|
||||
// The base URL, not the request origin: a host-less site reached under two names serves each its own links,
|
||||
// and each crawler's copy stays right for the address it fetched — folding the origin would only make the
|
||||
// validator advance on every alternate request.
|
||||
java.time.Instant newest = CrawlConditional.lastModified(req.site().id(), CrawlConditional.LLMS, items,
|
||||
java.util.Arrays.asList(req.site().displayName(), summary, def.toLanguageTag(),
|
||||
req.site().baseUrl()));
|
||||
if (CrawlConditional.notModified(req, newest)) {
|
||||
return CrawlConditional.notModifiedResponse(newest);
|
||||
}
|
||||
|
||||
StringBuilder out = new StringBuilder(512);
|
||||
out.append("# ").append(req.site().displayName()).append("\n\n");
|
||||
if (!summary.isBlank()) {
|
||||
out.append("> ").append(oneLine(summary)).append("\n\n");
|
||||
}
|
||||
out.append("## Pages\n\n");
|
||||
for (CatalogEntry item : items) {
|
||||
// Same rule as the sitemap: content the site tells robots not to index has no business being
|
||||
// advertised to answer engines either. llms.txt is a recommendation list, not a site dump.
|
||||
if (item.ref().noindex()) {
|
||||
continue;
|
||||
}
|
||||
String title = item.ref().titleFor(def);
|
||||
String label = mdLabel((title == null || title.isBlank()) ? item.ref().id() : title);
|
||||
String url = base + item.pathFor(def);
|
||||
out.append("- [").append(label).append("](").append(url).append(")");
|
||||
String desc = item.ref().descriptionFor(def);
|
||||
if (desc != null && !desc.isBlank()) {
|
||||
out.append(": ").append(oneLine(desc));
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
return new RouteResponse(200,
|
||||
CrawlConditional.cacheHeaders(newest, "text/plain; charset=utf-8"),
|
||||
out.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String oneLine(String text) {
|
||||
return text.replace('\n', ' ').replace('\r', ' ').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* A markdown-safe link label: one line, with the link metacharacters mapped to parentheses-free forms so a
|
||||
* legitimate title like {@code FAQ [updated]} cannot terminate the {@code [label](url)} early and corrupt
|
||||
* the machine-parsed index.
|
||||
*/
|
||||
private static String mdLabel(String text) {
|
||||
return oneLine(text).replace('[', '(').replace(']', ')');
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.geo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits one or more schema.org {@code LocalBusiness} nodes (or the entry's declared subtype, e.g.
|
||||
* {@code CafeOrCoffeeShop}) from a {@code content.schema} entry. A {@code locations:} list yields one node per
|
||||
* location (name/address/geo/telephone/openingHours/priceRange); with no list, a single node is built from the
|
||||
* entry's own fields. {@code geo} is emitted only when both latitude and longitude are provided.
|
||||
*/
|
||||
final class LocalBusinessSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "LocalBusiness";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String type = Schemas.str(cfg, "type", "LocalBusiness"); // LocalBusiness | CafeOrCoffeeShop | …
|
||||
List<Map<String, Object>> locations = Schemas.maps(cfg, "locations");
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
if (locations.isEmpty()) {
|
||||
out.add(business(type, cfg, ctx, sc, 1));
|
||||
} else {
|
||||
int index = 1;
|
||||
for (Map<String, Object> location : locations) {
|
||||
out.add(business(type, location, ctx, sc, index++));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> business(String type, Map<String, Object> b, HeadContext ctx,
|
||||
SchemaContext sc, int index) {
|
||||
// A stable @id per location (canonical#business-N) + a link back to the page, so each node is part of the
|
||||
// graph rather than a bare, unlinked node. geo is emitted below when the tenant supplies coordinates.
|
||||
Map<String, Object> node = Ld.node(type, sc.canonical() + "#business-" + index);
|
||||
Ld.ref(node, "mainEntityOfPage", sc.webpageId());
|
||||
Ld.put(node, "url", Schemas.absolute(Schemas.str(b, "url", sc.canonical()), sc.base()));
|
||||
Ld.put(node, "name", Schemas.str(b, "name", ctx.site().displayName()));
|
||||
Ld.put(node, "telephone", Schemas.str(b, "telephone"));
|
||||
Ld.putList(node, "image", Schemas.absolute(Schemas.strings(b, "image"), sc.base()));
|
||||
Ld.put(node, "priceRange", Schemas.str(b, "priceRange"));
|
||||
Ld.putList(node, "openingHours", Schemas.strings(b, "hours"));
|
||||
|
||||
String street = Schemas.str(b, "street");
|
||||
String locality = Schemas.str(b, "locality");
|
||||
if (street != null || locality != null) {
|
||||
Map<String, Object> address = Ld.node("PostalAddress", null);
|
||||
Ld.put(address, "streetAddress", street);
|
||||
Ld.put(address, "addressLocality", locality);
|
||||
Ld.put(address, "addressRegion", Schemas.str(b, "region"));
|
||||
Ld.put(address, "postalCode", Schemas.str(b, "postalCode"));
|
||||
Ld.put(address, "addressCountry", Schemas.str(b, "country"));
|
||||
node.put("address", address);
|
||||
}
|
||||
|
||||
String latitude = Schemas.str(b, "latitude");
|
||||
String longitude = Schemas.str(b, "longitude");
|
||||
if (latitude != null && longitude != null) {
|
||||
Map<String, Object> geo = new LinkedHashMap<>();
|
||||
geo.put("@type", "GeoCoordinates");
|
||||
geo.put("latitude", latitude);
|
||||
geo.put("longitude", longitude);
|
||||
node.put("geo", geo);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
/**
|
||||
* Parses the per-tenant {@code content.schema} text (a small YAML document keyed by URL-path pattern) and
|
||||
* resolves the entry for a given page path. Parsing is memoized by the raw text, so it happens once per distinct
|
||||
* config value (which changes only when the tenant edits it) rather than per request.
|
||||
*
|
||||
* <p>Format — a map of path pattern → entry. An entry is either <b>one type-block</b> (a map with a {@code type}
|
||||
* plus type-specific fields) or a <b>list of type-blocks</b> when a single page carries several types (e.g. a
|
||||
* pricing page that is both an {@code FAQPage} and a set of {@code Offer}s):
|
||||
* <pre>
|
||||
* /coffee-*:
|
||||
* type: Product
|
||||
* currency: USD
|
||||
* /pricing:
|
||||
* - type: FAQPage
|
||||
* faq: [ { q: "Why ranges?", a: "Scope drives cost…" } ]
|
||||
* - type: Service
|
||||
* offers: [ { name: "Advisory Sprint", price: "18000", currency: USD } ]
|
||||
* </pre>
|
||||
* A pattern ending in {@code *} is a prefix match; an <b>exact</b> path always wins, and among prefix patterns
|
||||
* the <b>longest</b> wins. A malformed document disables typing (returns no entries) rather than breaking the page.
|
||||
*/
|
||||
final class PageSchemaConfig {
|
||||
|
||||
private static final YAMLMapper YAML = YAMLMapper.builder().build();
|
||||
private static final int MAX_CACHE = 128;
|
||||
// Memo keyed by the raw config text — self-evicting (a changed value is a new key); bounded as a backstop.
|
||||
// Value: pattern → entry, where an entry is a Map (one type-block) or a List of Maps (several).
|
||||
private static final Map<String, Map<String, Object>> CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
private PageSchemaConfig() {
|
||||
}
|
||||
|
||||
/** Parses {@code content.schema} into {@code pattern → entry}; empty for blank/malformed input. */
|
||||
static Map<String, Object> parse(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> cached = CACHE.get(text);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Map<String, Object> parsed = doParse(text);
|
||||
if (CACHE.size() > MAX_CACHE) {
|
||||
CACHE.clear();
|
||||
}
|
||||
CACHE.put(text, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why {@code text} cannot be used at all, or {@code null} when it parses (blank included): the YAML error, or a
|
||||
* root that is not a map of patterns. {@link #parse} turns either into "no types" so a page never breaks; this
|
||||
* tells the site manager instead.
|
||||
*/
|
||||
static String syntaxProblem(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Object root = YAML.readValue(text, Object.class);
|
||||
return root instanceof Map<?, ?> ? null : "the text is not a list of 'pattern: type' entries";
|
||||
} catch (Exception e) {
|
||||
String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
|
||||
int newline = message.indexOf('\n');
|
||||
return newline > 0 ? message.substring(0, newline) : message;
|
||||
}
|
||||
}
|
||||
|
||||
/** The raw entries whose value is neither one block nor a list of blocks: they are ignored. */
|
||||
static List<String> ignoredPatterns(String text) {
|
||||
List<String> out = new ArrayList<>();
|
||||
try {
|
||||
Object root = YAML.readValue(text, Object.class);
|
||||
if (root instanceof Map<?, ?> map) {
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List)) {
|
||||
out.add(String.valueOf(entry.getKey()));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// syntaxProblem reports it
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> doParse(String text) {
|
||||
try {
|
||||
Object root = YAML.readValue(text, Object.class);
|
||||
if (!(root instanceof Map<?, ?> map)) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (var entry : map.entrySet()) {
|
||||
// An entry is one type-block (Map) or several (List); anything else is ignored.
|
||||
if (entry.getKey() != null && (entry.getValue() instanceof Map || entry.getValue() instanceof List)) {
|
||||
out.put(entry.getKey().toString(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch (Exception ex) {
|
||||
return Map.of(); // a malformed content.schema disables typing rather than breaking the page
|
||||
}
|
||||
}
|
||||
|
||||
/** The entry (a Map or a List) whose pattern matches {@code path}: exact wins, else the longest {@code *}-prefix. */
|
||||
static Object resolve(Map<String, Object> patterns, String path) {
|
||||
String pattern = matchingPattern(patterns, path);
|
||||
return pattern == null ? null : patterns.get(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* The pattern that matches {@code path}: the path itself when listed, else the longest {@code *}-prefix whose
|
||||
* prefix starts the path; {@code null} when none does. A {@code *} anywhere but at the end is a literal
|
||||
* character.
|
||||
*/
|
||||
static String matchingPattern(Map<String, Object> patterns, String path) {
|
||||
if (patterns.isEmpty() || path == null) {
|
||||
return null;
|
||||
}
|
||||
if (patterns.containsKey(path)) {
|
||||
return path;
|
||||
}
|
||||
String best = null;
|
||||
int bestLen = -1;
|
||||
for (String pattern : patterns.keySet()) {
|
||||
if (pattern.endsWith("*")) {
|
||||
String prefix = pattern.substring(0, pattern.length() - 1);
|
||||
if (path.startsWith(prefix) && prefix.length() > bestLen) {
|
||||
best = pattern;
|
||||
bestLen = prefix.length();
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Normalizes a resolved entry to its list of type-blocks: a single Map → one block; a List → its Map items. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<Map<String, Object>> blocks(Object entry) {
|
||||
if (entry instanceof Map<?, ?> map) {
|
||||
return List.of((Map<String, Object>) map);
|
||||
}
|
||||
if (entry instanceof List<?> list) {
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Object item : list) {
|
||||
if (item instanceof Map<?, ?> map) {
|
||||
out.add((Map<String, Object>) map);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* The page editor's line about structured data: what this page is described as, and where that comes from — the
|
||||
* site's Default page type, or a Per-page types ({@code content.schema}) pattern — plus what the entry adds, and a
|
||||
* warning for a type the plugin does not know, a second page type it ignores, or a block that publishes nothing of
|
||||
* its own (an {@code FAQPage} with no complete question). A noindex page carries no structured data, and the line
|
||||
* says so first, as the head checks it first. A translated page that the default language's entry does not reach
|
||||
* gets a note naming the key that would.
|
||||
*
|
||||
* <h2>Why</h2>
|
||||
* The site form says "Default page type", and nothing showed whether a
|
||||
* given page took it or something else. The answer is computed by {@link PageTypes}, the same code the public page's
|
||||
* {@code <head>} uses, so the editor cannot describe a page differently from how it is served.
|
||||
*
|
||||
* <p>Reported through the existing quality-check seam as {@code INFO} (a neutral observation, never a gate) and
|
||||
* {@code WARNING} findings; their text is resolved here in the operator's UI language, since a finding carries no
|
||||
* message arguments.
|
||||
*/
|
||||
public class PageTypeCheck implements PageQualityCheck {
|
||||
|
||||
static final String CODE = "discoverability.page-type";
|
||||
static final String CODE_UNKNOWN = "discoverability.page-type.unknown";
|
||||
static final String CODE_EXTRA = "discoverability.page-type.extra";
|
||||
static final String CODE_GAP = "discoverability.page-type.gap";
|
||||
static final String CODE_OTHER_LANGUAGE = "discoverability.page-type.other-language";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Map<String, SchemaType> types;
|
||||
private final Messages messages;
|
||||
|
||||
PageTypeCheck(PluginSettings settings, Map<String, SchemaType> types, Messages messages) {
|
||||
this.settings = settings;
|
||||
this.types = types;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/page-type";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Finding> inspect(PageView page) {
|
||||
if (page == null || page.canonical() == null || page.canonical().isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
if (page.page() != null && page.page().noindex()) {
|
||||
// The head emits no JSON-LD on a noindex page, before it looks at anything else; so does this line.
|
||||
return List.of(Finding.info(CODE, text("discover.pagetype.noindex",
|
||||
"Structured data: this page is excluded from search engines (noindex), so it carries no "
|
||||
+ "structured data.")));
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(page.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "jsonld.enabled", true)) {
|
||||
return List.of(Finding.info(CODE, text("discover.pagetype.off",
|
||||
"Structured data is switched off for this site, so this page is not described to search "
|
||||
+ "engines.")));
|
||||
}
|
||||
String path = PageTypes.pathOf(page);
|
||||
PageTypes.Description d = PageTypes.describe(cfg, path, types);
|
||||
List<Finding> findings = new ArrayList<>();
|
||||
String main = d.source() == PageTypes.Source.SCHEMA
|
||||
? text("discover.pagetype.schema", "Structured data: this page is a {0}, set by Per-page types "
|
||||
+ "(pattern {1}).", d.type(), d.pattern())
|
||||
: text("discover.pagetype.default", "Structured data: this page is a {0}, the site''s Default "
|
||||
+ "page type.", d.type());
|
||||
if (!d.added().isEmpty()) {
|
||||
main = main + " " + text("discover.pagetype.added", "Per-page types also add: {0}.",
|
||||
String.join(", ", d.addedTypes()));
|
||||
}
|
||||
findings.add(Finding.info(CODE, main));
|
||||
PageTypes.OtherLanguageEntry other = PageTypes.otherLanguageEntry(cfg, path, page.site());
|
||||
if (other != null) {
|
||||
findings.add(Finding.info(CODE_OTHER_LANGUAGE, text("discover.pagetype.otherLanguage",
|
||||
"Per-page types: {0} describes the default language''s page, not this one; a page in another "
|
||||
+ "language is matched only by its own path. To describe this page, add {1}.",
|
||||
other.pattern(), other.suggestion())));
|
||||
}
|
||||
if (d.pageBlock() != null) {
|
||||
gap(findings, d.type(), d.pageBlock());
|
||||
}
|
||||
for (Map<String, Object> block : d.added()) {
|
||||
gap(findings, Schemas.str(block, "type", ""), block);
|
||||
}
|
||||
if (!d.unknown().isEmpty()) {
|
||||
findings.add(Finding.warning(CODE_UNKNOWN, text("discover.pagetype.unknown",
|
||||
"Per-page types name {0} for this page, which this plugin does not know; it is ignored.",
|
||||
String.join(", ", d.unknown()))));
|
||||
}
|
||||
if (!d.extraPageTypes().isEmpty()) {
|
||||
findings.add(Finding.warning(CODE_EXTRA, text("discover.pagetype.extra",
|
||||
"Per-page types give this page more than one page type; only the first ({0}) applies, "
|
||||
+ "{1} is ignored.", d.type(), String.join(", ", d.extraPageTypes()))));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
/** A warning for a block that applies but publishes nothing of its own ({@link SchemaType#gap}). */
|
||||
private void gap(List<Finding> findings, String token, Map<String, Object> block) {
|
||||
SchemaType handler = types.get(token);
|
||||
SchemaType.Gap gap = handler == null ? null : handler.gap(token, block);
|
||||
if (gap != null) {
|
||||
findings.add(Finding.warning(CODE_GAP, text(gap.code(), gap.fallback(), token)));
|
||||
}
|
||||
}
|
||||
|
||||
private String text(String code, String fallback, Object... args) {
|
||||
return messages == null ? java.text.MessageFormat.format(fallback, args)
|
||||
: messages.console(code, fallback, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("quality.advisory", "quality.structured-data");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* How one page is described in structured data: its own type, where that type comes from, and what else its
|
||||
* {@code content.schema} entry adds. The one answer both the public page ({@link StructuredDataHead}) and the page
|
||||
* editor's line ({@link PageTypeCheck}) use, so the two can never disagree.
|
||||
*
|
||||
* <h2>The rule</h2>
|
||||
* <ul>
|
||||
* <li>The page's {@code content.schema} entry is found by its own path: the exact path, else the longest
|
||||
* {@code *}-prefix. A page behind a language prefix ({@code /es/faq}) is matched only by a key written for that
|
||||
* path ({@code /es/faq}, {@code /es/*}, {@code /*}); {@code /faq} does not reach it, because an entry's text
|
||||
* (questions, names, a breadcrumb parent) is written in one language and would be published on the other
|
||||
* language's page.</li>
|
||||
* <li>The first block whose type describes the page itself ({@link SchemaType#describesPage}) sets the page's
|
||||
* type; otherwise the page has the site's Default page type ({@code jsonld.type}).</li>
|
||||
* <li>Every other recognized block adds an entity (a product, a service, a business, a person, a list).</li>
|
||||
* <li>A block naming an unknown type is ignored, and so is a second block that describes the page (a page has one
|
||||
* type); both are reported in the editor so neither goes unnoticed.</li>
|
||||
* </ul>
|
||||
*/
|
||||
final class PageTypes {
|
||||
|
||||
/** Where the page's own type came from. */
|
||||
enum Source {
|
||||
/** The site's Default page type ({@code jsonld.type}). */
|
||||
DEFAULT,
|
||||
/** A {@code content.schema} block for this page. */
|
||||
SCHEMA
|
||||
}
|
||||
|
||||
/**
|
||||
* One page's description.
|
||||
*
|
||||
* @param type the page's own {@code @type}
|
||||
* @param source where {@code type} came from
|
||||
* @param pattern the matching {@code content.schema} pattern, or {@code null} when none matches
|
||||
* @param pageBlock the block that set the type ({@code null} when it is the default)
|
||||
* @param added the blocks that add an entity, in declared order
|
||||
* @param unknown type tokens in the entry that no handler knows (a block with no {@code type} is not listed)
|
||||
* @param extraPageTypes page-describing tokens after the first, which are ignored
|
||||
*/
|
||||
record Description(String type, Source source, String pattern, Map<String, Object> pageBlock,
|
||||
List<Map<String, Object>> added, List<String> unknown, List<String> extraPageTypes) {
|
||||
|
||||
/** The type tokens of the added blocks, in order. */
|
||||
List<String> addedTypes() {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (Map<String, Object> block : added) {
|
||||
out.add(Schemas.str(block, "type", ""));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
private PageTypes() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The path of the page a {@link mx.quest.runway.spi.model.PageView} shows, relative to the site base, the way the
|
||||
* head derives it from the canonical URL.
|
||||
*/
|
||||
static String pathOf(mx.quest.runway.spi.model.PageView page) {
|
||||
String base = page.site().baseUrl();
|
||||
base = (base != null && !base.isBlank()) ? base.trim() : "";
|
||||
if (base.endsWith("/")) {
|
||||
base = base.substring(0, base.length() - 1);
|
||||
}
|
||||
return StructuredDataHead.pathOf(base, page.canonical());
|
||||
}
|
||||
|
||||
/** The site's Default page type as the head uses it: {@code Article} when so configured, else {@code WebPage}. */
|
||||
static String defaultType(Map<String, Object> cfg) {
|
||||
return "Article".equals(SiteConfig.str(cfg, "jsonld.type", "WebPage")) ? "Article" : "WebPage";
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes the page at {@code path}.
|
||||
*
|
||||
* @param cfg the site's discoverability settings
|
||||
* @param path the page's path relative to the site base, starting with {@code /}
|
||||
* @param types the type registry, by token
|
||||
*/
|
||||
static Description describe(Map<String, Object> cfg, String path, Map<String, SchemaType> types) {
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", ""));
|
||||
String pattern = PageSchemaConfig.matchingPattern(patterns, path);
|
||||
Map<String, Object> pageBlock = null;
|
||||
String pageType = null;
|
||||
List<Map<String, Object>> added = new ArrayList<>();
|
||||
List<String> unknown = new ArrayList<>();
|
||||
List<String> extraPageTypes = new ArrayList<>();
|
||||
if (pattern != null) {
|
||||
for (Map<String, Object> block : PageSchemaConfig.blocks(patterns.get(pattern))) {
|
||||
String token = Schemas.str(block, "type", "");
|
||||
if (token.isBlank()) {
|
||||
continue; // a block with no type only carries shared fields (a breadcrumb parent)
|
||||
}
|
||||
SchemaType handler = types.get(token);
|
||||
if (handler == null) {
|
||||
unknown.add(token);
|
||||
} else if (handler.describesPage(token)) {
|
||||
if (pageBlock == null) {
|
||||
pageBlock = block;
|
||||
pageType = token;
|
||||
} else {
|
||||
extraPageTypes.add(token);
|
||||
}
|
||||
} else {
|
||||
added.add(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
return pageBlock != null
|
||||
? new Description(pageType, Source.SCHEMA, pattern, pageBlock, added, unknown, extraPageTypes)
|
||||
: new Description(defaultType(cfg), Source.DEFAULT, pattern, null, added, unknown, extraPageTypes);
|
||||
}
|
||||
|
||||
/** The matching {@code content.schema} entry for {@code path}, or {@code null}. */
|
||||
static Object entry(Map<String, Object> cfg, String path) {
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", ""));
|
||||
String pattern = PageSchemaConfig.matchingPattern(patterns, path);
|
||||
return pattern == null ? null : patterns.get(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* The default language's entry that does not reach a translated page.
|
||||
*
|
||||
* @param pattern the pattern matching the same path in the default language ({@code /faq})
|
||||
* @param suggestion the key that would describe this page ({@code /es/faq}; {@code /es/blog/*} for {@code /blog/*})
|
||||
*/
|
||||
record OtherLanguageEntry(String pattern, String suggestion) {
|
||||
}
|
||||
|
||||
/**
|
||||
* For a page behind a non-default language prefix ({@code /es/faq}): the pattern that matches the same path in
|
||||
* the default language ({@code /faq}) but not this page; {@code null} when there is none, or when this page's own
|
||||
* match is at least as specific (the same {@code /*}, or {@code /es/*} beside {@code /*}). Only the page editor
|
||||
* uses it, to say that the other language's entry does not reach this page and which key would.
|
||||
*/
|
||||
static OtherLanguageEntry otherLanguageEntry(Map<String, Object> cfg, String path, SiteView site) {
|
||||
String prefix = path == null || site == null ? null : languagePrefix(path, site);
|
||||
if (prefix == null) {
|
||||
return null;
|
||||
}
|
||||
String stripped = path.length() <= prefix.length() + 1 ? "/" : path.substring(prefix.length());
|
||||
Map<String, Object> patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", ""));
|
||||
String base = PageSchemaConfig.matchingPattern(patterns, stripped);
|
||||
String own = PageSchemaConfig.matchingPattern(patterns, path);
|
||||
if (base == null || (own != null && specificity(own, path) >= specificity(base, stripped))) {
|
||||
return null; // nothing to say, or this page's own match is at least as specific (/es/*, /*)
|
||||
}
|
||||
return new OtherLanguageEntry(base, base.equals(stripped) ? path : prefix + base);
|
||||
}
|
||||
|
||||
/** How specific a matching pattern is: an exact key above any prefix, a longer prefix above a shorter one. */
|
||||
private static int specificity(String pattern, String path) {
|
||||
return pattern.equals(path) ? Integer.MAX_VALUE : pattern.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* The leading {@code /<language>} of {@code path} when that language is one of the site's languages other than
|
||||
* the default ({@code /es} for {@code /es/faq} and for {@code /es}); {@code null} otherwise.
|
||||
*/
|
||||
static String languagePrefix(String path, SiteView site) {
|
||||
for (Locale locale : site.locales()) {
|
||||
if (locale.equals(site.defaultLocale())) {
|
||||
continue; // the default language's pages are unprefixed
|
||||
}
|
||||
String prefix = "/" + locale.getLanguage();
|
||||
if (path.equals(prefix) || path.startsWith(prefix + "/")) {
|
||||
return prefix;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* The absolute base of the crawl-surface endpoints (sitemap, robots.txt, llms.txt). The URLs themselves come from
|
||||
* the host's content listing ({@code CatalogEntry} / {@code LocalizedUrl}, root-relative) — this plugin never
|
||||
* applies the URL scheme itself; it only prefixes the origin.
|
||||
*/
|
||||
final class PageUrls {
|
||||
|
||||
private PageUrls() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The site's absolute base ({@code scheme://host[:port]}, no trailing slash): the site view's base URL — which
|
||||
* the host fills with the configured base URL, else {@code https://<the site's first host name>} — and, for a
|
||||
* site with neither (a host-less catch-all site), the request's <b>trusted origin</b>
|
||||
* ({@link RouteRequest#origin()}: the scheme and host as the host's trusted-proxy gate leaves them — a configured
|
||||
* proxy's forwarded values applied, raw values otherwise). Empty only when none is known.
|
||||
*
|
||||
* <p>Until 2.0.0 that last fallback was built from the raw {@code Host} header with the scheme read from
|
||||
* {@code X-Forwarded-Proto} — which the kernel does not pass to plugins — or else <i>guessed</i> as
|
||||
* {@code https}. The origin replaces both: no header is trusted unless the operator trusted the proxy that set
|
||||
* it, and the scheme is the one the request actually arrived on.
|
||||
*/
|
||||
static String base(SiteView site, RouteRequest req) {
|
||||
String configured = site.baseUrl();
|
||||
String base = (configured != null && !configured.isBlank()) ? configured.trim() : req.origin().trim();
|
||||
return base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits schema.org {@code Person} node(s) from a {@code content.schema} entry — a {@code people:} list yields
|
||||
* one {@code Person} per member (name/jobTitle/image/sameAs, {@code worksFor}→Organization); with no list, a
|
||||
* single {@code Person} is built from the entry's own fields. A person with no name is skipped.
|
||||
*/
|
||||
final class PersonSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Person";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
List<Map<String, Object>> people = Schemas.maps(cfg, "people");
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
if (people.isEmpty()) {
|
||||
Map<String, Object> single = person(cfg, sc);
|
||||
if (single != null) {
|
||||
out.add(single);
|
||||
}
|
||||
} else {
|
||||
for (Map<String, Object> member : people) {
|
||||
Map<String, Object> node = person(member, sc);
|
||||
if (node != null) {
|
||||
out.add(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> person(Map<String, Object> p, SchemaContext sc) {
|
||||
String name = Schemas.str(p, "name");
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> node = Ld.node("Person", null);
|
||||
Ld.put(node, "name", name);
|
||||
Ld.put(node, "jobTitle", Schemas.str(p, "jobTitle"));
|
||||
Ld.putList(node, "image", Schemas.absolute(Schemas.strings(p, "image"), sc.base()));
|
||||
Ld.putList(node, "sameAs", Schemas.strings(p, "sameAs"));
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(node, "worksFor", sc.organizationId());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code Product} (with a nested {@code Offer}) from a product page's {@code content.schema}
|
||||
* entry — name/description/image/sku, {@code brand}→Organization, and {@code offers}(price/currency/availability/
|
||||
* url). Name and description fall back to the page's title/description. The node is {@code mainEntityOfPage}-linked
|
||||
* to this page's {@code WebPage}.
|
||||
*/
|
||||
final class ProductSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Product";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String name = Schemas.str(cfg, "name", ctx.page().title());
|
||||
if (name == null || name.isBlank()) {
|
||||
return List.of(); // nothing substantive to say — don't emit a bare {@type: Product} node
|
||||
}
|
||||
Map<String, Object> product = Ld.node("Product", null);
|
||||
Ld.put(product, "name", name);
|
||||
Ld.put(product, "description", Schemas.str(cfg, "description", ctx.page().description()));
|
||||
Ld.putList(product, "image", Schemas.absolute(Schemas.strings(cfg, "image"), sc.base()));
|
||||
Ld.put(product, "sku", Schemas.str(cfg, "sku"));
|
||||
Ld.ref(product, "mainEntityOfPage", sc.webpageId());
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(product, "brand", sc.organizationId());
|
||||
}
|
||||
String price = Schemas.str(cfg, "price");
|
||||
if (price != null) {
|
||||
Map<String, Object> offer = new LinkedHashMap<>();
|
||||
offer.put("@type", "Offer");
|
||||
offer.put("price", price);
|
||||
offer.put("priceCurrency", Schemas.str(cfg, "currency", "USD"));
|
||||
String availability = Schemas.str(cfg, "availability");
|
||||
if (availability != null) {
|
||||
offer.put("availability",
|
||||
availability.startsWith("http") ? availability : "https://schema.org/" + availability);
|
||||
}
|
||||
offer.put("url", sc.canonical());
|
||||
product.put("offers", offer);
|
||||
}
|
||||
return List.of(product);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* SEO+/GEO — serves a per-site <b>{@code /robots.txt}</b>. The kernel deliberately does <b>not</b> own this
|
||||
* route (an {@code EndpointContributor} route has exactly one owner, and a kernel handler reading a plugin's
|
||||
* config would hard-code a plugin id into the core); the discoverability plugin owns it because the two things
|
||||
* a rich {@code robots.txt} needs are already the plugin's: the {@code Sitemap:} line points at the plugin's own
|
||||
* {@code /sitemap.xml} (and is emitted only when that surface is enabled, so it never points at a {@code 404}),
|
||||
* and the AI/LLM-crawler policy is a GEO concern that sits beside {@code llms.txt}.
|
||||
*
|
||||
* <p>The body is an <b>explicit</b> named AI/LLM-crawler group (always emitted, so the AI posture is stated
|
||||
* rather than merely implied by the wildcard), then a general {@code User-agent: *} group (allow-all, plus any
|
||||
* tenant {@code robots.extra-disallow} paths), followed by the {@code Sitemap:} line. On the allow posture the
|
||||
* AI group mirrors the general group's exclusions (a most-specific match wins in robots.txt, so a bare
|
||||
* {@code Allow: /} would let those agents bypass the tenant's own Disallow paths); on opt-out it is a clean
|
||||
* {@code Disallow: /}. The AI posture is per-tenant ({@code robots.ai-policy}: {@code allow}/{@code disallow}/
|
||||
* {@code inherit}) falling back to the app-level default ({@code robots.ai-default}, GEO-friendly {@code allow}).
|
||||
* {@code robots.custom} is a full-body escape hatch that replaces the generated output verbatim.
|
||||
*
|
||||
* <p>An install <b>without</b> this plugin serves no {@code /robots.txt} at all, which crawlers treat as
|
||||
* allow-all — functionally identical to the old permissive kernel default.
|
||||
*/
|
||||
public class RobotsTxtEndpoint implements EndpointContributor {
|
||||
|
||||
/**
|
||||
* AI/LLM crawler user-agents grouped under one {@code Disallow: /} when a site opts out of AI crawling.
|
||||
* These are training/answer-engine agents kept distinct from the classic search crawlers (e.g.
|
||||
* {@code Google-Extended} ≠ {@code Googlebot}, {@code Applebot-Extended} ≠ {@code Applebot}), so opting out
|
||||
* of AI never deindexes the site from web search.
|
||||
*
|
||||
* <p><b>This list goes stale, and it fails silently when it does.</b> Operators publish, rename and retire
|
||||
* agent names on their own schedule; an agent missing from this list is simply <i>not covered</i> by an
|
||||
* opt-out, and nothing anywhere reports that — the site owner believes they opted out and did not. That is
|
||||
* not hypothetical: {@code Claude-User} and {@code Claude-SearchBot} were absent from the shipped 1.3.0 list
|
||||
* while {@code ClaudeBot} was present, so a site set to {@code disallow} was still reachable by two of the
|
||||
* three Anthropic agents.
|
||||
*
|
||||
* <p>Because a compile-time constant cannot be corrected without a plugin release, the effective list is
|
||||
* this constant <b>plus</b> the app-level {@code robots.ai-agents-extra} setting
|
||||
* ({@link DiscoverabilityProperties.Robots#getAiAgentsExtra()}) — so an operator can cover a newly announced
|
||||
* agent the same day it is announced. See {@link #aiAgents()}.
|
||||
*
|
||||
* <p>Each agent is also assigned an {@link AiClass}, so a site can decline <b>training</b> while staying
|
||||
* citable by answer engines — see {@link #AI_CLASSES}.
|
||||
*/
|
||||
static final List<String> AI_CRAWLERS = List.of(
|
||||
"GPTBot", "OAI-SearchBot", "ChatGPT-User", // OpenAI: training / retrieval / user-triggered
|
||||
"ClaudeBot", "Claude-SearchBot", "Claude-User", // Anthropic: training / retrieval / user-triggered
|
||||
"anthropic-ai", "Claude-Web", // Anthropic legacy names, kept: harmless if retired
|
||||
"Google-Extended", // Google (Gemini training; NOT Googlebot)
|
||||
"PerplexityBot", "Perplexity-User", // Perplexity: retrieval / user-triggered
|
||||
"CCBot", // Common Crawl (feeds many LLMs)
|
||||
"Bytespider", // ByteDance
|
||||
"Amazonbot", // Amazon
|
||||
"Applebot-Extended", // Apple (AI training opt-out; NOT Applebot)
|
||||
"Meta-ExternalAgent", "FacebookBot", // Meta
|
||||
"cohere-ai", "Diffbot", "Omgilibot", "Timpibot", "YouBot");
|
||||
|
||||
/**
|
||||
* What an AI agent is <i>for</i>. The three roles the operators themselves distinguish, and the reason a
|
||||
* single AI switch was not enough: they carry opposite consequences for a site.
|
||||
*/
|
||||
enum AiClass {
|
||||
|
||||
/** Collecting text to train a model. Declining costs the site nothing it can see. */
|
||||
TRAINING("training"),
|
||||
|
||||
/** Building an index an answer engine cites from. Declining removes the site from those answers. */
|
||||
RETRIEVAL("retrieval"),
|
||||
|
||||
/** Fetching one page because a person asked about it. Declining breaks a visit somebody initiated. */
|
||||
USER("user");
|
||||
|
||||
private final String key;
|
||||
|
||||
AiClass(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
/** The token used in setting keys and in operator-supplied {@code class=Agent} entries. */
|
||||
String key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
static AiClass of(String token) {
|
||||
for (AiClass value : values()) {
|
||||
if (value.key.equalsIgnoreCase(token)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Which class each built-in agent belongs to.
|
||||
*
|
||||
* <h2>How these were assigned, and where the uncertainty is</h2>
|
||||
* The triads are the operators' own published distinction and are not in doubt: OpenAI's
|
||||
* {@code GPTBot}/{@code OAI-SearchBot}/{@code ChatGPT-User}, Anthropic's
|
||||
* {@code ClaudeBot}/{@code Claude-SearchBot}/{@code Claude-User}, Perplexity's
|
||||
* {@code PerplexityBot}/{@code Perplexity-User}. So are the training-only opt-out agents that exist
|
||||
* precisely to be separable from their search siblings — {@code Google-Extended} (not {@code Googlebot}),
|
||||
* {@code Applebot-Extended} (not {@code Applebot}).
|
||||
*
|
||||
* <p>The rest are a best-effort reading of each operator's own description, and some genuinely serve more
|
||||
* than one purpose. <b>An agent whose role is ambiguous is placed in {@link AiClass#TRAINING}</b>, because
|
||||
* that is the class a site opting out is most likely to mean, and a misplaced agent should fail toward
|
||||
* honouring the site's stated intent rather than around it.
|
||||
*
|
||||
* <p>An agent absent from this map is governed by the site's overall {@code robots.ai-policy} — the
|
||||
* behaviour every site had before classes existed, so an operator-added name keeps working unchanged.
|
||||
*/
|
||||
static final Map<String, AiClass> AI_CLASSES = Map.ofEntries(
|
||||
Map.entry("GPTBot", AiClass.TRAINING),
|
||||
Map.entry("OAI-SearchBot", AiClass.RETRIEVAL),
|
||||
Map.entry("ChatGPT-User", AiClass.USER),
|
||||
Map.entry("ClaudeBot", AiClass.TRAINING),
|
||||
Map.entry("Claude-SearchBot", AiClass.RETRIEVAL),
|
||||
Map.entry("Claude-User", AiClass.USER),
|
||||
Map.entry("anthropic-ai", AiClass.TRAINING),
|
||||
Map.entry("Claude-Web", AiClass.TRAINING),
|
||||
Map.entry("Google-Extended", AiClass.TRAINING),
|
||||
Map.entry("PerplexityBot", AiClass.RETRIEVAL),
|
||||
Map.entry("Perplexity-User", AiClass.USER),
|
||||
Map.entry("CCBot", AiClass.TRAINING),
|
||||
Map.entry("Bytespider", AiClass.TRAINING),
|
||||
Map.entry("Amazonbot", AiClass.TRAINING),
|
||||
Map.entry("Applebot-Extended", AiClass.TRAINING),
|
||||
Map.entry("Meta-ExternalAgent", AiClass.TRAINING),
|
||||
Map.entry("FacebookBot", AiClass.TRAINING),
|
||||
Map.entry("cohere-ai", AiClass.TRAINING),
|
||||
Map.entry("Diffbot", AiClass.TRAINING),
|
||||
Map.entry("Omgilibot", AiClass.TRAINING),
|
||||
Map.entry("Timpibot", AiClass.TRAINING),
|
||||
Map.entry("YouBot", AiClass.RETRIEVAL));
|
||||
|
||||
/**
|
||||
* One AI agent as it will be emitted: its name, and the class governing it ({@code null} = the site's
|
||||
* overall policy).
|
||||
*
|
||||
* <p>Name <b>and</b> class together, rather than a name list beside a shared lookup map, because
|
||||
* {@code /robots.txt} is a public route served on many threads at once: a map rebuilt per request would
|
||||
* let one thread read it mid-rebuild and emit an agent under a policy the operator never chose. There is
|
||||
* no shared mutable state here at all — the classification is derived per call and thrown away.
|
||||
*/
|
||||
record Agent(String name, AiClass declaredClass) {
|
||||
}
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RobotsTxtEndpoint.class);
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final DiscoverabilityProperties properties;
|
||||
|
||||
public RobotsTxtEndpoint(PluginSettings settings, DiscoverabilityProperties properties) {
|
||||
this.settings = settings;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/robots";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// Not indexable, not in sitemap, cacheable (content is per-host stable).
|
||||
return List.of(new Route("GET", "/robots.txt", Realm.TENANT, new SurfacePosture(false, false, true)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
|
||||
// Full-body override — replaces the generated output entirely.
|
||||
String custom = SiteConfig.str(cfg, "robots.custom", "");
|
||||
if (!custom.isBlank()) {
|
||||
return RouteResponse.text(200, ensureTrailingNewline(custom));
|
||||
}
|
||||
|
||||
String base = PageUrls.base(req.site(), req);
|
||||
StringBuilder body = new StringBuilder(256);
|
||||
List<String> extra = extraDisallow(cfg);
|
||||
|
||||
// Named AI/LLM-crawler group(s), ALWAYS emitted so the crawl posture is EXPLICIT rather than implied by
|
||||
// the wildcard (a GEO signal). On opt-out a group is a clean Disallow: /. On allow it MIRRORS the
|
||||
// general group (Allow: / + the same tenant Disallow paths) — a most-specific match wins in robots.txt,
|
||||
// so an explicit Allow: / with no exclusions would otherwise let these agents ignore the site's own
|
||||
// extra Disallows.
|
||||
//
|
||||
// ONE group when every class resolves the same way — which is every site that has not set a per-class
|
||||
// override, so their robots.txt is byte-identical to before classes existed. Splitting a site that made
|
||||
// no such choice into three identical groups would churn every crawler's copy to say the same thing.
|
||||
appendAiGroups(body, cfg, extra);
|
||||
|
||||
// The general group: allow-all, plus any tenant-declared extra Disallow paths.
|
||||
body.append("User-agent: *\n");
|
||||
appendAllowWithExclusions(body, extra);
|
||||
|
||||
// Sitemap reference — only when the sitemap surface is actually served (matches SitemapEndpoint's gate).
|
||||
if (!base.isBlank() && SiteConfig.bool(cfg, "sitemap.enabled", true)) {
|
||||
body.append("\nSitemap: ").append(base).append("/sitemap.xml\n");
|
||||
}
|
||||
|
||||
return RouteResponse.text(200, body.toString());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Writes the AI-crawler group(s): one per distinct policy across the three classes.
|
||||
*
|
||||
* <p>A site that has expressed no per-class preference gets exactly the single group it always got —
|
||||
* identical bytes, identical agent order. Only a site that actually distinguishes the classes pays the
|
||||
* extra groups.
|
||||
*/
|
||||
private void appendAiGroups(StringBuilder body, Map<String, Object> cfg, List<String> extra) {
|
||||
boolean training = aiDisallowed(cfg, AiClass.TRAINING);
|
||||
boolean retrieval = aiDisallowed(cfg, AiClass.RETRIEVAL);
|
||||
boolean user = aiDisallowed(cfg, AiClass.USER);
|
||||
List<Agent> agents = aiAgentsClassified();
|
||||
|
||||
if (training == retrieval && retrieval == user) {
|
||||
appendAiGroup(body, agents.stream().map(Agent::name).toList(), training, extra);
|
||||
return;
|
||||
}
|
||||
// Split. Unclassified agents (operator additions with no class= prefix) follow the site's overall
|
||||
// policy, exactly as they did before classes existed — inventing a class for a name we do not
|
||||
// recognise would silently apply a policy the operator never chose.
|
||||
for (AiClass aiClass : AiClass.values()) {
|
||||
List<String> ofClass = agents.stream()
|
||||
.filter(a -> classOf(a) == aiClass).map(Agent::name).toList();
|
||||
if (!ofClass.isEmpty()) {
|
||||
appendAiGroup(body, ofClass, aiDisallowed(cfg, aiClass), extra);
|
||||
}
|
||||
}
|
||||
List<String> unclassified = agents.stream()
|
||||
.filter(a -> classOf(a) == null).map(Agent::name).toList();
|
||||
if (!unclassified.isEmpty()) {
|
||||
appendAiGroup(body, unclassified, aiDisallowed(cfg), extra);
|
||||
}
|
||||
}
|
||||
|
||||
/** One {@code User-agent:} block: the names, then either {@code Disallow: /} or the mirrored allow. */
|
||||
private static void appendAiGroup(StringBuilder body, List<String> agents, boolean disallowed,
|
||||
List<String> extra) {
|
||||
for (String agent : agents) {
|
||||
body.append("User-agent: ").append(agent).append('\n');
|
||||
}
|
||||
if (disallowed) {
|
||||
body.append("Disallow: /\n\n");
|
||||
} else {
|
||||
appendAllowWithExclusions(body, extra);
|
||||
body.append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/** The class of {@code agent} — its declared {@code class=} prefix if any, else the built-in map. */
|
||||
private static AiClass classOf(Agent agent) {
|
||||
return agent.declaredClass() != null ? agent.declaredClass() : AI_CLASSES.get(agent.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code aiClass} is disallowed for this site: its own override if set, else the site's overall
|
||||
* {@code robots.ai-policy}, else the app-level default.
|
||||
*
|
||||
* <p>The per-class key is {@code robots.ai-training} / {@code -retrieval} / {@code -user} — deliberately
|
||||
* NOT {@code robots.ai-policy.training}, which would make one key both a scalar and a map prefix and is
|
||||
* the kind of shape that parses today and breaks the first time the config is read as a tree.
|
||||
*/
|
||||
private boolean aiDisallowed(Map<String, Object> cfg, AiClass aiClass) {
|
||||
String policy = SiteConfig.str(cfg, "robots.ai-" + aiClass.key(), "inherit").trim();
|
||||
if (policy.equalsIgnoreCase("allow")) {
|
||||
return false;
|
||||
}
|
||||
if (policy.equalsIgnoreCase("disallow")) {
|
||||
return true;
|
||||
}
|
||||
return aiDisallowed(cfg); // inherit → the site's overall AI policy
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in {@link #AI_CRAWLERS} plus any operator-added names from {@code robots.ai-agents-extra},
|
||||
* de-duplicated case-insensitively and sanitised.
|
||||
*
|
||||
* <p>Sanitisation is not cosmetic: an operator-supplied value lands in a {@code User-agent:} line, so a name
|
||||
* containing CR/LF would let one setting inject arbitrary robots directives into every tenant's file — the
|
||||
* same injection this class already closes for tenant {@code extra-disallow} paths. Whitespace and colons are
|
||||
* stripped for the same reason (a colon would forge a second directive on one line).
|
||||
*
|
||||
* <p>Order is stable: built-ins first in declaration order, then operator additions in the order given, so
|
||||
* the emitted file diffs cleanly between restarts.
|
||||
*/
|
||||
List<String> aiAgents() {
|
||||
return aiAgentsClassified().stream().map(Agent::name).toList();
|
||||
}
|
||||
|
||||
/** As {@link #aiAgents()}, but each name paired with the class its entry declared (if any). */
|
||||
List<Agent> aiAgentsClassified() {
|
||||
List<Agent> agents = new ArrayList<>();
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (String a : AI_CRAWLERS) {
|
||||
agents.add(new Agent(a, null));
|
||||
seen.add(a.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
for (String raw : properties.getRobots().getAiAgentsExtra()) {
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
// An entry may declare which class the agent belongs to: `training=SomeNewBot`. Without it the
|
||||
// agent follows the site's overall AI policy, which is what every operator addition did before
|
||||
// classes existed — so nothing already configured changes meaning.
|
||||
String value = raw;
|
||||
AiClass declared = null;
|
||||
int eq = value.indexOf('=');
|
||||
if (eq > 0) {
|
||||
String token = value.substring(0, eq).trim();
|
||||
declared = AiClass.of(token);
|
||||
// A misspelt class is reported and the AGENT is still honoured, unclassified. Folding the bad
|
||||
// prefix into the name instead would produce a user-agent token that matches nothing, and the
|
||||
// operator would believe they had covered an agent they had not — the exact silent failure
|
||||
// this whole list exists to warn about.
|
||||
if (declared == null) {
|
||||
log.warn("robots.ai-agents-extra entry '{}' names an unknown AI class '{}' — the agent is "
|
||||
+ "still listed, but it follows the site's overall AI policy. Valid classes: {}.",
|
||||
raw, token, java.util.Arrays.stream(AiClass.values()).map(AiClass::key).toList());
|
||||
}
|
||||
value = value.substring(eq + 1);
|
||||
}
|
||||
String clean = value.replaceAll("[\\r\\n:=\\s]", "").trim();
|
||||
if (!clean.isEmpty() && seen.add(clean.toLowerCase(Locale.ROOT))) {
|
||||
agents.add(new Agent(clean, declared));
|
||||
}
|
||||
}
|
||||
return List.copyOf(agents);
|
||||
}
|
||||
|
||||
/** True when this site opts out of AI/LLM crawlers: per-tenant {@code robots.ai-policy}, else the app default. */
|
||||
private boolean aiDisallowed(Map<String, Object> cfg) {
|
||||
String policy = SiteConfig.str(cfg, "robots.ai-policy", "inherit").trim();
|
||||
if (policy.equalsIgnoreCase("allow")) {
|
||||
return false;
|
||||
}
|
||||
if (policy.equalsIgnoreCase("disallow")) {
|
||||
return true;
|
||||
}
|
||||
return "disallow".equalsIgnoreCase(properties.getRobots().getAiDefault()); // inherit → app-level default
|
||||
}
|
||||
|
||||
/** Writes {@code Allow: /} followed by one {@code Disallow:} line per tenant exclusion path. */
|
||||
private static void appendAllowWithExclusions(StringBuilder body, List<String> extra) {
|
||||
body.append("Allow: /\n");
|
||||
for (String path : extra) {
|
||||
body.append("Disallow: ").append(path).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/** Tenant extra Disallow paths, each normalized to start with {@code /} and stripped of CR/LF. */
|
||||
private static List<String> extraDisallow(Map<String, Object> cfg) {
|
||||
List<String> paths = new ArrayList<>();
|
||||
for (String p : SiteConfig.list(cfg, "robots.extra-disallow")) {
|
||||
// Strip CR/LF so one list entry can never inject extra robots lines/directives.
|
||||
String clean = p.replaceAll("[\\r\\n]", "").trim();
|
||||
if (!clean.isEmpty()) {
|
||||
paths.add(clean.startsWith("/") ? clean : "/" + clean);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
private static String ensureTrailingNewline(String s) {
|
||||
return s.endsWith("\n") ? s : s + "\n";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.robots");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The immutable inputs a {@link SchemaType} needs beyond the {@link mx.quest.runway.spi.model.HeadContext}: the
|
||||
* resolved site {@code base} and this page's {@code path}/{@code canonical}, whether it is a homepage, whether
|
||||
* the site declares an Organization, the shared {@code @id}s (so a typed node cross-references the
|
||||
* {@code WebPage}/{@code Organization} by reference rather than redefining them), the current {@code locale},
|
||||
* and the matched per-page config subtree parsed from {@code content.schema}.
|
||||
*
|
||||
* @param base the site base URL (no trailing slash)
|
||||
* @param canonical this page's absolute canonical URL
|
||||
* @param path this page's path relative to base (starts with {@code /})
|
||||
* @param home whether this page is a homepage
|
||||
* @param hasOrg whether the site has a configured Organization (so {@code publisher}/{@code brand} refs apply)
|
||||
* @param websiteId the {@code @id} of the graph's {@code WebSite} node
|
||||
* @param webpageId the {@code @id} of the graph's {@code WebPage} node (for {@code mainEntityOfPage}/{@code isPartOf})
|
||||
* @param organizationId the {@code @id} of the graph's {@code Organization} node ({@code null}/unused when absent)
|
||||
* @param pageConfig the matched {@code content.schema} entry (its {@code type} + type-specific fields)
|
||||
* @param locale the resolved request locale
|
||||
*/
|
||||
record SchemaContext(String base, String canonical, String path, boolean home, boolean hasOrg,
|
||||
String websiteId, String webpageId, String organizationId,
|
||||
Map<String, Object> pageConfig, Locale locale) {
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* A plugin-internal content type that maps a tenant-declared page/section type (e.g. {@code FAQPage},
|
||||
* {@code Product}) to schema.org JSON-LD {@code @graph} node(s). This is the extension seam behind item 5's
|
||||
* type-aware structured data: {@link StructuredDataHead} holds a registry of these keyed by {@link #key()} and,
|
||||
* for a page whose path matches a {@code content.schema} entry, appends {@link #nodes(HeadContext, SchemaContext)}
|
||||
* to the graph — with zero type-aware branching in the contributor itself (capability/registry dispatch, per the
|
||||
* host's capability-driven-SPI principle).
|
||||
*
|
||||
* <p>Implementations are pure and stateless: they read the immutable {@link HeadContext} and the matched
|
||||
* per-page config carried by {@link SchemaContext}, and return plain node maps that reference the shared
|
||||
* {@code #webpage}/{@code #organization} entities by {@code @id}. Content <em>values</em> are tenant-owned (they
|
||||
* come from the config); the plugin owns only the typing mechanism.
|
||||
*/
|
||||
interface SchemaType {
|
||||
|
||||
/** The type token a tenant declares in {@code content.schema} (e.g. {@code "FAQPage"}); the registry key. */
|
||||
String key();
|
||||
|
||||
/**
|
||||
* The schema.org node(s) for this typed page, or an empty list when the config has nothing to emit.
|
||||
*
|
||||
* @param ctx the immutable head context (site, page, locale, canonical)
|
||||
* @param sc the resolved schema context (base, path, shared {@code @id}s, the matched per-page config)
|
||||
*/
|
||||
List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc);
|
||||
|
||||
/**
|
||||
* Whether a block declaring {@code token} (one of the tokens this type is registered under) describes the page
|
||||
* itself — its own {@code #webpage} node's {@code @type} — rather than adding a separate entity. Such a block
|
||||
* replaces the site's Default page type for the pages it matches, and the head then calls
|
||||
* {@link #describePage} instead of {@link #nodes}. Until 2.2.0 every block added a node, so a page declared
|
||||
* {@code Article} carried two Article nodes when the site default was Article as well.
|
||||
*/
|
||||
default boolean describesPage(String token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a block that {@linkplain #describesPage describes the page}: adds this type's properties to the page's own
|
||||
* node (whose {@code @type} the caller has already set to the declared token) and appends any separate nodes the
|
||||
* type needs to {@code graph}.
|
||||
*
|
||||
* @param page the page's own node, mutable
|
||||
* @param graph the graph being built, for nodes the page refers to by {@code @id}
|
||||
*/
|
||||
default void describePage(Map<String, Object> page, HeadContext ctx, SchemaContext sc,
|
||||
List<Map<String, Object>> graph) {
|
||||
}
|
||||
|
||||
/**
|
||||
* What a block declaring {@code token} lacks to publish what it is for, or {@code null} when it lacks nothing:
|
||||
* an {@code FAQPage} with no complete question, a list with no item that has a {@code url}. Such a block breaks
|
||||
* nothing, so the page is still served; the settings form's Per-page types check and the page editor report it,
|
||||
* since until 2.2.0 nobody saw it. A key that has a default (a product's name falls back to the page title) is
|
||||
* not a gap.
|
||||
*/
|
||||
default Gap gap(String token, Map<String, Object> block) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gap: the message code and its English text, whose {@code {0}} is the type token.
|
||||
*
|
||||
* @param code the message key, resolved in the operator's UI language
|
||||
* @param fallback the English text
|
||||
*/
|
||||
record Gap(String code, String fallback) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Null-safe readers over the parsed {@code content.schema} entry maps (nested {@code Map}/{@code List} produced
|
||||
* by the YAML parser). Shared by the {@link SchemaType} implementations so each stays a small pure mapper.
|
||||
*/
|
||||
final class Schemas {
|
||||
|
||||
private Schemas() {
|
||||
}
|
||||
|
||||
/** The string value of {@code key}, or {@code null} when absent/blank. */
|
||||
static String str(Map<String, Object> map, String key) {
|
||||
Object v = map == null ? null : map.get(key);
|
||||
if (v == null) {
|
||||
return null;
|
||||
}
|
||||
String s = v.toString();
|
||||
return s.isBlank() ? null : s;
|
||||
}
|
||||
|
||||
/** The string value of {@code key}, or {@code def} when absent/blank. */
|
||||
static String str(Map<String, Object> map, String key, String def) {
|
||||
String v = str(map, key);
|
||||
return v == null ? def : v;
|
||||
}
|
||||
|
||||
/** The list-of-maps value of {@code key} (e.g. {@code faq}, {@code locations}, {@code people}); never null. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<Map<String, Object>> maps(Map<String, Object> map, String key) {
|
||||
Object v = map == null ? null : map.get(key);
|
||||
if (!(v instanceof List<?> list)) {
|
||||
return List.of();
|
||||
}
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Object o : list) {
|
||||
if (o instanceof Map<?, ?> m) {
|
||||
out.add((Map<String, Object>) m);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The list-of-strings value of {@code key} (a scalar is treated as a one-element list); never null. */
|
||||
static List<String> strings(Map<String, Object> map, String key) {
|
||||
Object v = map == null ? null : map.get(key);
|
||||
if (v instanceof List<?> list) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (Object o : list) {
|
||||
if (o != null && !o.toString().isBlank()) {
|
||||
out.add(o.toString());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
return List.of(s);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code url} made absolute against the site {@code base} when it is root-relative ({@code /img/a.png}); any
|
||||
* other value as given. JSON-LD URLs must be absolute; until 2.2.0 a root-relative image was emitted as written,
|
||||
* which search engines reject.
|
||||
*/
|
||||
static String absolute(String url, String base) {
|
||||
return url != null && url.startsWith("/") && !url.startsWith("//") && base != null && !base.isBlank()
|
||||
? base + url : url;
|
||||
}
|
||||
|
||||
/** {@link #absolute} applied to each URL of a list. */
|
||||
static List<String> absolute(List<String> urls, String base) {
|
||||
List<String> out = new ArrayList<>(urls.size());
|
||||
for (String url : urls) {
|
||||
out.add(absolute(url, base));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* Emits a schema.org {@code Service} (or the entry's declared subtype, e.g. {@code ProfessionalService}) from a
|
||||
* service page's {@code content.schema} entry: name/description/{@code serviceType}/{@code areaServed}/{@code offers},
|
||||
* with {@code provider}→Organization and {@code mainEntityOfPage}→WebPage. Name and description fall back to the
|
||||
* page's title/description. An {@code offers:} list turns a pricing page's tiers into machine-readable
|
||||
* {@code Offer}s (a recurring tier declares {@code unit:} → a {@code UnitPriceSpecification}, e.g. per month).
|
||||
*/
|
||||
final class ServiceSchema implements SchemaType {
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "Service";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
Map<String, Object> cfg = sc.pageConfig();
|
||||
String name = Schemas.str(cfg, "name", ctx.page().title());
|
||||
if (name == null || name.isBlank()) {
|
||||
return List.of(); // nothing substantive to say — don't emit a bare {@type: Service} node
|
||||
}
|
||||
String type = Schemas.str(cfg, "type", "Service"); // Service | ProfessionalService
|
||||
Map<String, Object> service = Ld.node(type, null);
|
||||
Ld.put(service, "name", name);
|
||||
Ld.put(service, "description", Schemas.str(cfg, "description", ctx.page().description()));
|
||||
Ld.put(service, "serviceType", Schemas.str(cfg, "serviceType"));
|
||||
Ld.putList(service, "areaServed", Schemas.strings(cfg, "areaServed"));
|
||||
List<Map<String, Object>> offers = offers(cfg);
|
||||
if (!offers.isEmpty()) {
|
||||
service.put("offers", offers);
|
||||
}
|
||||
Ld.ref(service, "mainEntityOfPage", sc.webpageId());
|
||||
if (sc.hasOrg()) {
|
||||
Ld.ref(service, "provider", sc.organizationId());
|
||||
}
|
||||
return List.of(service);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code offers:} list mapped to schema.org {@code Offer} nodes. An offer needs a {@code price}; a
|
||||
* {@code unit:} (e.g. {@code month}) makes it a recurring {@code UnitPriceSpecification}, else a flat
|
||||
* {@code price}/{@code priceCurrency}. Currency defaults to USD. Offers without a price are skipped.
|
||||
*/
|
||||
private static List<Map<String, Object>> offers(Map<String, Object> cfg) {
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Map<String, Object> o : Schemas.maps(cfg, "offers")) {
|
||||
String price = Schemas.str(o, "price");
|
||||
if (price == null) {
|
||||
continue;
|
||||
}
|
||||
String currency = Schemas.str(o, "currency", "USD");
|
||||
String unit = Schemas.str(o, "unit");
|
||||
Map<String, Object> offer = new LinkedHashMap<>();
|
||||
offer.put("@type", "Offer");
|
||||
Ld.put(offer, "name", Schemas.str(o, "name"));
|
||||
if (unit != null) {
|
||||
Map<String, Object> spec = new LinkedHashMap<>();
|
||||
spec.put("@type", "UnitPriceSpecification");
|
||||
spec.put("price", price);
|
||||
spec.put("priceCurrency", currency);
|
||||
spec.put("unitText", unit);
|
||||
offer.put("priceSpecification", spec);
|
||||
} else {
|
||||
offer.put("price", price);
|
||||
offer.put("priceCurrency", currency);
|
||||
}
|
||||
out.add(offer);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
|
||||
/**
|
||||
* A schema.org page type that only names what the page is — {@code AboutPage}, {@code ContactPage},
|
||||
* {@code WebPage} and the like — with no properties of its own. Declared in {@code content.schema}, it becomes the
|
||||
* page's own {@code @type}, replacing the site's Default page type; so a site whose default is {@code Article} can
|
||||
* say its contact page is a {@code ContactPage}, and a single page can go back to a plain {@code WebPage}.
|
||||
*/
|
||||
final class SimplePageType implements SchemaType {
|
||||
|
||||
/**
|
||||
* The page types this class serves, each registered as its own key. Not {@code ProfilePage} or {@code QAPage}:
|
||||
* Google requires a {@code mainEntity} on both (the person; the one user-submitted question with its answers),
|
||||
* which a type with no keys cannot give, so declaring them would only earn a Search Console error. Site-authored
|
||||
* questions are an {@code FAQPage}.
|
||||
*/
|
||||
static final List<String> KEYS = List.of("WebPage", "AboutPage", "ContactPage", "ItemPage", "SearchResultsPage");
|
||||
|
||||
private final String key;
|
||||
|
||||
SimplePageType(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> nodes(HeadContext ctx, SchemaContext sc) {
|
||||
return List.of(); // describes the page itself; see describesPage
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean describesPage(String token) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Null/absent-safe typed readers over this plugin's effective per-site settings map — the
|
||||
* {@code SettingsView.values()} that {@code PluginSettings.site(siteId)} returns: the descriptor's
|
||||
* {@code siteSettings} defaults overlaid by the values stored for the site, each already coerced by the host to
|
||||
* its declared type (boolean→Boolean, int→Long, list→List<String>, enum/string/text→String).
|
||||
*
|
||||
* <p>Kept instead of the {@code SettingsView} accessors on purpose: these are the readers 1.x used, and their
|
||||
* lenient rules for a hand-edited value (any string other than true/on/yes/1 reads as {@code false}; a blank value
|
||||
* falls back) are part of what an unchanged site renders. The code fallbacks passed in equal the descriptor's
|
||||
* declared defaults ({@code DescriptorDefaultsTest} proves the rendered surfaces do not change when the defaults
|
||||
* are applied), so they matter only for a key the descriptor declares without a default.
|
||||
*/
|
||||
final class SiteConfig {
|
||||
|
||||
private SiteConfig() {
|
||||
}
|
||||
|
||||
static boolean bool(Map<String, Object> cfg, String key, boolean def) {
|
||||
Object v = cfg.get(key);
|
||||
if (v instanceof Boolean b) {
|
||||
return b;
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
return s.equalsIgnoreCase("true") || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("yes") || s.equals("1");
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
static String str(Map<String, Object> cfg, String key, String def) {
|
||||
Object v = cfg.get(key);
|
||||
return (v == null || v.toString().isBlank()) ? def : v.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<String> list(Map<String, Object> cfg, String key) {
|
||||
Object v = cfg.get(key);
|
||||
if (v instanceof List<?> l) {
|
||||
return l.stream().map(String::valueOf).map(String::trim).filter(s -> !s.isBlank()).toList();
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
return List.of(s.split("[,\\n]")).stream().map(String::trim).filter(x -> !x.isBlank()).toList();
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Alternate;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* SEO+ — serves a per-site <b>{@code /sitemap.xml}</b> enumerating the site's whole published content surface —
|
||||
* kernel pages AND every content source's items (blog entries, any plugin content) through the host's
|
||||
* {@link ContentCatalogView} — each {@code <url>} carrying its {@code hreflang} alternates, {@code x-default}, and
|
||||
* (when the item knows it) a {@code <lastmod>}. Every URL is one the host computed ({@link CatalogEntry#urls()},
|
||||
* {@link CatalogEntry#xDefaultPath()}) with the SAME code the head-injection alternates use, so the
|
||||
* {@code <head>} and the sitemap provably agree about every item's URLs; this class only prefixes the origin.
|
||||
*
|
||||
* <p>The catalog is already kernel-re-filtered (published-only, path-safe, reserved paths dropped) and
|
||||
* metadata-only (no item's body is ever read serving this route — a sitemap request stays cheap no matter how
|
||||
* many sources are installed).
|
||||
*
|
||||
* <p>The route is tenant-scoped and {@link SurfacePosture#discoverable()}. It honors the per-tenant
|
||||
* {@code sitemap.enabled} flag — disabled ⇒ {@code 404}, so a tenant can opt out without uninstalling the
|
||||
* plugin.
|
||||
*/
|
||||
public class SitemapEndpoint implements EndpointContributor {
|
||||
|
||||
private final ContentCatalogView catalog;
|
||||
private final PluginSettings settings;
|
||||
|
||||
public SitemapEndpoint(ContentCatalogView catalog, PluginSettings settings) {
|
||||
this.catalog = catalog;
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/sitemap";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// Indexable + in-sitemap + CACHEABLE: this endpoint manages its own caching (Last-Modified +
|
||||
// no-cache revalidation below) — the dispatcher must not stamp no-store over it.
|
||||
SurfacePosture posture = new SurfacePosture(true, true, true);
|
||||
List<Route> routes = new java.util.ArrayList<>(MAX_SHARDS + 1);
|
||||
routes.add(new Route("GET", SITEMAP_PATH, Realm.TENANT, posture));
|
||||
// Shard routes are declared STATICALLY, one per possible shard, because the host matches routes by
|
||||
// exact path — there is no pattern form, deliberately (a pattern on a public tenant route is a
|
||||
// path-safety surface nobody needs). A shard beyond what a site actually has answers 404; nothing
|
||||
// links to it, so the only way to reach one is to type it.
|
||||
for (int shard = 1; shard <= MAX_SHARDS; shard++) {
|
||||
routes.add(new Route("GET", shardPath(shard), Realm.TENANT, posture));
|
||||
}
|
||||
return List.copyOf(routes);
|
||||
}
|
||||
|
||||
/** The path of shard {@code n} (1-based), e.g. {@code /sitemap-3.xml}. */
|
||||
private static String shardPath(int n) {
|
||||
return "/sitemap-" + n + ".xml";
|
||||
}
|
||||
|
||||
/** The shard number a path names, or {@code 0} when it is the index itself / not a shard path. */
|
||||
private static int shardNumber(String path) {
|
||||
if (path == null || !path.startsWith("/sitemap-") || !path.endsWith(".xml")) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(path.substring("/sitemap-".length(), path.length() - ".xml".length()));
|
||||
} catch (NumberFormatException notAShard) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
Map<String, Object> cfg = settings.site(req.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "sitemap.enabled", true)) {
|
||||
// The route posture is cacheable (so the 200/304 carry their own validators), which means the
|
||||
// dispatcher no longer stamps a fail-safe no-store — so this disabled-path 404 must forbid caching
|
||||
// itself, or a heuristically-cacheable 404 could outlive the tenant re-enabling the surface.
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
String base = PageUrls.base(req.site(), req);
|
||||
List<CatalogEntry> items = catalog.entries(req.site().id());
|
||||
|
||||
// Conditional GET: crawlers revalidate constantly; when nothing changed since their copy, answer 304
|
||||
// without re-serializing the document. The index and every shard share the site's newest instant —
|
||||
// coarse (any edit revalidates all of them) but honest: a per-shard instant would claim a shard is
|
||||
// unchanged while an item moved into or out of it.
|
||||
java.time.Instant newest = CrawlConditional.lastModified(req.site().id(), items);
|
||||
if (CrawlConditional.notModified(req, newest)) {
|
||||
return CrawlConditional.notModifiedResponse(newest);
|
||||
}
|
||||
|
||||
Listing listing = listing(items, base);
|
||||
int shard = shardNumber(req.path());
|
||||
if (shard > 0) {
|
||||
return shardResponse(listing, shard, newest, req.site().id());
|
||||
}
|
||||
if (listing.urls().size() <= SHARD_URLS) {
|
||||
// The ordinary case, and the shape every small site keeps: one plain <urlset>, no index, no extra
|
||||
// round trip. Splitting a 40-URL site across an index would cost a crawler two fetches to learn
|
||||
// nothing.
|
||||
return ok(urlsetDocument(listing.urls(), 0, listing.urls().size()), newest);
|
||||
}
|
||||
return ok(indexDocument(listing, base, newest), newest);
|
||||
}
|
||||
|
||||
/** One sitemap entry: the URL to list, its alternates block (pre-rendered), and its {@code <lastmod>}. */
|
||||
private record Entry(String url, String alternates, String lastmod) {
|
||||
}
|
||||
|
||||
/** The site's whole sitemap surface, and what was left out of it. */
|
||||
private record Listing(List<Entry> urls, int skippedNoindex, int skippedCanonical) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every URL this site advertises, in a <b>stable, content-derived order</b>.
|
||||
*
|
||||
* <h2>Why it is sorted</h2>
|
||||
* {@link ContentCatalogView#entries} returns items grouped by source in an order it does not promise, which is stable
|
||||
* within a boot and says nothing across boots or across the nodes of a cluster. Shard membership is
|
||||
* derived from position in this list, so an unsorted list would let two nodes behind the same load
|
||||
* balancer serve <b>different content for the same shard number</b> — a crawler alternating between them
|
||||
* would see URLs appear and vanish with nothing in the response to explain it. Sorting by URL makes the
|
||||
* boundaries a function of the content alone.
|
||||
*
|
||||
* <p>Metadata only: no item's body is read here, so this stays cheap however many sources are installed.
|
||||
*/
|
||||
private static Listing listing(List<CatalogEntry> items, String base) {
|
||||
List<Entry> entries = new java.util.ArrayList<>();
|
||||
int skippedNoindex = 0;
|
||||
int skippedCanonical = 0;
|
||||
|
||||
for (CatalogEntry item : items) {
|
||||
// A sitemap is a set of RECOMMENDATIONS to index. Listing a URL the same site tells robots not to
|
||||
// index contradicts itself, so drop those here rather than in the host listing — the router, the search
|
||||
// indexer and llms.txt all legitimately need the full published set.
|
||||
if (item.ref().noindex()) {
|
||||
skippedNoindex++;
|
||||
continue;
|
||||
}
|
||||
// Likewise a page whose canonical points somewhere ELSE is, by its own declaration, not the
|
||||
// authoritative URL. Emitting it would advertise a self-declared non-canonical address. (A canonical
|
||||
// equal to the item's own URL is the normal self-referential case and stays.)
|
||||
if (pointsElsewhere(item, base)) {
|
||||
skippedCanonical++;
|
||||
continue;
|
||||
}
|
||||
// The host's URLs — the same computation the head-injection alternates use (provable agreement): one
|
||||
// per available locale, each a REAL routing address (never the canonical override).
|
||||
List<Alternate> alternates = item.urls().stream().map(url -> url.alternate(base)).toList();
|
||||
String xDefault = base + item.xDefaultPath();
|
||||
String lastmod = item.ref().updatedAt() == null ? null : item.ref().updatedAt().toString();
|
||||
|
||||
StringBuilder links = new StringBuilder(128);
|
||||
for (Alternate alt : alternates) {
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"").append(alt.hreflang())
|
||||
.append("\" href=\"").append(xml(alt.url())).append("\"/>\n");
|
||||
}
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"")
|
||||
.append(xml(xDefault)).append("\"/>\n");
|
||||
String block = links.toString();
|
||||
|
||||
for (Alternate self : alternates) {
|
||||
entries.add(new Entry(self.url(), block, lastmod));
|
||||
}
|
||||
}
|
||||
entries.sort(java.util.Comparator.comparing(Entry::url));
|
||||
return new Listing(List.copyOf(entries), skippedNoindex, skippedCanonical);
|
||||
}
|
||||
|
||||
/** One shard's {@code <urlset>}, or {@code 404} for a shard this site does not have. */
|
||||
private RouteResponse shardResponse(Listing listing, int shard, java.time.Instant newest, String siteId) {
|
||||
int total = listing.urls().size();
|
||||
if (total <= SHARD_URLS) {
|
||||
// Not sharded at all: the shard paths exist as routes on every site, so they must say "no" rather
|
||||
// than duplicate /sitemap.xml at a second address — two URLs serving one document is exactly the
|
||||
// duplicate-content shape the rest of this plugin works to avoid.
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
int from = (shard - 1) * SHARD_URLS;
|
||||
if (from >= total) {
|
||||
return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]);
|
||||
}
|
||||
int to = Math.min(from + SHARD_URLS, total);
|
||||
warnIfTruncated(listing, siteId);
|
||||
return ok(urlsetDocument(listing.urls(), from, to), newest);
|
||||
}
|
||||
|
||||
/** The {@code <sitemapindex>} naming each shard this site actually has. */
|
||||
private byte[] indexDocument(Listing listing, String base, java.time.Instant newest) {
|
||||
int shards = Math.min(shardCount(listing.urls().size()), MAX_SHARDS);
|
||||
StringBuilder xml = new StringBuilder(256 + shards * 128);
|
||||
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
.append("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
|
||||
for (int shard = 1; shard <= shards; shard++) {
|
||||
xml.append(" <sitemap>\n")
|
||||
.append(" <loc>").append(xml(base + shardPath(shard))).append("</loc>\n");
|
||||
if (newest != null) {
|
||||
xml.append(" <lastmod>").append(newest).append("</lastmod>\n");
|
||||
}
|
||||
xml.append(" </sitemap>\n");
|
||||
}
|
||||
xml.append("</sitemapindex>\n");
|
||||
return xml.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** A {@code <urlset>} over {@code urls[from, to)}. */
|
||||
private static byte[] urlsetDocument(List<Entry> urls, int from, int to) {
|
||||
StringBuilder xml = new StringBuilder(512 + (to - from) * 256);
|
||||
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"")
|
||||
.append(" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n");
|
||||
for (int i = from; i < to; i++) {
|
||||
Entry entry = urls.get(i);
|
||||
xml.append(" <url>\n")
|
||||
.append(" <loc>").append(xml(entry.url())).append("</loc>\n");
|
||||
if (entry.lastmod() != null) {
|
||||
xml.append(" <lastmod>").append(entry.lastmod()).append("</lastmod>\n");
|
||||
}
|
||||
xml.append(entry.alternates()).append(" </url>\n");
|
||||
}
|
||||
xml.append("</urlset>\n");
|
||||
return xml.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** How many shards {@code total} URLs need. */
|
||||
private static int shardCount(int total) {
|
||||
return (total + SHARD_URLS - 1) / SHARD_URLS;
|
||||
}
|
||||
|
||||
private static void warnIfTruncated(Listing listing, String siteId) {
|
||||
int needed = shardCount(listing.urls().size());
|
||||
if (needed > MAX_SHARDS) {
|
||||
// LOUD, and naming the tenant: a silently truncated sitemap is indistinguishable from a small site,
|
||||
// so an operator would have no way to learn that content stopped being advertised.
|
||||
log.warn("sitemap for site '{}' needs {} shards but only {} are served ({} URLs per shard) — "
|
||||
+ "{} URL(s) beyond {} are NOT advertised.", siteId, needed, MAX_SHARDS, SHARD_URLS,
|
||||
listing.urls().size() - (long) MAX_SHARDS * SHARD_URLS, (long) MAX_SHARDS * SHARD_URLS);
|
||||
}
|
||||
}
|
||||
|
||||
private static RouteResponse ok(byte[] body, java.time.Instant newest) {
|
||||
return new RouteResponse(200,
|
||||
CrawlConditional.cacheHeaders(newest, "application/xml; charset=utf-8"), body);
|
||||
}
|
||||
|
||||
/** The route the index (or, for a small site, the single {@code <urlset>}) is served at. */
|
||||
private static final String SITEMAP_PATH = "/sitemap.xml";
|
||||
|
||||
/**
|
||||
* URLs per shard, and how many shards are served — together the ceiling on what a site can advertise
|
||||
* ({@value #SHARD_URLS} × {@value #MAX_SHARDS}).
|
||||
*
|
||||
* <h2>Why 10,000 and not the spec's 50,000</h2>
|
||||
* sitemaps.org allows <b>50,000 URLs and 50 MB</b> per file, and a conformant consumer may reject a
|
||||
* document that exceeds either — so an unbounded generator does not degrade gracefully on a large tenant,
|
||||
* it loses the whole sitemap at once. But the spec cap is not the binding constraint here: this is a
|
||||
* <b>public, anonymous</b> route, and a 50,000-URL document with {@code hreflang} alternates is tens of
|
||||
* megabytes assembled in the heap, per concurrent request. A smaller shard keeps each response comfortably
|
||||
* inside both the spec and a sane memory envelope, and costs a crawler only extra round trips it makes
|
||||
* anyway.
|
||||
*
|
||||
* <p>{@value #MAX_SHARDS} shards is a real ceiling — {@value #SHARD_URLS} × {@value #MAX_SHARDS}
|
||||
* URLs — because the host matches routes by exact path, so each shard is a declared route rather than a
|
||||
* pattern. Well past any filesystem-backed tenant, four times the single-file limit it replaces, and it
|
||||
* still WARNs loudly rather than truncating in silence.
|
||||
*/
|
||||
private static final int SHARD_URLS = 10_000;
|
||||
private static final int MAX_SHARDS = 20;
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SitemapEndpoint.class);
|
||||
|
||||
/**
|
||||
* Whether {@code item} declares a canonical URL pointing somewhere other than its own address — in which case
|
||||
* the item asks not to be treated as the authoritative URL and has no business in the sitemap.
|
||||
*
|
||||
* <p>The override is read from {@link LocalizedUrl#canonical()} (the host hands it over as given; equal to the
|
||||
* URL's own path when there is none). A root-relative override ({@code /about}) is resolved against
|
||||
* {@code base} before comparing, as the kernel does for the {@code <head>} canonical: it names an address on
|
||||
* this site, so {@code /about} on the {@code /about} page is the self-referential case. (Until 2.0.0 the raw
|
||||
* value was compared with the absolute URLs, so such a page was dropped from the sitemap.)
|
||||
*
|
||||
* <p>Compared against every locale's address and the {@code x-default}, because a localized variant is its own
|
||||
* address: a canonical matching any of the item's own URLs is the ordinary self-referential case.
|
||||
*/
|
||||
private static boolean pointsElsewhere(CatalogEntry item, String base) {
|
||||
String override = null;
|
||||
for (LocalizedUrl url : item.urls()) {
|
||||
if (!url.canonical().equals(url.path())) {
|
||||
override = url.canonical();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (override == null || override.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String want = override.trim();
|
||||
if (want.startsWith("/")) {
|
||||
want = base + want;
|
||||
}
|
||||
for (LocalizedUrl url : item.urls()) {
|
||||
if (url.absolute(base).equals(want)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return !want.equals(base + item.xDefaultPath());
|
||||
}
|
||||
|
||||
/** XML text/attribute escaping for URLs (chiefly {@code &} in query strings). */
|
||||
private static String xml(String value) {
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "endpoint.sitemap");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* SEO+ and GEO — the single {@code HeadContributor} that injects one schema.org {@code @graph} of JSON-LD into
|
||||
* every indexable page's {@code <head>}. This is the layer the lean kernel deliberately leaves out: the kernel
|
||||
* already emits canonical, hreflang, robots, Open Graph and Twitter cards, so this contributor adds only the
|
||||
* structured-data {@code @graph} — never a tag the kernel already produces.
|
||||
*
|
||||
* <p>It emits <b>one</b> {@code <script type="application/ld+json">} block whose {@code @graph} carries each
|
||||
* entity <b>exactly once</b>: {@code WebSite} (with the GEO {@code SearchAction} folded in as its
|
||||
* {@code potentialAction}), {@code Organization}, {@code WebPage}/{@code Article} (with the GEO
|
||||
* {@code speakable} folded in), and {@code BreadcrumbList} on deep pages. Folding GEO into the same nodes — rather
|
||||
* than re-declaring {@code #website}/{@code #webpage} in a second block — means a JSON-LD consumer that parses
|
||||
* each {@code <script>} independently still sees complete entities.
|
||||
*
|
||||
* <p>Pure and stateless. Emits nothing for a preview or {@code noindex} render (structured data belongs only on
|
||||
* indexable pages), or when the tenant turns {@code jsonld.enabled} off (which also suppresses the GEO signals,
|
||||
* since a {@code SearchAction}/{@code speakable} that references an undefined {@code #website}/{@code #webpage}
|
||||
* would be an orphan). GEO signals are additionally gated by the opt-in {@code geo.enabled} flag. All URLs are
|
||||
* anchored on the host-resolved {@link HeadContext#canonical()} so the graph is internally consistent — made
|
||||
* absolute against {@link HeadContext#origin()} on a host-less site, whose canonical is root-relative (since 2.1.0;
|
||||
* it is why the plugin needs SPI 1.0.0).
|
||||
*/
|
||||
public class StructuredDataHead implements HeadContributor {
|
||||
|
||||
static final String PLUGIN_ID = "discoverability";
|
||||
|
||||
/**
|
||||
* Default {@code speakable} selectors when the tenant has not customized {@code geo.speakable}. Only elements
|
||||
* the shipped seed master (and a typical custom master) actually render — {@code <article>} is intentionally
|
||||
* NOT a default, since the seed masters have none and a phantom selector helps no assistant. A tenant whose
|
||||
* master really has {@code <article>} adds it back in the per-site GEO settings.
|
||||
*/
|
||||
private static final List<String> DEFAULT_SPEAKABLE = List.of("h1", "main");
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Map<String, SchemaType> types;
|
||||
|
||||
public StructuredDataHead(PluginSettings settings, Map<String, SchemaType> types) {
|
||||
this.settings = settings;
|
||||
this.types = types == null ? Map.of() : types;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "discoverability/structured-data";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String render(HeadContext ctx) {
|
||||
if (ctx.preview() || ctx.noindex()) {
|
||||
return "";
|
||||
}
|
||||
Map<String, Object> cfg = settings.site(ctx.site().id()).values();
|
||||
if (!SiteConfig.bool(cfg, "jsonld.enabled", true)) {
|
||||
return "";
|
||||
}
|
||||
if (ctx.canonical() == null || ctx.canonical().isBlank()) {
|
||||
return ""; // no URL to anchor the graph — emit nothing rather than a broken graph
|
||||
}
|
||||
String base = baseFor(ctx, ctx.canonical());
|
||||
// A host-less site's canonical is root-relative (the kernel prefixes only a base URL it knows); JSON-LD
|
||||
// URLs and @ids must be absolute, so it is anchored on the trusted origin the page is served under.
|
||||
String canonical = absolute(ctx.canonical(), base);
|
||||
String siteUrl = base.isBlank() ? null : base + "/";
|
||||
String path = pathOf(base, canonical);
|
||||
boolean geo = SiteConfig.bool(cfg, "geo.enabled", false);
|
||||
List<Map<String, Object>> graph = new ArrayList<>();
|
||||
|
||||
// WebSite — the GEO SearchAction is folded in as potentialAction so #website is defined exactly once.
|
||||
Map<String, Object> website = Ld.node("WebSite", Ld.websiteId(base));
|
||||
Ld.put(website, "url", siteUrl);
|
||||
Ld.put(website, "name", ctx.site().displayName());
|
||||
Ld.put(website, "inLanguage", ctx.locale().toLanguageTag());
|
||||
if (geo && !base.isBlank()) {
|
||||
String searchUrl = SiteConfig.str(cfg, "search.url", "");
|
||||
if (!searchUrl.isBlank()) {
|
||||
website.put("potentialAction", searchAction(base, searchUrl));
|
||||
}
|
||||
}
|
||||
graph.add(website);
|
||||
|
||||
// Organization (only when the tenant has named one)
|
||||
String orgName = SiteConfig.str(cfg, "org.name", "");
|
||||
boolean hasOrg = !orgName.isBlank();
|
||||
if (hasOrg) {
|
||||
Map<String, Object> org = Ld.node("Organization", Ld.organizationId(base));
|
||||
Ld.put(org, "name", orgName);
|
||||
Ld.put(org, "url", siteUrl);
|
||||
Ld.put(org, "logo", absolutize(SiteConfig.str(cfg, "org.logo", ""), base));
|
||||
Ld.putList(org, "sameAs", SiteConfig.list(cfg, "org.sameas"));
|
||||
graph.add(org);
|
||||
}
|
||||
|
||||
// The page's own node — its type is the site's Default page type, or the page type its content.schema entry
|
||||
// declares (PageTypes: the same answer the page editor shows). The GEO speakable is folded in so #webpage is
|
||||
// defined exactly once.
|
||||
PageTypes.Description described = PageTypes.describe(cfg, path, types);
|
||||
String type = described.type();
|
||||
Map<String, Object> page = Ld.node(type, Ld.webpageId(canonical));
|
||||
Ld.put(page, "url", canonical);
|
||||
Ld.put(page, "Article".equals(type) ? "headline" : "name", ctx.page().title());
|
||||
Ld.put(page, "description", ctx.page().description());
|
||||
Ld.put(page, "inLanguage", ctx.locale().toLanguageTag());
|
||||
Ld.ref(page, "isPartOf", Ld.websiteId(base));
|
||||
if (hasOrg) {
|
||||
Ld.ref(page, "publisher", Ld.organizationId(base));
|
||||
}
|
||||
if (geo) {
|
||||
List<String> selectors = SiteConfig.list(cfg, "geo.speakable");
|
||||
if (selectors.isEmpty()) {
|
||||
selectors = DEFAULT_SPEAKABLE;
|
||||
}
|
||||
Map<String, Object> speakable = new LinkedHashMap<>();
|
||||
speakable.put("@type", "SpeakableSpecification");
|
||||
speakable.put("cssSelector", selectors);
|
||||
page.put("speakable", speakable);
|
||||
}
|
||||
graph.add(page);
|
||||
if (described.pageBlock() != null) {
|
||||
types.get(type).describePage(page, ctx,
|
||||
schemaContext(ctx, base, canonical, path, hasOrg, described.pageBlock()), graph);
|
||||
}
|
||||
|
||||
// SoftwareApplication — a product/app entity emitted on the HOMEPAGE ONLY (so it never leaks onto
|
||||
// interior pages the way a hand-authored extra-head block did), @id-linked into this same graph. The
|
||||
// tenant configures it via software.* instead of hand-authoring raw JSON-LD in seo.yml's extraHead.
|
||||
if (SiteConfig.bool(cfg, "software.enabled", false) && isHome(path, ctx)) {
|
||||
graph.add(softwareApplication(cfg, base, siteUrl, canonical, orgName, hasOrg, ctx));
|
||||
}
|
||||
|
||||
// Type-aware structured data — a tenant declares a page/section type in content.schema; the matching
|
||||
// SchemaType maps it to schema.org nodes that reference this WebPage / Organization by @id. The head
|
||||
// contributor stays type-blind: it dispatches through the registry, never branches on a concrete type.
|
||||
appendTypedNodes(ctx, described.added(), base, canonical, path, hasOrg, graph);
|
||||
|
||||
// BreadcrumbList (home → [collection] → this page), @id'd and linked from WebPage.breadcrumb.
|
||||
if (SiteConfig.bool(cfg, "jsonld.breadcrumbs", true) && siteUrl != null) {
|
||||
Map<String, Object> crumbs =
|
||||
breadcrumbs(base, canonical, path, ctx.page().title(), collectionParent(cfg, path, ctx));
|
||||
if (crumbs != null) {
|
||||
graph.add(crumbs);
|
||||
Ld.ref(page, "breadcrumb", (String) crumbs.get("@id"));
|
||||
}
|
||||
}
|
||||
|
||||
return Ld.script(graph);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the site's {@code SoftwareApplication} node from the {@code software.*} config. {@code name}
|
||||
* falls back to the organization name / site display name; {@code url} to the homepage; {@code offers} is
|
||||
* emitted only when a price is set (price {@code 0} = free); {@code publisher} references the Organization.
|
||||
*/
|
||||
private static Map<String, Object> softwareApplication(Map<String, Object> cfg, String base, String siteUrl,
|
||||
String canonical, String orgName, boolean hasOrg, HeadContext ctx) {
|
||||
Map<String, Object> app = Ld.node("SoftwareApplication", Ld.softwareId(base));
|
||||
String name = SiteConfig.str(cfg, "software.name", "");
|
||||
if (name.isBlank()) {
|
||||
name = orgName.isBlank() ? ctx.site().displayName() : orgName;
|
||||
}
|
||||
Ld.put(app, "name", name);
|
||||
String url = SiteConfig.str(cfg, "software.url", "");
|
||||
Ld.put(app, "url", !url.isBlank() ? url : (siteUrl != null ? siteUrl : canonical));
|
||||
Ld.put(app, "applicationCategory", SiteConfig.str(cfg, "software.category", ""));
|
||||
Ld.put(app, "operatingSystem", SiteConfig.str(cfg, "software.os", "Web"));
|
||||
String description = SiteConfig.str(cfg, "software.description", "");
|
||||
Ld.put(app, "description", description.isBlank() ? ctx.page().description() : description);
|
||||
Ld.put(app, "inLanguage", ctx.locale().toLanguageTag());
|
||||
Ld.put(app, "license", SiteConfig.str(cfg, "software.license", ""));
|
||||
Ld.put(app, "screenshot", SiteConfig.str(cfg, "software.screenshot", ""));
|
||||
String price = SiteConfig.str(cfg, "software.price", "");
|
||||
if (!price.isBlank()) {
|
||||
Map<String, Object> offer = new LinkedHashMap<>();
|
||||
offer.put("@type", "Offer");
|
||||
offer.put("price", price);
|
||||
offer.put("priceCurrency", SiteConfig.str(cfg, "software.currency", "USD"));
|
||||
app.put("offers", offer);
|
||||
}
|
||||
if (hasOrg) {
|
||||
Ld.ref(app, "publisher", Ld.organizationId(base));
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the nodes of the blocks that add an entity to the page (a product, a service, a business, a person, a
|
||||
* list), each through its registered {@link SchemaType}. The block that describes the page itself has already
|
||||
* shaped the page's own node; {@link PageTypes} decided which is which.
|
||||
*/
|
||||
private void appendTypedNodes(HeadContext ctx, List<Map<String, Object>> blocks, String base, String canonical,
|
||||
String path, boolean hasOrg, List<Map<String, Object>> graph) {
|
||||
// A path may declare SEVERAL type-blocks (e.g. an FAQPage AND a set of Offers on a pricing page);
|
||||
// dispatch each through the registry. The contributor stays type-blind — no instanceof/switch.
|
||||
for (Map<String, Object> block : blocks) {
|
||||
SchemaType type = types.get(Schemas.str(block, "type", ""));
|
||||
List<Map<String, Object>> nodes =
|
||||
type.nodes(ctx, schemaContext(ctx, base, canonical, path, hasOrg, block));
|
||||
if (nodes != null) {
|
||||
for (Map<String, Object> node : nodes) {
|
||||
if (node != null && !node.isEmpty()) {
|
||||
graph.add(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static SchemaContext schemaContext(HeadContext ctx, String base, String canonical, String path,
|
||||
boolean hasOrg, Map<String, Object> block) {
|
||||
return new SchemaContext(base, canonical, path, isHome(path, ctx), hasOrg,
|
||||
Ld.websiteId(base), Ld.webpageId(canonical), hasOrg ? Ld.organizationId(base) : null,
|
||||
block, ctx.locale());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a root-relative URL (one that starts with {@code /}) to absolute against the site base, so a
|
||||
* portable seed can ship {@code org.logo: /static/img/logo.svg} without hard-coding a host; an
|
||||
* already-absolute or blank value passes through unchanged.
|
||||
*/
|
||||
private static String absolutize(String url, String base) {
|
||||
return (url != null && url.startsWith("/") && !base.isBlank()) ? base + url : url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path portion of the (absolute) canonical relative to the site base ({@code "/"} for the home). Guards
|
||||
* against a per-page <b>canonical override to a different host</b>: when the canonical does not start with
|
||||
* the site base (or its own origin), the raw canonical is returned — which is neither {@code "/"} nor a
|
||||
* {@code /}-rooted path, so {@code isHome()}, {@code content.schema} matching and breadcrumbs all correctly
|
||||
* treat it as "not this site's home / no path match" rather than slicing a garbage substring. Package-private
|
||||
* so the FAQ advisory can resolve a page's path the same way the render-time typing does.
|
||||
*/
|
||||
static String pathOf(String base, String canonical) {
|
||||
String origin = (base == null || base.isBlank()) ? Ld.origin(canonical) : base;
|
||||
if (!origin.isBlank() && canonical.startsWith(origin)) {
|
||||
String path = canonical.substring(origin.length());
|
||||
return path.isEmpty() ? "/" : path;
|
||||
}
|
||||
return canonical; // canonical diverges from the site base (a cross-domain per-page canonical override)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code path} addresses a homepage — the default-locale home ({@code "/"}) or a localized home
|
||||
* ({@code /<locale>}), matched against the site's actual locale set so a real 2-letter slug is not mistaken
|
||||
* for a locale prefix.
|
||||
*/
|
||||
private static boolean isHome(String path, HeadContext ctx) {
|
||||
String p = (path.length() > 1 && path.endsWith("/")) ? path.substring(0, path.length() - 1) : path;
|
||||
if (p.isEmpty() || p.equals("/")) {
|
||||
return true;
|
||||
}
|
||||
String seg = p.startsWith("/") ? p.substring(1) : p;
|
||||
Locale def = ctx.site().defaultLocale();
|
||||
for (Locale locale : ctx.site().locales()) {
|
||||
// The DEFAULT locale's home is "/" (unprefixed), never "/<code>", so a "/<default-code>" path is a
|
||||
// real page, not a home — skipping it removes the most likely code-vs-slug collision (e.g. "/en").
|
||||
if (locale.equals(def)) {
|
||||
continue;
|
||||
}
|
||||
if (seg.equalsIgnoreCase(locale.getLanguage()) || seg.equalsIgnoreCase(locale.toLanguageTag())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The site base: the site's base URL (configured, or derived from its host name), else — a host-less site,
|
||||
* such as the platform's catch-all default — the trusted origin the page is served under
|
||||
* ({@link HeadContext#origin()}, SPI 1.0.0: the request's scheme and host as the kernel's trusted-proxy gate left
|
||||
* them, never a raw {@code X-Forwarded-*} header), else the origin of an absolute canonical. {@code ""} only
|
||||
* when none is known. Until 2.1.0 a host-less site had no base here, so its graph was root-relative and carried
|
||||
* no {@code SearchAction} and no breadcrumb trail.
|
||||
*/
|
||||
static String baseFor(HeadContext ctx, String canonical) {
|
||||
String configured = ctx.site().baseUrl();
|
||||
String base;
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
base = configured.trim();
|
||||
} else if (!ctx.origin().isBlank()) {
|
||||
base = ctx.origin().trim();
|
||||
} else {
|
||||
base = Ld.origin(canonical);
|
||||
}
|
||||
return base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code canonical} made absolute against {@code base} when it is root-relative ({@code /about}); an absolute
|
||||
* canonical (the usual case, and every cross-domain override) passes through unchanged, and with no base known
|
||||
* ({@code ""}) a root-relative one stays as it is. A protocol-relative {@code //host/x} is left alone — it already
|
||||
* names a host.
|
||||
*/
|
||||
static String absolute(String canonical, String base) {
|
||||
return canonical.startsWith("/") && !canonical.startsWith("//") ? base + canonical : canonical;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a schema.org {@code SearchAction} for the site's search URL. A {@code {query}} or
|
||||
* {@code {search_term_string}} placeholder is honored; otherwise a {@code q=} parameter is appended.
|
||||
*/
|
||||
private static Map<String, Object> searchAction(String base, String searchUrl) {
|
||||
String template = searchUrl.startsWith("http")
|
||||
? searchUrl
|
||||
: base + (searchUrl.startsWith("/") ? "" : "/") + searchUrl;
|
||||
if (template.contains("{query}")) {
|
||||
template = template.replace("{query}", "{search_term_string}");
|
||||
} else if (!template.contains("{search_term_string}")) {
|
||||
template = template + (template.contains("?") ? "&" : "?") + "q={search_term_string}";
|
||||
}
|
||||
Map<String, Object> action = new LinkedHashMap<>();
|
||||
action.put("@type", "SearchAction");
|
||||
// NEVER Map.of() for a node that is serialized: java.util.Map.of randomizes iteration order PER JVM
|
||||
// INSTANCE (ImmutableCollections.SALT), so the emitted JSON-LD key order flipped on roughly every
|
||||
// other restart — stable within one run, different after the next. Found in a live deployment by an operator
|
||||
// byte-diffing homepages across an upgrade, who reasonably read it as a one-off change between builds;
|
||||
// it was not, it was every restart, forever. Harmless semantically (the graphs are equal), but it made
|
||||
// rendered output non-reproducible and quietly broke the promise of the page's strong ETag, which
|
||||
// folds metadata and templates and therefore did NOT change when the body did.
|
||||
Map<String, Object> target = new LinkedHashMap<>();
|
||||
target.put("@type", "EntryPoint");
|
||||
target.put("urlTemplate", template);
|
||||
action.put("target", target);
|
||||
action.put("query-input", "required name=search_term_string");
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code Home → [collection] → page} breadcrumb with a stable {@code @id} (so the {@code WebPage} can point
|
||||
* at it); {@code null} for the home page (or a cross-domain canonical). When {@code parent} is non-null (a
|
||||
* content.schema {@code breadcrumb: {name, url}} on a detail page under a collection) it becomes the middle
|
||||
* level, so a product's trail reads {@code Home → Coffees → Ethiopia Guji} rather than {@code Home → Guji}.
|
||||
*/
|
||||
private static Map<String, Object> breadcrumbs(String base, String canonical, String path, String pageTitle,
|
||||
Map<String, Object> parent) {
|
||||
if (path.isBlank() || path.equals("/") || !path.startsWith("/")) {
|
||||
return null; // home, or a canonical that isn't a path under this site — no breadcrumb trail
|
||||
}
|
||||
List<Map<String, Object>> items = new ArrayList<>();
|
||||
int position = 1;
|
||||
items.add(listItem(position++, "Home", base + "/"));
|
||||
if (parent != null) {
|
||||
String parentUrl = Schemas.str(parent, "url");
|
||||
items.add(listItem(position++, Schemas.str(parent, "name"),
|
||||
parentUrl != null && parentUrl.startsWith("/") ? base + parentUrl : parentUrl));
|
||||
}
|
||||
items.add(listItem(position, (pageTitle == null || pageTitle.isBlank()) ? path : pageTitle, canonical));
|
||||
Map<String, Object> list = Ld.node("BreadcrumbList", canonical + "#breadcrumb");
|
||||
list.put("itemListElement", items);
|
||||
return list;
|
||||
}
|
||||
|
||||
private static Map<String, Object> listItem(int position, String name, String item) {
|
||||
Map<String, Object> node = new LinkedHashMap<>();
|
||||
node.put("@type", "ListItem");
|
||||
node.put("position", position);
|
||||
Ld.put(node, "name", name);
|
||||
Ld.put(node, "item", item);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** The optional parent-collection level a page declares in content.schema ({@code breadcrumb: {name, url}}). */
|
||||
private static Map<String, Object> collectionParent(Map<String, Object> cfg, String path, HeadContext ctx) {
|
||||
Object entry = PageTypes.entry(cfg, path);
|
||||
for (Map<String, Object> block : PageSchemaConfig.blocks(entry)) {
|
||||
if (block.get("breadcrumb") instanceof Map<?, ?> map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> parent = (Map<String, Object>) map;
|
||||
if (Schemas.str(parent, "name") != null && Schemas.str(parent, "url") != null) {
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("head.structured-data", "head.per-locale", "head.geo");
|
||||
}
|
||||
|
||||
/**
|
||||
* This contributor's whole per-site input: its own settings file.
|
||||
*
|
||||
* <p>Declared so the kernel can fold it into each page's {@code ETag}. Head markup is spliced in at the
|
||||
* response edge, <b>after</b> the page validator has been computed and may already have answered
|
||||
* {@code 304} — so without this, changing a per-site setting here (organisation name, GEO, the search URL)
|
||||
* changed the delivered page and not its validator, and every client and CDN holding the old one kept the
|
||||
* previous markup indefinitely.
|
||||
*/
|
||||
@Override
|
||||
public java.util.List<String> headInputs(String siteId) {
|
||||
return java.util.List.of("plugins/discoverability.yml");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The membership-aware crawl validator: {@code Last-Modified} must advance on ANY document change — including
|
||||
* removals, which a naive {@code max(updatedAt)} can never see (deleting an item only removes an mtime from
|
||||
* the pool) — while staying stable for unchanged documents so revalidating crawlers actually get their 304s.
|
||||
* Time is injected via the class's clock hook; {@code reset()} simulates a restart.
|
||||
*/
|
||||
class CrawlConditionalTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), null);
|
||||
private static final Instant T0 = Instant.parse("2026-07-17T10:00:00Z");
|
||||
|
||||
private Instant now;
|
||||
|
||||
@BeforeEach
|
||||
void freezeClock() {
|
||||
CrawlConditional.reset();
|
||||
now = T0;
|
||||
CrawlConditional.clock = () -> now;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreClock() {
|
||||
CrawlConditional.reset();
|
||||
}
|
||||
|
||||
private static CatalogEntry item(String id, Instant updatedAt) {
|
||||
return Entries.of("blog", new ContentRef(id, "/blog/" + id, Map.of(), List.of(EN),
|
||||
Map.of("en", id), Map.of(), "", "__site__/acme/e", true, updatedAt, false, null, null, Map.of()), SITE);
|
||||
}
|
||||
|
||||
private static RouteRequest revalidating(Instant lastModified) {
|
||||
Map<String, String> headers = Map.of("If-Modified-Since",
|
||||
CrawlConditional.cacheHeaders(lastModified, null).get("Last-Modified"));
|
||||
return new RouteRequest(SITE, EN, "GET", "/sitemap.xml", Map.of(), headers, new byte[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedDocumentKeepsItsValidatorSoRevalidationYields304() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant first = CrawlConditional.lastModified("acme", items);
|
||||
now = T0.plusSeconds(300);
|
||||
Instant later = CrawlConditional.lastModified("acme", items);
|
||||
assertEquals(first, later, "an unchanged document keeps a stable validator");
|
||||
assertTrue(CrawlConditional.notModified(revalidating(first), later), "a revalidating crawler gets 304");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRemovalAdvancesTheValidatorSoStaleCopiesAreRefetched() {
|
||||
// The naive max(updatedAt) blind spot: deleting an item only REMOVES an mtime — the max never moves.
|
||||
CatalogEntry a = item("a", T0.minusSeconds(7200));
|
||||
CatalogEntry b = item("b", T0.minusSeconds(3600));
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(a, b));
|
||||
|
||||
now = T0.plusSeconds(600); // the entry is deleted ten minutes later
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(a));
|
||||
assertTrue(after.isAfter(before), "a removal must advance the validator");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after),
|
||||
"a crawler holding the pre-removal copy gets a fresh 200, never a stale 304");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAdditionWithoutUpdatedAtStillAdvances() {
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(item("a", T0.minusSeconds(3600))));
|
||||
now = T0.plusSeconds(60);
|
||||
Instant after = CrawlConditional.lastModified("acme",
|
||||
List.of(item("a", T0.minusSeconds(3600)), item("new", null)));
|
||||
assertTrue(after.isAfter(before), "a new null-updatedAt item is still a document change");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFutureMtimeCannotPinTheValidator() {
|
||||
// Clock skew / a touched file: a future updatedAt would otherwise mask every later real change.
|
||||
Instant seeded = CrawlConditional.lastModified("acme", List.of(item("a", T0.plusSeconds(86400))));
|
||||
assertFalse(seeded.isAfter(now), "the validator is clamped to now, never in the future");
|
||||
now = T0.plusSeconds(120);
|
||||
Instant advanced = CrawlConditional.lastModified("acme",
|
||||
List.of(item("a", T0.plusSeconds(86400)), item("b", null)));
|
||||
assertTrue(advanced.isAfter(seeded), "later changes still advance past the clamped value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSameSecondChangeIsReDetectedOnceTheClockMoves() {
|
||||
// A change landing in the same second as the previous advance cannot advance a second-granular
|
||||
// validator — the state must NOT absorb it (or it would 304 forever); the next request re-detects it.
|
||||
Instant seeded = CrawlConditional.lastModified("acme", List.of(item("a", null), item("b", null)));
|
||||
Instant sameSecond = CrawlConditional.lastModified("acme", List.of(item("a", null)));
|
||||
assertEquals(seeded, sameSecond, "within the same second the validator cannot advance yet");
|
||||
now = T0.plusSeconds(1);
|
||||
Instant next = CrawlConditional.lastModified("acme", List.of(item("a", null)));
|
||||
assertTrue(next.isAfter(seeded), "the held change advances as soon as the clock moves");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restartSeedsWithNowSoAcrossRestartRemovalsAreNeverMasked() {
|
||||
Instant before = CrawlConditional.lastModified("acme",
|
||||
List.of(item("a", T0.minusSeconds(7200)), item("b", T0.minusSeconds(3600))));
|
||||
CrawlConditional.reset(); // the app restarts; the entry was deleted while it was down
|
||||
CrawlConditional.clock = () -> now;
|
||||
now = T0.plusSeconds(900);
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(item("a", T0.minusSeconds(7200))));
|
||||
assertTrue(after.isAfter(before), "seeding with now (not the content mtime) covers the restart gap");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after),
|
||||
"a crawler from before the restart re-fetches and drops the removed URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* A change of the host-computed URLs alone — the site starts serving a second locale, so every item gains an
|
||||
* alternate — reshapes the sitemap while no item's id, path, mtime or indexability moves. 1.x left it out of the
|
||||
* fingerprint, so a revalidating crawler kept the old document; since 2.0.0 the URLs are part of it.
|
||||
*/
|
||||
@Test
|
||||
void aChangeOfTheComputedUrlsAloneAdvancesTheValidator() {
|
||||
ContentRef ref = new ContentRef("a", "/a", Map.of(), List.of(EN, ES), Map.of("en", "a"), Map.of(), "",
|
||||
"__site__/acme/a", true, T0.minusSeconds(3600), false, null, null, Map.of());
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", ref, SITE)));
|
||||
now = T0.plusSeconds(60);
|
||||
SiteView bilingual = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", ref, bilingual)));
|
||||
assertTrue(after.isAfter(before), "a new alternate is a document change");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after));
|
||||
}
|
||||
|
||||
/** …and so does a canonical override appearing (it moves the item out of the sitemap). */
|
||||
@Test
|
||||
void aNewCanonicalOverrideAdvancesTheValidator() {
|
||||
ContentRef plain = new ContentRef("a", "/a", Map.of(), List.of(EN), Map.of("en", "a"), Map.of(), "",
|
||||
"__site__/acme/a", true, null, false, null, null, Map.of());
|
||||
ContentRef elsewhere = new ContentRef("a", "/a", Map.of(), List.of(EN), Map.of("en", "a"), Map.of(), "",
|
||||
"__site__/acme/a", true, null, false, "https://other.test/a", null, Map.of());
|
||||
Instant before = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", plain, SITE)));
|
||||
now = T0.plusSeconds(60);
|
||||
Instant after = CrawlConditional.lastModified("acme", List.of(Entries.of("pages", elsewhere, SITE)));
|
||||
assertTrue(after.isAfter(before));
|
||||
}
|
||||
|
||||
// --- document-level facts (2.1.0) -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* llms.txt prints the site name and {@code geo.summary}, which no catalog item carries; until 2.1.0 the validator
|
||||
* folded the items only, so editing either changed the document while a revalidating crawler kept its copy.
|
||||
*/
|
||||
@Test
|
||||
void aChangedDocumentFactAdvancesTheValidator() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant before = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
List.of("Acme", "We build things."));
|
||||
now = T0.plusSeconds(60);
|
||||
assertEquals(before, CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
List.of("Acme", "We build things.")), "unchanged facts keep the validator");
|
||||
Instant after = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
List.of("Acme", "We build better things."));
|
||||
assertEquals(now, after, "a fact carries no mtime of its own, so the change advances to now");
|
||||
assertFalse(CrawlConditional.notModified(revalidating(before), after));
|
||||
}
|
||||
|
||||
/** Facts are length-prefixed: moving characters from one fact to the next is a different document. */
|
||||
@Test
|
||||
void factsCannotAliasByShiftingCharactersAcrossTheBoundary() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant before = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("Acme", "Co"));
|
||||
now = T0.plusSeconds(60);
|
||||
Instant after = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("AcmeC", "o"));
|
||||
assertTrue(after.isAfter(before), "['Acme','Co'] and ['AcmeC','o'] are different documents");
|
||||
now = T0.plusSeconds(120);
|
||||
Instant nulled = CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items,
|
||||
java.util.Arrays.asList("AcmeC", null));
|
||||
assertTrue(nulled.isAfter(after), "a fact that disappears is a change too (null folds as empty)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Each document keeps its own validator: llms.txt folds facts the sitemap does not, and one shared record per
|
||||
* site would let the two documents advance each other's validator on every alternate request.
|
||||
*/
|
||||
@Test
|
||||
void theSitemapAndLlmsTxtKeepSeparateValidators() {
|
||||
List<CatalogEntry> items = List.of(item("a", T0.minusSeconds(3600)));
|
||||
Instant sitemap = CrawlConditional.lastModified("acme", items);
|
||||
now = T0.plusSeconds(60);
|
||||
CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("Acme", "One"));
|
||||
now = T0.plusSeconds(120);
|
||||
CrawlConditional.lastModified("acme", CrawlConditional.LLMS, items, List.of("Acme", "Two"));
|
||||
now = T0.plusSeconds(180);
|
||||
assertEquals(sitemap, CrawlConditional.lastModified("acme", items),
|
||||
"llms.txt's changes do not move the sitemap's validator");
|
||||
assertEquals(sitemap, CrawlConditional.lastModified("acme", CrawlConditional.SITEMAP, items, List.of()),
|
||||
"the two-argument form is the sitemap's");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The settings change that came with the SPI: 1.x read only the values a site had STORED and applied its own code
|
||||
* fallbacks; since 2.0.0 the host's {@code PluginSettings} applies the descriptor's declared {@code default:}s first.
|
||||
* If a code fallback and its declared default ever disagreed, an unchanged site would render differently after the
|
||||
* upgrade. This renders every surface twice — with the declared defaults applied and with none — for a site that
|
||||
* stored nothing, and for one that stored blank values the form may write, and requires identical bytes.
|
||||
*/
|
||||
class DescriptorDefaultsTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
|
||||
/** Stored values a site may hold without meaning anything: blank fields the settings form saved. */
|
||||
private static final Map<String, Object> BLANKS = Map.ofEntries(
|
||||
Map.entry("jsonld.type", ""), Map.entry("robots.ai-policy", ""), Map.entry("robots.ai-training", ""),
|
||||
Map.entry("robots.ai-retrieval", ""), Map.entry("robots.ai-user", ""), Map.entry("geo.speakable", ""),
|
||||
Map.entry("software.os", ""), Map.entry("software.currency", ""), Map.entry("org.sameas", ""),
|
||||
Map.entry("geo.enabled", true), Map.entry("software.enabled", true), Map.entry("software.name", "App"),
|
||||
Map.entry("software.price", "0"));
|
||||
|
||||
@BeforeEach
|
||||
void freshValidators() {
|
||||
CrawlConditional.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDeclaredDefaultsAreTheCodeFallbacks() {
|
||||
// Every key with a declared default — so a key added later without its twin in code fails here.
|
||||
assertEquals(java.util.Set.of("jsonld.enabled", "jsonld.type", "jsonld.breadcrumbs", "org.sameas",
|
||||
"sitemap.enabled", "robots.ai-policy", "robots.ai-training", "robots.ai-retrieval",
|
||||
"robots.ai-user", "geo.enabled", "geo.speakable", "software.enabled", "software.os",
|
||||
"software.currency", "indexnow.enabled"),
|
||||
TestSettings.declaredDefaults().keySet(), "the set of declared per-site defaults this test covers");
|
||||
for (Map<String, Object> stored : List.of(Map.<String, Object>of(), BLANKS,
|
||||
Map.<String, Object>of("geo.enabled", true, "software.enabled", true, "software.name", "App",
|
||||
"software.price", "0", "org.name", "Acme Corp"))) {
|
||||
assertEquals(render(TestSettings.bare().site("acme", stored)),
|
||||
render(TestSettings.declared().site("acme", stored)), "stored: " + stored);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRenderingIsNotTriviallyEmpty() {
|
||||
String all = render(TestSettings.declared().site("acme", Map.of("geo.enabled", true)));
|
||||
assertFalse(all.isBlank());
|
||||
for (String part : List.of("\"@type\":\"WebSite\"", "SpeakableSpecification", "<urlset", "## Pages",
|
||||
"User-agent: *", "Sitemap: https://acme.test/sitemap.xml")) {
|
||||
assertTrue(all.contains(part), "the comparison covers " + part);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every settings-driven surface, concatenated: head JSON-LD, robots.txt, sitemap, llms.txt, card values. */
|
||||
private static String render(PluginSettings settings) {
|
||||
CrawlConditional.reset();
|
||||
ContentRef about = ContentRef.of("about", "/about", Map.of(), List.of(EN), Map.of("en", "About"),
|
||||
Map.of("en", "Who"), "__site__/acme/about", Instant.parse("2026-07-17T10:00:00Z"));
|
||||
ContentRef home = ContentRef.of("index", "/", Map.of(), List.of(EN), Map.of("en", "Home"), Map.of(),
|
||||
"__site__/acme/index", Instant.parse("2026-07-17T10:00:00Z"));
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", Entries.page(home, SITE)).entry("acme", Entries.page(about, SITE));
|
||||
StringBuilder out = new StringBuilder();
|
||||
StructuredDataHead head = new StructuredDataHead(settings, Map.of());
|
||||
for (String path : List.of("/", "/about")) {
|
||||
PageMeta meta = new PageMeta(path.equals("/") ? "index" : "about", "T", "D", List.of(EN), EN, true, false);
|
||||
out.append(head.render(new HeadContext(SITE, meta, EN, "https://acme.test" + path,
|
||||
"https://acme.test" + path, List.of(), false, false))).append('\n');
|
||||
}
|
||||
DiscoverabilityProperties props = new DiscoverabilityProperties();
|
||||
out.append(text(new RobotsTxtEndpoint(settings, props).handle(req("/robots.txt"))));
|
||||
out.append(text(new SitemapEndpoint(catalog, settings).handle(req("/sitemap.xml"))));
|
||||
out.append(text(new LlmsTxtEndpoint(catalog, settings).handle(req("/llms.txt"))));
|
||||
out.append(new IndexNowKeyEndpoint(settings, props).handle(req("/indexnow-key.txt")).status()).append('\n');
|
||||
DiscoverAdminModel model = new DiscoverAdminModel(settings, catalog);
|
||||
out.append(model.jsonldEnabled("acme")).append(model.jsonldType("acme")).append(model.sitemapEnabled("acme"))
|
||||
.append(model.geoEnabled("acme")).append(model.orgConfigured("acme")).append('\n');
|
||||
out.append(new FaqAdvisoryCheck(settings).inspect(new PageView(SITE,
|
||||
new PageMeta("faq", "F", "", List.of(EN), EN, true, false), EN, "https://acme.test/faq",
|
||||
"<details><summary>a</summary>b</details><details><summary>c</summary>d</details>")));
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static RouteRequest req(String path) {
|
||||
return new RouteRequest(SITE, EN, "GET", path, Map.of(), Map.of(), new byte[0], Map.of(), null, "");
|
||||
}
|
||||
|
||||
private static String text(mx.quest.runway.spi.model.RouteResponse response) {
|
||||
return response.status() + "\n" + new String(response.body(), StandardCharsets.UTF_8) + "\n";
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
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.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.EndpointContributor;
|
||||
import mx.quest.runway.spi.HeadContributor;
|
||||
import mx.quest.runway.spi.PageQualityCheck;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
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 mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name rule,
|
||||
* the bean names the templates reference, the app-level settings binding, the descriptor (SPI floor, release
|
||||
* version) 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 DiscoverabilityConfigTest {
|
||||
|
||||
private static final String PREFIX = "discoverability";
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(DiscoverabilityConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromSpiServicesUnderPrefixedNamesAndBindsTheAppSettings() {
|
||||
SiteView acme = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().entry("acme", Entries.page(
|
||||
ContentRef.of("about", "/about", Map.of(), List.of(EN), Map.of("en", "About"), Map.of(),
|
||||
"__site__/acme/about", null), acme));
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
// What the host provides: the SPI services, and Spring Boot's @ConfigurationProperties binding.
|
||||
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("app-level", Map.of(
|
||||
"runway.plugin.discoverability.indexnow.enabled", "true",
|
||||
"runway.plugin.discoverability.indexnow.max-urls-per-submission", "7",
|
||||
"runway.plugin.discoverability.robots.ai-default", "disallow")));
|
||||
ConfigurationPropertiesBindingPostProcessor.register(ctx);
|
||||
ctx.registerBean(PluginSettings.class, () -> TestSettings.declared().site("acme", Map.of("org.name", "Acme")));
|
||||
ctx.registerBean(ContentCatalogView.class, () -> catalog);
|
||||
ctx.registerBean(Sites.class, () -> new FakeSiteServices().site(acme));
|
||||
ctx.register(DiscoverabilityConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
for (String name : ctx.getBeanDefinitionNames()) {
|
||||
if (ctx.getBeanFactory().getBeanDefinition(name).getFactoryBeanName() != null) {
|
||||
assertTrue(name.startsWith(PREFIX), "every plugin bean carries the plugin id: " + name);
|
||||
}
|
||||
}
|
||||
assertInstanceOf(StructuredDataHead.class, ctx.getBean("discoverabilityStructuredData", HeadContributor.class));
|
||||
assertInstanceOf(SitemapEndpoint.class, ctx.getBean("discoverabilitySitemap", EndpointContributor.class));
|
||||
assertInstanceOf(LlmsTxtEndpoint.class, ctx.getBean("discoverabilityLlms", EndpointContributor.class));
|
||||
assertInstanceOf(RobotsTxtEndpoint.class, ctx.getBean("discoverabilityRobots", EndpointContributor.class));
|
||||
assertInstanceOf(IndexNowKeyEndpoint.class,
|
||||
ctx.getBean("discoverabilityIndexNowKey", EndpointContributor.class));
|
||||
assertInstanceOf(FaqAdvisoryCheck.class, ctx.getBean("discoverabilityFaqAdvisory", PageQualityCheck.class));
|
||||
assertEquals(List.of("discoverabilityIndexNow"), List.of(ctx.getBeanNamesForType(SiteEventListener.class)),
|
||||
"IndexNow is collected by the host as a SiteEventListener");
|
||||
|
||||
DiscoverabilityProperties props = ctx.getBean("discoverabilityProperties", DiscoverabilityProperties.class);
|
||||
assertTrue(props.getIndexnow().isEnabled(), "app-level settings bind through the named @Bean");
|
||||
assertEquals(7, props.getIndexnow().getMaxUrlsPerSubmission());
|
||||
assertEquals("disallow", props.getRobots().getAiDefault());
|
||||
assertEquals(1, ctx.getBeanNamesForType(DiscoverabilityProperties.class).length,
|
||||
"one properties bean — no second one under @EnableConfigurationProperties' generated name");
|
||||
|
||||
DiscoverAdminModel model = ctx.getBean("discoverabilityAdminModel", DiscoverAdminModel.class);
|
||||
assertEquals(1, model.pageCount("acme"), "the admin model counts the injected listing");
|
||||
assertTrue(model.orgConfigured("acme"), "…and reads the injected settings");
|
||||
assertEquals(0, model.pageCount("other"));
|
||||
assertEquals(0, model.pageCount(null), "no tenant bound → 0, not an error page");
|
||||
assertEquals(0, model.pageCount("../x"), "a malformed id → 0, not an error page");
|
||||
assertTrue(model.jsonldEnabled(null), "no tenant → the defaults");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
assertEquals(Set.of("discoverabilityProperties", "discoverabilityStructuredData", "discoverabilitySitemap",
|
||||
"discoverabilityLlms", "discoverabilityRobots", "discoverabilityIndexNowKey", "discoverabilityIndexNow",
|
||||
"discoverabilityFaqAdvisory", "discoverabilityPageType", "discoverabilityAdminModel"),
|
||||
beanMethodNames());
|
||||
for (Method m : DiscoverabilityConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
assertEquals(0, bean.name().length + bean.value().length,
|
||||
"the bean name is the method name (" + m.getName() + "), never an alias to keep in sync");
|
||||
}
|
||||
}
|
||||
assertFalse(DiscoverabilityConfig.class.isAnnotationPresent(
|
||||
org.springframework.boot.context.properties.EnableConfigurationProperties.class),
|
||||
"@EnableConfigurationProperties would register an unprefixed bean name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException {
|
||||
Set<String> referenced = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
Matcher m = Pattern.compile("\\$\\{\\s*!?\\s*@(\\w+)").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("discoverabilityAdminModel"), referenced, "the console templates read the admin model only");
|
||||
assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = TestSettings.descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"),
|
||||
"HeadContext.origin() (a host-less site's absolute JSON-LD) arrived in SPI 1.0.0");
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-discoverability</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals("2.3.0", version.group(1));
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree");
|
||||
String defaultBuild = pom.substring(0, pom.indexOf("<profiles>"));
|
||||
assertFalse(defaultBuild.contains("<artifactId>runway-app</artifactId>"),
|
||||
"no runway-app dependency outside the host-it profile");
|
||||
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T18:56:00Z</project.build.outputTimestamp>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePluginStoresNoPerSiteFilesSoItDeclaresNoPersonalData() {
|
||||
assertFalse(TestSettings.descriptor().containsKey("siteData"),
|
||||
"nothing under sites/<id>/plugins/discoverability/ — its settings file is not personal data");
|
||||
}
|
||||
|
||||
@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 >= 25, "the compiled classes were found (" + scanned + ")");
|
||||
assertTrue(problems.isEmpty(), "host linkage: " + problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
|
||||
/**
|
||||
* Builds the {@link CatalogEntry} the host would list for a {@link ContentRef}, applying the kernel's documented URL
|
||||
* rule (its single URL authority, mirrored here so unit tests need no kernel): one URL per <b>available</b> locale —
|
||||
* the item's declared locales the site serves, else the site default — each the locale's localized path under
|
||||
* {@code /<lang>} (no prefix for the site default); the canonical of each URL is the item's override as given; the
|
||||
* {@code x-default} is the primary locale's URL, or — when the site does not serve the primary — the first available
|
||||
* locale's (SPI 1.0.0; until then it was clamped to the site default, an address the item may not exist at).
|
||||
* The host-it profile checks this mirror against the real kernel ({@code HostCatalogParityTest}).
|
||||
*/
|
||||
final class Entries {
|
||||
|
||||
private Entries() {
|
||||
}
|
||||
|
||||
static CatalogEntry of(String sourceKey, ContentRef ref, SiteView site) {
|
||||
Locale def = site.defaultLocale();
|
||||
List<Locale> available = new ArrayList<>();
|
||||
for (Locale locale : ref.locales()) {
|
||||
if (site.locales().contains(locale)) {
|
||||
available.add(locale);
|
||||
}
|
||||
}
|
||||
if (available.isEmpty()) {
|
||||
available.add(def);
|
||||
}
|
||||
List<LocalizedUrl> urls = new ArrayList<>();
|
||||
for (Locale locale : available) {
|
||||
urls.add(new LocalizedUrl(locale, url(ref, locale, def), ref.canonical()));
|
||||
}
|
||||
Locale primary = ref.primaryLocale(def);
|
||||
if (!site.locales().contains(primary)) {
|
||||
primary = available.get(0);
|
||||
}
|
||||
return new CatalogEntry(sourceKey, ref, urls, url(ref, primary, def));
|
||||
}
|
||||
|
||||
static CatalogEntry page(ContentRef ref, SiteView site) {
|
||||
return of("pages", ref, site);
|
||||
}
|
||||
|
||||
private static String url(ContentRef ref, Locale locale, Locale def) {
|
||||
String path = ref.pathFor(locale);
|
||||
return locale.equals(def) ? path : "/" + locale.getLanguage() + path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* FaqAdvisoryCheck: flags an unmarked on-page FAQ ({@code <details>/<summary>} clusters), stays silent below the
|
||||
* threshold, when there's no FAQ, on a noindex page, and when the head renders the page as an {@code FAQPage}.
|
||||
*/
|
||||
class FaqAdvisoryCheckTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final FaqAdvisoryCheck check = new FaqAdvisoryCheck(config);
|
||||
|
||||
private void cfg(Map<String, Object> map) {
|
||||
config.site("acme", map);
|
||||
}
|
||||
|
||||
private static final String TWO_FAQ =
|
||||
"<main><details><summary>Why ranges?</summary>Scope drives cost.</details>"
|
||||
+ "<details><summary>Fixed fee?</summary>Yes, usually.</details></main>";
|
||||
|
||||
private static PageView page(String path, String html) {
|
||||
return page(path, html, false);
|
||||
}
|
||||
|
||||
private static PageView page(String path, String html, boolean noindex) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta meta = new PageMeta(path.substring(1), "T", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
noindex);
|
||||
return new PageView(site, meta, Locale.ENGLISH, "https://acme.test" + path, html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void flagsAnUnmarkedOnPageFaq() {
|
||||
cfg(Map.of()); // no content.schema → the FAQ is not typed
|
||||
List<Finding> found = check.inspect(page("/pricing", TWO_FAQ));
|
||||
assertEquals(1, found.size(), found.toString());
|
||||
assertEquals("discoverability.faq.unmarked", found.get(0).code());
|
||||
assertEquals("INFO", found.get(0).severity().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentWhenTheFaqIsAlreadyTyped() {
|
||||
cfg(Map.of("content.schema", "/pricing:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n"));
|
||||
assertTrue(check.inspect(page("/pricing", TWO_FAQ)).isEmpty(), "already FAQPage-typed → no nag");
|
||||
}
|
||||
|
||||
/** "Already typed" means the head renders the page as an FAQPage, the same answer PageTypes gives it. */
|
||||
@Test
|
||||
void aTypeTheHeadDoesNotApplyDoesNotCountAsTyped() {
|
||||
cfg(Map.of("content.schema", "/pricing:\n type: faqpage\n faq:\n - { q: Q, a: A }\n"));
|
||||
List<Finding> misspelt = check.inspect(page("/pricing", TWO_FAQ));
|
||||
assertEquals(1, misspelt.size(), "faqpage is an unknown type, the page is a WebPage: " + misspelt);
|
||||
assertEquals("discoverability.faq.unmarked", misspelt.get(0).code());
|
||||
cfg(Map.of("content.schema",
|
||||
"/pricing:\n - type: AboutPage\n - type: FAQPage\n faq:\n - { q: Q, a: A }\n"));
|
||||
assertEquals(1, check.inspect(page("/pricing", TWO_FAQ)).size(),
|
||||
"a second page type is ignored, so the page is an AboutPage");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentWhenStructuredDataIsOff() {
|
||||
cfg(Map.of("jsonld.enabled", false));
|
||||
assertTrue(check.inspect(page("/pricing", TWO_FAQ)).isEmpty(), "the head publishes no JSON-LD at all");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentOnANoindexPage() {
|
||||
cfg(Map.of());
|
||||
assertTrue(check.inspect(page("/pricing", TWO_FAQ, true)).isEmpty(), "noindex pages carry no structured data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentBelowTheDisclosureThreshold() {
|
||||
cfg(Map.of());
|
||||
assertTrue(check.inspect(page("/x", "<details><summary>Q</summary>A</details>")).isEmpty(),
|
||||
"a lone <details> is a 'read more', not an FAQ");
|
||||
assertTrue(check.inspect(page("/y", "<p>no faq here</p>")).isEmpty(), "no disclosures at all");
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentOnEmptyHtml() {
|
||||
cfg(Map.of());
|
||||
assertTrue(check.inspect(page("/z", "")).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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 static org.mockito.Mockito.mock;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.content.ContentCatalog;
|
||||
import mx.quest.runway.content.ContentCatalogViewImpl;
|
||||
import mx.quest.runway.content.ContentSourceRegistry;
|
||||
import mx.quest.runway.content.RoutableContent;
|
||||
import mx.quest.runway.page.ContentUrls;
|
||||
import mx.quest.runway.page.LocaleUrls;
|
||||
import mx.quest.runway.page.PageStore;
|
||||
import mx.quest.runway.page.RenderModelBuilder;
|
||||
import mx.quest.runway.spi.ContentSource;
|
||||
import mx.quest.runway.spi.model.Alternate;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentBody;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* host-it: the sitemap and llms.txt over the REAL kernel catalog ({@code ContentCatalog} behind the kernel's
|
||||
* {@code ContentCatalogViewImpl}), compared with what 1.6.0 computed from the same catalog through the kernel's URL
|
||||
* builders ({@code ContentUrls}, {@code LocaleUrls}) — the before/after proof at unit level, plus the head-vs-sitemap
|
||||
* agreement and the test fixture mirror ({@code Entries}) checked against the kernel.
|
||||
*/
|
||||
class HostCatalogParityTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final Locale FR = Locale.FRENCH;
|
||||
private static final Instant T = Instant.parse("2026-07-17T10:00:00Z");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
|
||||
private static ContentRef ref(String id, String path, Map<String, String> localized, List<Locale> locales,
|
||||
boolean published, boolean noindex, String canonical) {
|
||||
return new ContentRef(id, path, localized, locales, Map.of("en", "T " + id, "es", "T-es " + id),
|
||||
Map.of("en", "D " + id), null, "__site__/acme/" + id, published, T, noindex, canonical, null, Map.of());
|
||||
}
|
||||
|
||||
/** Everything the URL rule distinguishes: locales, localized slugs, an unserved locale, canonicals, noindex. */
|
||||
private static final List<ContentRef> PAGES = List.of(
|
||||
ref("index", "/", Map.of(), List.of(EN, ES), true, false, null),
|
||||
ref("about", "/about", Map.of("es", "/acerca"), List.of(EN, ES), true, false, null),
|
||||
ref("en-only", "/en-only", Map.of(), List.of(), true, false, null),
|
||||
ref("fr-and-es", "/fr-es", Map.of(), List.of(FR, ES), true, false, null),
|
||||
ref("french", "/french", Map.of(), List.of(FR), true, false, null),
|
||||
ref("es-only", "/solo", Map.of("es", "/solo-es"), List.of(ES), true, false, null),
|
||||
ref("draft", "/draft", Map.of(), List.of(EN), false, false, null),
|
||||
ref("hidden", "/hidden", Map.of(), List.of(EN), true, true, null),
|
||||
ref("dupe", "/dupe", Map.of(), List.of(EN), true, false, "https://acme.test/about"),
|
||||
ref("self", "/self", Map.of(), List.of(EN), true, false, "https://acme.test/self"),
|
||||
ref("reserved", "/login", Map.of(), List.of(EN), true, false, null));
|
||||
private static final List<ContentRef> POSTS = List.of(
|
||||
ref("hello", "/blog/hello", Map.of("es", "/blog/hola"), List.of(EN, ES), true, false, null));
|
||||
|
||||
private static ContentSource source(String key, List<ContentRef> refs) {
|
||||
return new ContentSource() {
|
||||
@Override public String key() { return key; }
|
||||
@Override public List<ContentRef> enumerate(SiteView site) { return refs; }
|
||||
@Override public ContentBody body(SiteView site, String id, Locale locale) {
|
||||
throw new IllegalStateException("the crawl surfaces never read a body");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private ContentCatalog catalog;
|
||||
private ContentCatalogViewImpl view;
|
||||
|
||||
@BeforeEach
|
||||
void kernel() {
|
||||
CrawlConditional.reset();
|
||||
ContentSource broken = new ContentSource() {
|
||||
@Override public String key() { return "broken"; }
|
||||
@Override public List<ContentRef> enumerate(SiteView site) { throw new IllegalStateException("boom"); }
|
||||
@Override public ContentBody body(SiteView site, String id, Locale locale) { return ContentBody.empty(); }
|
||||
};
|
||||
catalog = new ContentCatalog(new ContentSourceRegistry(
|
||||
List.of(source("pages", PAGES), broken, source("blog", POSTS))));
|
||||
view = new ContentCatalogViewImpl(catalog, new FakeSiteServices().site(SITE), mock(PageStore.class));
|
||||
}
|
||||
|
||||
private static RouteRequest req(String path) {
|
||||
return new RouteRequest(SITE, EN, "GET", path, Map.of(), Map.of(), new byte[0], Map.of(), null, "");
|
||||
}
|
||||
|
||||
private static String body(mx.quest.runway.spi.model.RouteResponse r) {
|
||||
assertEquals(200, r.status());
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTestFixtureMirrorBuildsExactlyTheKernelsEntries() {
|
||||
for (CatalogEntry kernelEntry : view.entries("acme")) {
|
||||
assertEquals(kernelEntry, Entries.of(kernelEntry.sourceKey(), kernelEntry.ref(), SITE),
|
||||
kernelEntry.compositeId());
|
||||
}
|
||||
assertEquals(10, view.entries("acme").size(),
|
||||
"the published, unreserved items of the healthy sources (noindex is listed; the sitemap drops it)");
|
||||
}
|
||||
|
||||
/**
|
||||
* The 2.0.0 sitemap over the kernel's listing equals the document 1.6.0 built from the same catalog with the
|
||||
* kernel's builders — except the one documented fix in this fixture: none (the fixture's canonicals are absolute).
|
||||
*/
|
||||
@Test
|
||||
void theSitemapIsTheOneOnePointSixBuiltFromTheSameCatalog() {
|
||||
String now = body(new SitemapEndpoint(view, TestSettings.declared()).handle(req("/sitemap.xml")));
|
||||
assertEquals(sitemapAsOnePointSixBuiltIt(), now);
|
||||
assertFalse(now.contains("/draft") || now.contains("/login") || now.contains("/hidden")
|
||||
|| now.contains("/dupe"), now);
|
||||
assertTrue(now.contains("<loc>https://acme.test/blog/hola</loc>") == false
|
||||
&& now.contains("<loc>https://acme.test/es/blog/hola</loc>"), "a healthy source survives a broken one");
|
||||
}
|
||||
|
||||
/**
|
||||
* llms.txt equals 1.6.0's except where an item does not exist at the address 1.6.0 linked (an item missing from
|
||||
* the default locale, fixed in 2.0.0) and — from the SPI 1.0.0 kernel — an item whose primary locale the site does
|
||||
* not serve, whose x-default is now its first available locale's real address.
|
||||
*/
|
||||
@Test
|
||||
void llmsTxtIsTheOneOnePointSixBuiltExceptTheN6Fix() {
|
||||
String now = body(new LlmsTxtEndpoint(view, TestSettings.declared().site("acme", Map.of("geo.enabled", true)))
|
||||
.handle(req("/llms.txt")));
|
||||
String before = llmsAsOnePointSixBuiltIt();
|
||||
assertEquals(before.replace("(https://acme.test/solo)", "(https://acme.test/es/solo-es)")
|
||||
.replace("(https://acme.test/fr-es)", "(https://acme.test/es/fr-es)"), now,
|
||||
"only the two items that do not exist at the unprefixed path moved — to their real Spanish URLs");
|
||||
assertTrue(before.contains("(https://acme.test/solo)"), "1.6.0 linked the unprefixed path, which 404s");
|
||||
// fr-and-es: French first, Spanish served. Before SPI 1.0.0 the kernel clamped its x-default to the site
|
||||
// default, so CatalogEntry.pathFor fell back to the unprefixed /fr-es (a 404), as 1.6.0 did.
|
||||
assertTrue(before.contains("(https://acme.test/fr-es)"), before);
|
||||
assertTrue(now.contains("(https://acme.test/es/fr-es)"), now);
|
||||
}
|
||||
|
||||
@Test
|
||||
void headAlternatesAndSitemapAlternatesProvablyAgree() {
|
||||
String xml = body(new SitemapEndpoint(view, TestSettings.declared()).handle(req("/sitemap.xml")));
|
||||
for (RoutableContent item : catalog.enumerate(SITE)) {
|
||||
if (item.ref().noindex() || item.ref().canonical() != null) {
|
||||
continue;
|
||||
}
|
||||
List<Alternate> head = new RenderModelBuilder()
|
||||
.headContext(SITE, item, EN, "https://acme.test", false).alternates();
|
||||
for (Alternate alternate : head) {
|
||||
String link = "hreflang=\"" + alternate.hreflang() + "\" href=\"" + alternate.url() + "\"";
|
||||
assertTrue(xml.contains(link), "the sitemap carries the head's exact alternate: " + link);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 1.6.0's algorithms, verbatim in substance, over the kernel's builders --------------------------------
|
||||
|
||||
private String sitemapAsOnePointSixBuiltIt() {
|
||||
String base = "https://acme.test";
|
||||
record Entry(String url, String block, String lastmod) { }
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
for (RoutableContent item : catalog.enumerate(SITE)) {
|
||||
if (item.ref().noindex()) {
|
||||
continue;
|
||||
}
|
||||
List<Alternate> alternates = ContentUrls.alternates(item, SITE, base);
|
||||
String xDefault = ContentUrls.xDefault(item, SITE, base);
|
||||
String canonical = item.ref().canonical();
|
||||
if (canonical != null && !canonical.isBlank()) {
|
||||
String want = canonical.trim();
|
||||
if (alternates.stream().noneMatch(a -> a.url().equals(want)) && !want.equals(xDefault)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
StringBuilder links = new StringBuilder();
|
||||
for (Alternate alt : alternates) {
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"").append(alt.hreflang())
|
||||
.append("\" href=\"").append(alt.url()).append("\"/>\n");
|
||||
}
|
||||
links.append(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"").append(xDefault)
|
||||
.append("\"/>\n");
|
||||
for (Alternate self : alternates) {
|
||||
entries.add(new Entry(self.url(), links.toString(), item.ref().updatedAt().toString()));
|
||||
}
|
||||
}
|
||||
entries.sort(Comparator.comparing(Entry::url));
|
||||
StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\""
|
||||
+ " xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n");
|
||||
for (Entry e : entries) {
|
||||
xml.append(" <url>\n <loc>").append(e.url()).append("</loc>\n <lastmod>").append(e.lastmod())
|
||||
.append("</lastmod>\n").append(e.block()).append(" </url>\n");
|
||||
}
|
||||
return xml.append("</urlset>\n").toString();
|
||||
}
|
||||
|
||||
private String llmsAsOnePointSixBuiltIt() {
|
||||
StringBuilder out = new StringBuilder("# Acme\n\n## Pages\n\n");
|
||||
for (RoutableContent item : catalog.enumerate(SITE)) {
|
||||
if (item.ref().noindex()) {
|
||||
continue;
|
||||
}
|
||||
out.append("- [").append(item.titleFor(EN)).append("](https://acme.test")
|
||||
.append(LocaleUrls.urlFor(item, EN, EN)).append("): ").append(item.descriptionFor(EN))
|
||||
.append('\n');
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.PluginSettingDef;
|
||||
import mx.quest.runway.plugin.SitePluginConfigService;
|
||||
import mx.quest.runway.plugin.spi.PluginSettingsImpl;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* host-it: the descriptor through the KERNEL's own parser, and the settings the kernel's {@code PluginSettingsImpl}
|
||||
* hands this plugin compared with the fake every unit test uses ({@code TestSettings}) — so the unit tests' premise
|
||||
* (declared defaults overlaid by stored values) is the kernel's behaviour, not an assumption.
|
||||
*/
|
||||
class HostDescriptorTest {
|
||||
|
||||
private static PluginDescriptor descriptor() throws IOException {
|
||||
try (InputStream in = Files.newInputStream(Path.of("plugin.yml"))) {
|
||||
return PluginDescriptor.read(in);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKernelParsesTheDescriptorWithEveryLayoutKey() throws IOException {
|
||||
PluginDescriptor d = descriptor();
|
||||
assertEquals("discoverability", d.id());
|
||||
// The release number is asserted once, in DiscoverabilityConfigTest (the default build); here the kernel's
|
||||
// parse is compared with the descriptor, so a version bump does not have to remember this profile's test.
|
||||
assertEquals(String.valueOf(TestSettings.descriptor().get("version")), d.version());
|
||||
assertEquals(6, d.settingGroups().size());
|
||||
Map<String, PluginSettingDef> site = new LinkedHashMap<>();
|
||||
d.siteSettings().forEach(def -> site.put(def.key(), def));
|
||||
assertEquals("app:robots.ai-default", site.get("robots.ai-policy").inheritsFrom());
|
||||
assertEquals("indexnow.enabled", site.get("indexnow.enabled").requiresPlatform());
|
||||
assertEquals("jsonld.enabled", site.get("jsonld.type").showWhen());
|
||||
assertTrue(site.get("content.schema").advanced());
|
||||
for (PluginSettingDef def : d.siteSettings()) {
|
||||
assertNotNull(def.group(), def.key());
|
||||
assertNotNull(def.help(), def.key());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKernelsSettingsMergeIsTheOneTheUnitTestsAssume() throws IOException {
|
||||
List<PluginSettingDef> schema = descriptor().siteSettings();
|
||||
for (Map<String, Object> stored : List.<Map<String, Object>>of(Map.of(),
|
||||
Map.of("jsonld.type", "", "geo.enabled", true, "geo.speakable", List.of("h1"), "org.name", "Acme",
|
||||
"unknown.key", "kept"))) {
|
||||
SitePluginConfigService config = mock(SitePluginConfigService.class);
|
||||
when(config.config(anyString(), eq("discoverability"))).thenReturn(stored);
|
||||
PluginSettingsImpl kernel = new PluginSettingsImpl("discoverability", schema, config, null);
|
||||
assertEquals(TestSettings.declared().site("acme", stored).site("acme").values(),
|
||||
kernel.site("acme").values(), "stored: " + stored);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.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.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.config.EmbeddedValueResolver;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.context.expression.StandardBeanExpressionResolver;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
/**
|
||||
* IndexNow: the payload, the two switches, and the bounds.
|
||||
*
|
||||
* <h2>What is worth testing here</h2>
|
||||
* The protocol itself is four JSON fields — there is nothing clever to get right. What can go wrong is
|
||||
* everything <b>around</b> it, and all of it fails quietly:
|
||||
*
|
||||
* <ul>
|
||||
* <li>a switch that does not actually gate, so a deployment starts making outbound calls it never agreed to;</li>
|
||||
* <li>a bound that does not bound, so one tenant's bulk edit becomes an unbounded request;</li>
|
||||
* <li>an unescaped tenant-controlled value in a hand-built JSON body.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The HTTP call is the injected {@link IndexNowSubmitter.Exchange} seam, so every one of those is exercised
|
||||
* with no network at all — and the recording exchange makes "did anything go out?" an assertion rather than an
|
||||
* assumption.
|
||||
*/
|
||||
class IndexNowSubmitterTest {
|
||||
|
||||
/** An exchange that answers 200 and remembers every call — so "nothing went out" is provable. */
|
||||
private static final class Recorder implements IndexNowSubmitter.Exchange {
|
||||
|
||||
private final List<String> payloads = new ArrayList<>();
|
||||
private int status = 200;
|
||||
|
||||
@Override
|
||||
public Response post(String url, String json) {
|
||||
payloads.add(json);
|
||||
return new Response(status, "ok");
|
||||
}
|
||||
}
|
||||
|
||||
private static DiscoverabilityProperties props(boolean platformEnabled) {
|
||||
DiscoverabilityProperties p = new DiscoverabilityProperties();
|
||||
p.getIndexnow().setEnabled(platformEnabled);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static PluginSettings config(Map<String, Object> cfg) {
|
||||
return TestSettings.declared().site("acme", cfg);
|
||||
}
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private static LocalizedUrl url(Locale locale, String path) {
|
||||
return new LocalizedUrl(locale, path, null);
|
||||
}
|
||||
|
||||
/** A local page change, as the host delivers it: the item's URLs before and after. */
|
||||
private static CatalogChange page(String slug, List<LocalizedUrl> before, List<LocalizedUrl> after) {
|
||||
return new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", slug, null, before, after, true);
|
||||
}
|
||||
|
||||
/** A submitter with both switches on, a key, and a site at https://acme.test. */
|
||||
private static IndexNowSubmitter enabled(IndexNowSubmitter.Exchange exchange) {
|
||||
return new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange);
|
||||
}
|
||||
|
||||
// --- the payload ---------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void thePayloadCarriesTheFourFieldsTheProtocolNeeds() {
|
||||
String json = IndexNowSubmitter.payload("acme.test", "abc123",
|
||||
"https://acme.test/indexnow-key.txt", List.of("https://acme.test/a", "https://acme.test/b"));
|
||||
|
||||
assertEquals("{\"host\":\"acme.test\",\"key\":\"abc123\","
|
||||
+ "\"keyLocation\":\"https://acme.test/indexnow-key.txt\","
|
||||
+ "\"urlList\":[\"https://acme.test/a\",\"https://acme.test/b\"]}", json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tenant-controlled values are escaped.
|
||||
*
|
||||
* <p>{@code host}, {@code key} and {@code keyLocation} all come from per-site configuration, and this body
|
||||
* is assembled by hand. An unescaped quote there is a payload-injection hole, not a formatting bug — and
|
||||
* one that only shows up when somebody puts a quote in a setting.
|
||||
*/
|
||||
@Test
|
||||
void tenantControlledValuesCannotBreakOutOfTheJson() {
|
||||
String json = IndexNowSubmitter.payload("acme.test", "ab\"c\\d\ne", "https://acme.test/k.txt",
|
||||
List.of("https://acme.test/a\"b"));
|
||||
|
||||
assertFalse(json.contains("ab\"c"), json);
|
||||
assertTrue(json.contains("ab\\\"c\\\\d\\ne"), json);
|
||||
assertTrue(json.contains("https://acme.test/a\\\"b"), json);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHostFieldIsTheBareHostname() {
|
||||
assertEquals("acme.test", IndexNowSubmitter.hostOf("https://acme.test"));
|
||||
assertEquals("acme.test", IndexNowSubmitter.hostOf("https://acme.test/some/path"));
|
||||
assertEquals("", IndexNowSubmitter.hostOf("not a url"));
|
||||
}
|
||||
|
||||
// --- the two switches ----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A tenant cannot switch on outbound traffic by itself.
|
||||
*
|
||||
* <p>The platform operator owns the network, the egress firewall and the incident. This is the assertion
|
||||
* that the operator's switch is a real gate rather than a label — and it is made against whether anything
|
||||
* left the process, because that is what "off" has to mean.
|
||||
*/
|
||||
@Test
|
||||
void nothingIsSubmittedWhenThePlatformHasNotPermittedIt() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc")), props(false), exchange);
|
||||
|
||||
// Through submit(), NOT flush(): flush() returns early on an empty queue, so a flush-based version of
|
||||
// this test passes whether or not the gate exists. A test of a switch has to be able to fail when the
|
||||
// switch is removed, and this one does — it is the same "asserting nothing" shape as scanning a
|
||||
// compressed archive for a plaintext secret.
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty(), "the platform switch must gate the network, not just the UI");
|
||||
}
|
||||
|
||||
/** The documented WARN for a site that wants IndexNow while the platform says no — and only for such a site. */
|
||||
@Test
|
||||
void aSiteThatEnabledItWhileThePlatformHasNotIsWarnedOnce() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter wants = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc")), props(false), exchange);
|
||||
wants.onCatalogChanged(page("home", List.of(), List.of(url(EN, "/"))));
|
||||
wants.onCatalogChanged(page("about", List.of(url(EN, "/about")), List.of(url(EN, "/about"))));
|
||||
assertTrue(wants.warnedInert("acme"), "the operator is told which setting to flip");
|
||||
assertTrue(exchange.payloads.isEmpty(), "and still nothing leaves the process");
|
||||
|
||||
IndexNowSubmitter doesNot = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of()), props(false), new Recorder());
|
||||
doesNot.onCatalogChanged(page("home", List.of(), List.of(url(EN, "/"))));
|
||||
assertFalse(doesNot.warnedInert("acme"), "a site that never asked for it is not warned about it");
|
||||
}
|
||||
|
||||
/** …and the positive control: the identical call DOES submit once the platform permits it. */
|
||||
@Test
|
||||
void theSameCallSubmitsOnceThePlatformPermitsIt() {
|
||||
Recorder exchange = new Recorder();
|
||||
new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc")), props(true), exchange)
|
||||
.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertEquals(1, exchange.payloads.size(), "otherwise the test above proves only that nothing works");
|
||||
}
|
||||
|
||||
/** …and a site that has not enabled it is not submitted for either. */
|
||||
@Test
|
||||
void nothingIsSubmittedForASiteThatHasNotEnabledIt() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.key", "abc")), props(true), exchange);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty(), "indexnow.enabled defaults false — silence is the default");
|
||||
}
|
||||
|
||||
/** A site with the switch on but no key submits nothing: there would be nothing for the engine to verify. */
|
||||
@Test
|
||||
void nothingIsSubmittedWithoutAKey() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true)), props(true), exchange);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
/** With both switches on and a key set, the submission goes out and names the key file's fixed location. */
|
||||
@Test
|
||||
void bothSwitchesOnSubmitsAndPointsAtTheKeyFile() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "abc123")), props(true), exchange);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertTrue(exchange.payloads.get(0).contains("\"keyLocation\":\"https://acme.test/indexnow-key.txt\""),
|
||||
exchange.payloads.get(0));
|
||||
assertTrue(exchange.payloads.get(0).contains("\"host\":\"acme.test\""), exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
// --- the bounds ----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A submission larger than the cap is trimmed, not sent whole.
|
||||
*
|
||||
* <p>A bulk edit or a restore can change every URL a site has. Without this the body is unbounded, which is
|
||||
* a problem for the endpoint, for the tenant's egress and for anyone reading the log.
|
||||
*/
|
||||
@Test
|
||||
void aSubmissionOverTheCapIsTrimmedRatherThanSentWhole() {
|
||||
Recorder exchange = new Recorder();
|
||||
DiscoverabilityProperties p = props(true);
|
||||
p.getIndexnow().setMaxUrlsPerSubmission(3);
|
||||
List<String> many = new ArrayList<>();
|
||||
for (int i = 0; i < 50; i++) {
|
||||
many.add("https://acme.test/p" + i);
|
||||
}
|
||||
|
||||
new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), p, exchange)
|
||||
.submit("acme", many);
|
||||
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertEquals(3, exchange.payloads.get(0).split("https://acme.test/p", -1).length - 1,
|
||||
exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* A failing endpoint does not throw into the caller, and does not retry.
|
||||
*
|
||||
* <p>A freshness ping that arrives late is worthless, and an unbounded retry queue during an outage is a
|
||||
* liability. The pages are still crawled the ordinary way, so the honest behaviour is to log and drop.
|
||||
*/
|
||||
@Test
|
||||
void aFailingEndpointIsLoggedAndDroppedRatherThanRetried() {
|
||||
IndexNowSubmitter.Exchange failing = (url, json) -> {
|
||||
throw new IOException("connection refused");
|
||||
};
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), failing);
|
||||
|
||||
submitter.submit("acme", List.of("https://acme.test/a")); // must not throw
|
||||
}
|
||||
|
||||
/** A refusal (403 = key file did not verify) is likewise survivable. */
|
||||
@Test
|
||||
void aRefusalIsSurvivable() {
|
||||
Recorder exchange = new Recorder();
|
||||
exchange.status = 403;
|
||||
new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange)
|
||||
.submit("acme", List.of("https://acme.test/a"));
|
||||
|
||||
assertEquals(1, exchange.payloads.size(), "it was attempted");
|
||||
}
|
||||
|
||||
/** A site with no base URL cannot be submitted for — there is no host to name. */
|
||||
@Test
|
||||
void aSiteWithNoBaseUrlIsSkipped() {
|
||||
Recorder exchange = new Recorder();
|
||||
new IndexNowSubmitter(sites("acme", ""),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange)
|
||||
.submit("acme", List.of("/a"));
|
||||
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
// --- what a change queues (the SPI change events) ------------------------------------------------
|
||||
|
||||
/**
|
||||
* A DELETED page reports where it was, and that address is submitted. 1.x resolved the URLs after
|
||||
* the host had dropped the page from its listing, so a deletion — the change most worth telling an engine
|
||||
* about — submitted nothing.
|
||||
*/
|
||||
@Test
|
||||
void aDeletedPagesOldUrlsAreSubmitted() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
|
||||
submitter.onCatalogChanged(page("about", List.of(url(EN, "/about"), url(ES, "/es/acerca")), List.of()));
|
||||
submitter.flush();
|
||||
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertTrue(exchange.payloads.get(0).endsWith(
|
||||
"\"urlList\":[\"https://acme.test/about\",\"https://acme.test/es/acerca\"]}"), exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** A moved item submits the old address AND the new one, each once, previous first. */
|
||||
@Test
|
||||
void aRenameSubmitsTheUnionOfBeforeAndAfterWithoutDuplicates() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
|
||||
submitter.onCatalogChanged(page("about", List.of(url(EN, "/about"), url(ES, "/es/acerca")),
|
||||
List.of(url(EN, "/about-us"), url(ES, "/es/acerca"))));
|
||||
submitter.flush();
|
||||
|
||||
assertTrue(exchange.payloads.get(0).endsWith("\"urlList\":[\"https://acme.test/about\","
|
||||
+ "\"https://acme.test/es/acerca\",\"https://acme.test/about-us\"]}"), exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** A new page has no previous URLs: its current ones are submitted. */
|
||||
@Test
|
||||
void aNewPageSubmitsItsCurrentUrls() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(page("news", List.of(), List.of(url(EN, "/news"))));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.get(0).contains("\"urlList\":[\"https://acme.test/news\"]"));
|
||||
}
|
||||
|
||||
/** A content source's item (a blog entry) is handled exactly like a page. */
|
||||
@Test
|
||||
void aContentSourceChangeIsSubmittedLikeAPage() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "blog", "hello", "blog",
|
||||
List.of(url(EN, "/blog/hello")), List.of(), true));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.get(0).contains("https://acme.test/blog/hello"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A cluster replays every change on its other nodes ({@code local == false}). Only the node where
|
||||
* the change happened submits — otherwise N nodes send N identical submissions.
|
||||
*/
|
||||
@Test
|
||||
void aPeersReplayedChangeIsIgnored() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", "about", null,
|
||||
List.of(url(EN, "/about")), List.of(), false));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty(), "the originating node submits; a replay never does");
|
||||
}
|
||||
|
||||
/** Changes that name no item carry no URLs: a lifecycle event, a settings save, a whole-site reload. */
|
||||
@Test
|
||||
void changesThatNameNoItemQueueNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
EventDispatch events = new EventDispatch("discoverability", Set.of()).listener(submitter);
|
||||
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
|
||||
events.settings("acme", "discoverability");
|
||||
events.page("acme", null, List.of(url(EN, "/x")), List.of());
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
assertTrue(events.failures().isEmpty(), events.failures().toString());
|
||||
}
|
||||
|
||||
/** Delivered the kernel's way (phases, order), a page deletion reaches the queue. */
|
||||
@Test
|
||||
void itIsAConsumerListenerAndADispatchedDeletionReachesTheQueue() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
assertEquals(SiteEventListener.Phase.CONSUMER, submitter.phase(), "it reads URLs after the sources dropped "
|
||||
+ "their state — the phase whose currentUrls the host fills");
|
||||
new EventDispatch("discoverability", Set.of()).listener(submitter)
|
||||
.page("acme", "about", List.of(url(EN, "/about")), List.of());
|
||||
submitter.flush();
|
||||
assertEquals(1, exchange.payloads.size());
|
||||
assertTrue(exchange.payloads.get(0).contains("https://acme.test/about"));
|
||||
}
|
||||
|
||||
/** One flush per batch: queued URLs are submitted once and the queue is emptied. */
|
||||
@Test
|
||||
void aFlushSubmitsOnceAndEmptiesTheQueue() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = enabled(exchange);
|
||||
submitter.onCatalogChanged(page("a", List.of(), List.of(url(EN, "/a"))));
|
||||
submitter.onCatalogChanged(page("b", List.of(), List.of(url(EN, "/b"))));
|
||||
submitter.onCatalogChanged(page("a", List.of(url(EN, "/a")), List.of(url(EN, "/a"))));
|
||||
submitter.flush();
|
||||
submitter.flush();
|
||||
assertEquals(1, exchange.payloads.size(), "a second flush has nothing to send");
|
||||
assertTrue(exchange.payloads.get(0).endsWith("[\"https://acme.test/a\",\"https://acme.test/b\"]}"),
|
||||
exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** The per-site queue is bounded: overflow is dropped (with a WARN), not grown. */
|
||||
@Test
|
||||
void theQueueIsBoundedPerSite() {
|
||||
Recorder exchange = new Recorder();
|
||||
DiscoverabilityProperties p = props(true);
|
||||
p.getIndexnow().setMaxQueuedPerSite(2);
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), p, exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(), List.of(url(EN, "/1"), url(ES, "/es/1"))));
|
||||
submitter.onCatalogChanged(page("y", List.of(), List.of(url(EN, "/2"))));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.get(0).endsWith("[\"https://acme.test/1\",\"https://acme.test/es/1\"]}"),
|
||||
"the overflow was dropped: " + exchange.payloads.get(0));
|
||||
}
|
||||
|
||||
/** With the platform switch off, a change queues nothing — the flush has nothing even if the switch flips. */
|
||||
@Test
|
||||
void withThePlatformOffAChangeQueuesNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
DiscoverabilityProperties p = props(false);
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", "https://acme.test"),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), p, exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(url(EN, "/x")), List.of()));
|
||||
p.getIndexnow().setEnabled(true);
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
/** A site with no configured base URL cannot be submitted for, so nothing is even queued. */
|
||||
@Test
|
||||
void aChangeOnASiteWithNoBaseUrlQueuesNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(sites("acme", null),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(url(EN, "/x")), List.of()));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
/** An unknown site (deleted between the change and now) queues nothing and does not fail the dispatch. */
|
||||
@Test
|
||||
void anUnknownSiteQueuesNothing() {
|
||||
Recorder exchange = new Recorder();
|
||||
IndexNowSubmitter submitter = new IndexNowSubmitter(new FakeSiteServices(),
|
||||
config(Map.of("indexnow.enabled", true, "indexnow.key", "k")), props(true), exchange);
|
||||
submitter.onCatalogChanged(page("x", List.of(url(EN, "/x")), List.of()));
|
||||
submitter.flush();
|
||||
assertTrue(exchange.payloads.isEmpty());
|
||||
}
|
||||
|
||||
private static FakeSiteServices sites(String id, String baseUrl) {
|
||||
return new FakeSiteServices().site(new SiteView(id, "Acme", EN, List.of(EN, ES), baseUrl));
|
||||
}
|
||||
|
||||
/** A hand-set batch interval outside the form's 5..3600 seconds is clamped, never handed to the scheduler as is. */
|
||||
@Test
|
||||
void aHandSetBatchIntervalIsKeptInsideTheFormsRange() throws Exception {
|
||||
String expression =
|
||||
IndexNowSubmitter.class.getMethod("flush").getAnnotation(Scheduled.class).fixedDelayString();
|
||||
assertEquals("60000", delayFor(expression, null), "unset: the 60-second default");
|
||||
assertEquals("60000", delayFor(expression, "60"));
|
||||
assertEquals("5000", delayFor(expression, "0"));
|
||||
assertEquals("5000", delayFor(expression, "-30"));
|
||||
assertEquals("3600000", delayFor(expression, "99999"));
|
||||
}
|
||||
|
||||
private static String delayFor(String expression, String value) {
|
||||
MockEnvironment env = new MockEnvironment();
|
||||
if (value != null) {
|
||||
env.setProperty("runway.plugin.discoverability.indexnow.batch-seconds", value);
|
||||
}
|
||||
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
|
||||
factory.addEmbeddedValueResolver(env::resolveRequiredPlaceholders);
|
||||
factory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
|
||||
return new EmbeddedValueResolver(factory).resolveStringValue(expression);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The JSON-LD core: @id conventions, origin extraction, node building, and safe <script> serialization. */
|
||||
class LdTest {
|
||||
|
||||
@Test
|
||||
void idConventionsAreStableAndAnchored() {
|
||||
assertEquals("https://x.test/#website", Ld.websiteId("https://x.test"));
|
||||
assertEquals("https://x.test/#organization", Ld.organizationId("https://x.test"));
|
||||
assertEquals("https://x.test/about#webpage", Ld.webpageId("https://x.test/about"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void originExtractsSchemeAndHost() {
|
||||
assertEquals("https://x.test", Ld.origin("https://x.test/about?q=1"));
|
||||
assertEquals("http://x.test:8080", Ld.origin("http://x.test:8080/"));
|
||||
assertEquals("", Ld.origin("/relative/path"));
|
||||
assertEquals("", Ld.origin(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scriptWrapsAGraphAndOmitsEmpty() {
|
||||
assertEquals("", Ld.script(List.of()), "an empty graph contributes nothing");
|
||||
Map<String, Object> node = Ld.node("WebPage", "https://x.test/#p");
|
||||
Ld.put(node, "name", "Hello");
|
||||
String out = Ld.script(List.of(node));
|
||||
assertTrue(out.contains("<script type=\"application/ld+json\">"));
|
||||
assertTrue(out.contains("\"@context\":\"https://schema.org\""));
|
||||
assertTrue(out.contains("\"@graph\""));
|
||||
assertTrue(out.contains("\"@type\":\"WebPage\""));
|
||||
assertTrue(out.contains("\"name\":\"Hello\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scriptNeutralizesHtmlBreakoutInsideTheScriptElement() {
|
||||
Map<String, Object> node = Ld.node("WebPage", null);
|
||||
Ld.put(node, "name", "a </script><b> & c");
|
||||
String out = Ld.script(List.of(node));
|
||||
assertFalse(out.contains("</script><b>"), "raw < / > / & must not survive inside the script element");
|
||||
assertTrue(out.contains("\\u003c"));
|
||||
assertTrue(out.contains("\\u003e"));
|
||||
assertTrue(out.contains("\\u0026"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putOmitsBlanksAndPutListCollapsesSingletons() {
|
||||
Map<String, Object> node = Ld.node("Organization", null);
|
||||
Ld.put(node, "name", " ");
|
||||
Ld.put(node, "url", null);
|
||||
assertFalse(node.containsKey("name"));
|
||||
assertFalse(node.containsKey("url"));
|
||||
Ld.putList(node, "sameAs", List.of("https://x.test"));
|
||||
assertEquals("https://x.test", node.get("sameAs"), "a single sameAs is a scalar");
|
||||
Ld.putList(node, "sameAs", List.of("https://a", "https://b"));
|
||||
assertEquals(List.of("https://a", "https://b"), node.get("sameAs"), "multiple is an array");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* /llms.txt: opt-in (geo.enabled) Markdown index of the host's published listing, in the site's default locale;
|
||||
* disabled ⇒ 404. The listing (published only, safe paths, reserved paths dropped) is the host's; what this
|
||||
* endpoint adds is the selection (noindex out), the labels, the summary and the absolute URLs.
|
||||
*/
|
||||
class LlmsTxtEndpointTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private final SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
private final FakePluginSettings settings = TestSettings.declared();
|
||||
private final FakeContentCatalog catalog = new FakeContentCatalog().site("acme");
|
||||
private final LlmsTxtEndpoint endpoint = new LlmsTxtEndpoint(catalog, settings);
|
||||
|
||||
private static final ContentRef ABOUT = ContentRef.of("about", "/about", Map.of(), List.of(EN),
|
||||
Map.of("en", "About"), Map.of("en", "Who we are."), "__site__/acme/about", null);
|
||||
private static final ContentRef ENTRY = ContentRef.of("my-post", "/blog/my-post", Map.of(), List.of(EN),
|
||||
Map.of("en", "My post"), Map.of("en", "A fine read."), "__plugin__/blog/entry", null);
|
||||
/** Published in Spanish only, on an English-default site. */
|
||||
private static final ContentRef SPANISH_ONLY = ContentRef.of("solo", "/solo", Map.of("es", "/solo-es"),
|
||||
List.of(ES), Map.of("es", "Sólo en español"), Map.of(), "__site__/acme/solo", null);
|
||||
private static final ContentRef HIDDEN = new ContentRef("hidden", "/hidden", Map.of(), List.of(EN),
|
||||
Map.of("en", "Hidden"), Map.of(), null, "__site__/acme/hidden", true, null, true, null, null, Map.of());
|
||||
|
||||
@BeforeEach
|
||||
@org.junit.jupiter.api.AfterEach
|
||||
void freshValidators() {
|
||||
CrawlConditional.reset(); // also restores the system clock a test may have stepped
|
||||
}
|
||||
|
||||
private RouteRequest req(SiteView s, Map<String, String> headers, String origin) {
|
||||
return new RouteRequest(s, EN, "GET", "/llms.txt", Map.of(), headers, new byte[0], Map.of(), null, origin);
|
||||
}
|
||||
|
||||
private String body(RouteResponse r) {
|
||||
assertEquals(200, r.status());
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void geo(Map<String, Object> extra) {
|
||||
Map<String, Object> cfg = new java.util.HashMap<>(Map.of("geo.enabled", true));
|
||||
cfg.putAll(extra);
|
||||
settings.site("acme", cfg);
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesMarkdownIndexWhenGeoEnabled() {
|
||||
geo(Map.of("geo.summary", "We build things."));
|
||||
catalog.entry("acme", Entries.page(ABOUT, site)).entry("acme", Entries.of("blog", ENTRY, site));
|
||||
|
||||
RouteResponse r = endpoint.handle(req(site, Map.of(), "http://ignored.test"));
|
||||
assertEquals("text/plain; charset=utf-8", r.headers().get("Content-Type"));
|
||||
assertEquals("""
|
||||
# Acme
|
||||
|
||||
> We build things.
|
||||
|
||||
## Pages
|
||||
|
||||
- [About](https://acme.test/about): Who we are.
|
||||
- [My post](https://acme.test/blog/my-post): A fine read.
|
||||
""", body(r), "the exact 1.x document shape; plugin content is a first-class citizen");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledReturns404WhenGeoOff() {
|
||||
settings.site("acme", Map.of("geo.enabled", false));
|
||||
RouteResponse r = endpoint.handle(req(site, Map.of(), ""));
|
||||
assertEquals(404, r.status());
|
||||
assertEquals("no-store", r.headers().get("Cache-Control"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void geoIsOffByDefault() {
|
||||
assertEquals(404, endpoint.handle(req(site, Map.of(), "")).status(), "GEO is opt-in");
|
||||
}
|
||||
|
||||
/**
|
||||
* An intended change: an item that does not exist in the default locale is linked where it exists
|
||||
* (its primary locale's real URL), never at the unprefixed default path that 1.x produced and the site 404s.
|
||||
*/
|
||||
@Test
|
||||
void anItemMissingFromTheDefaultLocaleIsLinkedWhereItExists() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(SPANISH_ONLY, site));
|
||||
|
||||
String md = body(endpoint.handle(req(site, Map.of(), "")));
|
||||
assertTrue(md.contains("- [Sólo en español](https://acme.test/es/solo-es)"), md);
|
||||
assertFalse(md.contains("https://acme.test/solo)"), "never the default path, which 404s: " + md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noindexContentIsNotAdvertised() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site)).entry("acme", Entries.page(HIDDEN, site));
|
||||
String md = body(endpoint.handle(req(site, Map.of(), "")));
|
||||
assertTrue(md.contains("[About]"));
|
||||
assertFalse(md.contains("Hidden"), md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsAreOneLineWithoutLinkMetacharactersAndFallBackToTheId() {
|
||||
geo(Map.of("geo.summary", "Line one\nline two"));
|
||||
ContentRef bracketed = ContentRef.of("faq", "/faq", Map.of(), List.of(EN), Map.of("en", "FAQ [updated]\nnow"),
|
||||
Map.of("en", "Two\nlines"), "__site__/acme/faq", null);
|
||||
ContentRef untitled = ContentRef.of("no-title", "/no-title", Map.of(), List.of(EN), Map.of(), Map.of(),
|
||||
"__site__/acme/nt", null);
|
||||
catalog.entry("acme", Entries.page(bracketed, site)).entry("acme", Entries.page(untitled, site));
|
||||
|
||||
String md = body(endpoint.handle(req(site, Map.of(), "")));
|
||||
assertTrue(md.contains("> Line one line two\n"), md);
|
||||
assertTrue(md.contains("- [FAQ (updated) now](https://acme.test/faq): Two lines\n"), md);
|
||||
assertTrue(md.contains("- [no-title](https://acme.test/no-title)\n"), md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutABaseUrlTheTrustedOriginIsUsed() {
|
||||
geo(Map.of());
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
catalog.entry("acme", Entries.page(ABOUT, noBase));
|
||||
String md = body(endpoint.handle(req(noBase, Map.of("Host", "spoofed.test"), "http://acme.test:8080")));
|
||||
assertTrue(md.contains("(http://acme.test:8080/about)"), md);
|
||||
assertFalse(md.contains("spoofed"), md);
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalGetRevalidatesWith304() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
String lastModified = fresh.headers().get("Last-Modified");
|
||||
assertEquals("no-cache", fresh.headers().get("Cache-Control"));
|
||||
RouteResponse again = endpoint.handle(req(site, Map.of("if-modified-since", lastModified), ""));
|
||||
assertEquals(304, again.status());
|
||||
assertEquals(0, again.body().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownSiteListsNothingButStillAnswers() {
|
||||
geo(Map.of());
|
||||
SiteView ghost = new SiteView("ghost", "Ghost", EN, List.of(EN), "https://ghost.test");
|
||||
settings.site("ghost", Map.of("geo.enabled", true));
|
||||
assertEquals("# Ghost\n\n## Pages\n\n", body(endpoint.handle(req(ghost, Map.of(), ""))));
|
||||
}
|
||||
|
||||
// --- the validator folds what the document prints besides the items (2.1.0) -----------------------------
|
||||
|
||||
private RouteResponse revalidate(SiteView s, RouteResponse fresh) {
|
||||
return endpoint.handle(req(s, Map.of("If-Modified-Since", fresh.headers().get("Last-Modified")), ""));
|
||||
}
|
||||
|
||||
/** Stepping the validator's clock past HTTP-date granularity, so an advance is observable. */
|
||||
private static void tick(int seconds) {
|
||||
java.time.Instant at = java.time.Instant.now().plusSeconds(seconds);
|
||||
CrawlConditional.clock = () -> at;
|
||||
}
|
||||
|
||||
@Test
|
||||
void editingTheSummaryAdvancesLastModified() {
|
||||
geo(Map.of("geo.summary", "We build things."));
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
assertEquals(304, revalidate(site, fresh).status(), "unchanged: 304");
|
||||
|
||||
tick(5);
|
||||
geo(Map.of("geo.summary", "We build better things."));
|
||||
RouteResponse after = revalidate(site, fresh);
|
||||
assertEquals(200, after.status(), "a crawler holding the old summary refetches");
|
||||
assertTrue(body(after).contains("> We build better things."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingTheSiteAdvancesLastModified() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
|
||||
tick(5);
|
||||
SiteView renamed = new SiteView("acme", "Acme Industries", EN, List.of(EN, ES), "https://acme.test");
|
||||
RouteResponse after = revalidate(renamed, fresh);
|
||||
assertEquals(200, after.status(), "the H1 is the site name: a rename is a document change");
|
||||
assertTrue(body(after).startsWith("# Acme Industries\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewBaseUrlAdvancesLastModified() {
|
||||
geo(Map.of());
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
RouteResponse fresh = endpoint.handle(req(site, Map.of(), ""));
|
||||
|
||||
tick(5);
|
||||
SiteView moved = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://www.acme.test");
|
||||
RouteResponse after = revalidate(moved, fresh);
|
||||
assertEquals(200, after.status(), "every link starts with the base URL");
|
||||
assertTrue(body(after).contains("(https://www.acme.test/about)"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A host-less site reached under two names serves each its own links; the request origin is deliberately NOT
|
||||
* folded, so each crawler's copy stays valid for the address it fetched and the validator does not advance on
|
||||
* every alternate request.
|
||||
*/
|
||||
@Test
|
||||
void theRequestOriginOfAHostlessSiteDoesNotMoveTheValidator() {
|
||||
geo(Map.of());
|
||||
SiteView hostless = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
catalog.entry("acme", Entries.page(ABOUT, hostless));
|
||||
RouteResponse first = endpoint.handle(req(hostless, Map.of(), "http://one.test"));
|
||||
tick(5);
|
||||
RouteResponse second = endpoint.handle(req(hostless, Map.of(), "http://two.test"));
|
||||
assertTrue(body(second).contains("(http://two.test/about)"));
|
||||
assertEquals(first.headers().get("Last-Modified"), second.headers().get("Last-Modified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void editingTheSummaryDoesNotMoveTheSitemapsValidator() {
|
||||
geo(Map.of("geo.summary", "One."));
|
||||
catalog.entry("acme", Entries.page(ABOUT, site));
|
||||
SitemapEndpoint sitemap = new SitemapEndpoint(catalog, settings);
|
||||
RouteRequest sitemapReq = new RouteRequest(site, EN, "GET", "/sitemap.xml", Map.of(), Map.of(), new byte[0],
|
||||
Map.of(), null, "");
|
||||
String sitemapValidator = sitemap.handle(sitemapReq).headers().get("Last-Modified");
|
||||
endpoint.handle(req(site, Map.of(), ""));
|
||||
tick(5);
|
||||
geo(Map.of("geo.summary", "Two."));
|
||||
endpoint.handle(req(site, Map.of(), ""));
|
||||
assertEquals(sitemapValidator, sitemap.handle(sitemapReq).headers().get("Last-Modified"),
|
||||
"the sitemap does not print the summary");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.PageView;
|
||||
import mx.quest.runway.spi.model.Severity;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The page editor's structured-data line says what the page is and where that comes from. */
|
||||
class PageTypeCheckTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final PageTypeCheck check = new PageTypeCheck(config, DiscoverabilityConfig.schemaTypes(), null);
|
||||
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
|
||||
private List<Finding> inspect(String path, Map<String, Object> cfg) {
|
||||
return inspect(path, cfg, false, List.of(Locale.ENGLISH));
|
||||
}
|
||||
|
||||
private List<Finding> inspect(String path, Map<String, Object> cfg, boolean noindex, List<Locale> languages) {
|
||||
config.site("acme", cfg);
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, languages, "https://acme.test");
|
||||
PageMeta page = new PageMeta(path.substring(1), "T", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
noindex);
|
||||
return check.inspect(new PageView(site, page, Locale.ENGLISH, "https://acme.test" + path, "<p>x</p>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultIsNamedAsTheSitesDefaultPageType() {
|
||||
List<Finding> f = inspect("/about", Map.of());
|
||||
assertEquals(1, f.size());
|
||||
assertEquals(Severity.INFO, f.get(0).severity());
|
||||
assertEquals("Structured data: this page is a WebPage, the site's Default page type.", f.get(0).message());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPerPageTypeNamesItsPatternAndWhatElseItAdds() {
|
||||
List<Finding> f = inspect("/pricing", Map.of("content.schema",
|
||||
"/pri*:\n - type: FAQPage\n faq: []\n - type: Service\n name: S\n"));
|
||||
assertEquals("Structured data: this page is a FAQPage, set by Per-page types (pattern /pri*). "
|
||||
+ "Per-page types also add: Service.", f.get(0).message());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownTypeAndASecondPageTypeAreWarnings() {
|
||||
List<Finding> f = inspect("/x", Map.of("content.schema",
|
||||
"/x:\n - type: AboutPage\n - type: ContactPage\n - type: Typo\n"));
|
||||
assertEquals(3, f.size(), f.toString());
|
||||
assertTrue(f.stream().anyMatch(x -> x.severity() == Severity.WARNING && x.message().contains("Typo")), f.toString());
|
||||
assertTrue(f.stream().anyMatch(x -> x.severity() == Severity.WARNING && x.message().contains("ContactPage is ignored")),
|
||||
f.toString());
|
||||
}
|
||||
|
||||
/** The head emits nothing on a noindex page, before anything else; the line says so, whatever else is set. */
|
||||
@Test
|
||||
void aNoindexPageIsSaidToCarryNoStructuredData() {
|
||||
List<Finding> f = inspect("/faq", Map.of("content.schema", "/faq:\n - type: FAQPage\n - type: Typo\n"),
|
||||
true, List.of(Locale.ENGLISH));
|
||||
assertEquals(1, f.size(), f.toString());
|
||||
assertEquals(Severity.INFO, f.get(0).severity());
|
||||
assertEquals("Structured data: this page is excluded from search engines (noindex), so it carries no "
|
||||
+ "structured data.", f.get(0).message());
|
||||
assertEquals(1, inspect("/x", Map.of("jsonld.enabled", false), true, List.of(Locale.ENGLISH)).size());
|
||||
assertTrue(inspect("/x", Map.of("jsonld.enabled", false), true, List.of(Locale.ENGLISH)).get(0).message()
|
||||
.contains("noindex"), "noindex is checked first, as the head does");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anFaqPageWithNoCompleteQuestionIsAWarning() {
|
||||
List<Finding> f = inspect("/faq", Map.of("content.schema",
|
||||
"/faq:\n type: FAQPage\n faq:\n - { question: Q, answer: A }\n"));
|
||||
assertEquals(2, f.size(), f.toString());
|
||||
assertEquals(Severity.WARNING, f.get(1).severity());
|
||||
assertEquals(PageTypeCheck.CODE_GAP, f.get(1).code());
|
||||
assertEquals("FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.",
|
||||
f.get(1).message());
|
||||
assertEquals(1, inspect("/faq", Map.of("content.schema",
|
||||
"/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n")).size(), "a complete pair is enough");
|
||||
List<Finding> list = inspect("/c", Map.of("content.schema",
|
||||
"/c:\n - type: AboutPage\n - type: ItemList\n items:\n - { name: A }\n"));
|
||||
assertTrue(list.stream().anyMatch(x -> x.severity() == Severity.WARNING
|
||||
&& x.message().equals("ItemList has no item with a url:, so no list is published.")), list.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTranslatedPageIsToldTheDefaultLanguagesEntryDoesNotReachIt() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n");
|
||||
List<Finding> f = inspect("/es/faq", cfg, false, List.of(Locale.ENGLISH, ES));
|
||||
assertEquals(2, f.size(), f.toString());
|
||||
assertEquals("Structured data: this page is a WebPage, the site's Default page type.", f.get(0).message());
|
||||
assertEquals(Severity.INFO, f.get(1).severity());
|
||||
assertEquals("Per-page types: /faq describes the default language's page, not this one; a page in another "
|
||||
+ "language is matched only by its own path. To describe this page, add /es/faq.", f.get(1).message());
|
||||
assertEquals(1, inspect("/faq", cfg, false, List.of(Locale.ENGLISH, ES)).size(), "the default language's page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchedOffSaysSo() {
|
||||
List<Finding> f = inspect("/x", Map.of("jsonld.enabled", false));
|
||||
assertTrue(f.get(0).message().startsWith("Structured data is switched off"), f.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* A page type declared in Per-page types replaces the site's Default page type on the page's own node;
|
||||
* every other type adds an entity. The head and the editor ask {@link PageTypes} the same question.
|
||||
*/
|
||||
class PageTypesTest {
|
||||
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH, ES),
|
||||
"https://acme.test");
|
||||
private static final Map<String, SchemaType> TYPES = DiscoverabilityConfig.schemaTypes();
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final StructuredDataHead head = new StructuredDataHead(config, TYPES);
|
||||
|
||||
private String render(String path, String title, Map<String, Object> cfg) {
|
||||
config.site("acme", cfg);
|
||||
PageMeta page = new PageMeta(path.substring(1), title, "d", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
false);
|
||||
String canonical = "https://acme.test" + path;
|
||||
return head.render(new HeadContext(SITE, page, Locale.ENGLISH, canonical, canonical, List.of(), false, false));
|
||||
}
|
||||
|
||||
private static int count(String haystack, String needle) {
|
||||
int n = 0;
|
||||
for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) {
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutAPageTypeThePageHasTheSiteDefault() {
|
||||
PageTypes.Description d = PageTypes.describe(Map.of(), "/about", TYPES);
|
||||
assertEquals("WebPage", d.type());
|
||||
assertEquals(PageTypes.Source.DEFAULT, d.source());
|
||||
assertEquals("Article", PageTypes.describe(Map.of("jsonld.type", "Article"), "/x", TYPES).type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArticleEntryIsThePagesOwnTypeNotASecondArticle() {
|
||||
String out = render("/news/one", "One", Map.of("jsonld.type", "Article",
|
||||
"content.schema", "/news/*:\n type: BlogPosting\n author: Ed\n"));
|
||||
assertEquals(1, count(out, "\"@type\":\"BlogPosting\""), out);
|
||||
assertEquals(0, count(out, "\"@type\":\"Article\""), "no second article beside the page: " + out);
|
||||
assertTrue(out.contains("\"@id\":\"https://acme.test/news/one#webpage\""), out);
|
||||
assertTrue(out.contains("\"headline\":\"One\"") && out.contains("\"name\":\"Ed\""), out);
|
||||
assertFalse(out.contains("mainEntityOfPage"), "nothing points back at itself: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anFaqEntryMakesThePageAnFaqPageWithItsQuestions() {
|
||||
String out = render("/faq", "FAQ", Map.of("content.schema",
|
||||
"/faq:\n type: FAQPage\n faq:\n - { q: \"Why?\", a: \"Because.\" }\n"));
|
||||
assertEquals(1, count(out, "\"@type\":\"FAQPage\""), out);
|
||||
assertEquals(0, count(out, "\"@type\":\"WebPage\""), out);
|
||||
assertTrue(out.contains("\"mainEntity\":[{\"@type\":\"Question\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCollectionPageIsThePageAndItsListIsItsMainEntity() {
|
||||
String out = render("/coffees", "Coffees", Map.of("content.schema",
|
||||
"/coffees:\n type: CollectionPage\n items:\n - { name: A, url: /a }\n"));
|
||||
assertTrue(out.contains("\"@type\":\"CollectionPage\",\"@id\":\"https://acme.test/coffees#webpage\""), out);
|
||||
assertTrue(out.contains("\"mainEntity\":{\"@id\":\"https://acme.test/coffees#itemlist\"}"), out);
|
||||
assertEquals(1, count(out, "\"@type\":\"ItemList\""), out);
|
||||
// ItemList alone still only adds the list.
|
||||
String list = render("/coffees", "Coffees", Map.of("content.schema",
|
||||
"/coffees:\n type: ItemList\n items:\n - { name: A, url: /a }\n"));
|
||||
assertTrue(list.contains("\"@type\":\"WebPage\""), list);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSimplePageTypeOnlyNamesThePage() {
|
||||
String out = render("/contact", "Contact", Map.of("jsonld.type", "Article",
|
||||
"content.schema", "/contact:\n type: ContactPage\n"));
|
||||
assertTrue(out.contains("\"@type\":\"ContactPage\""), out);
|
||||
assertTrue(out.contains("\"name\":\"Contact\""), "a non-article page keeps its name: " + out);
|
||||
assertEquals(0, count(out, "\"@type\":\"Article\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherTypesStillAddEntitiesBesideThePageType() {
|
||||
PageTypes.Description d = PageTypes.describe(Map.of("content.schema",
|
||||
"/pricing:\n - type: FAQPage\n faq: []\n - type: Service\n name: S\n - type: Nope\n"
|
||||
+ " - type: AboutPage\n"), "/pricing", TYPES);
|
||||
assertEquals("FAQPage", d.type());
|
||||
assertEquals(PageTypes.Source.SCHEMA, d.source());
|
||||
assertEquals("/pricing", d.pattern());
|
||||
assertEquals(List.of("Service"), d.addedTypes());
|
||||
assertEquals(List.of("Nope"), d.unknown());
|
||||
assertEquals(List.of("AboutPage"), d.extraPageTypes(), "a page has one type; the second is reported");
|
||||
}
|
||||
|
||||
/** An entry's text is in one language, so a translated page is matched only by its own path. */
|
||||
@Test
|
||||
void aPageBehindALanguagePrefixIsNotMatchedByTheDefaultLanguagesKey() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"Do you ship abroad?\", a: \"Yes.\" }\n/blog/*:\n type: BlogPosting\n"
|
||||
+ "/coffees/*:\n type: Product\n name: Ethiopia Guji\n breadcrumb: { name: Coffees, url: /coffees }\n");
|
||||
PageTypes.Description d = PageTypes.describe(cfg, "/es/faq", TYPES);
|
||||
assertEquals("WebPage", d.type());
|
||||
assertEquals(PageTypes.Source.DEFAULT, d.source());
|
||||
assertNull(d.pattern(), "/faq does not reach /es/faq");
|
||||
assertEquals("WebPage", PageTypes.describe(cfg, "/es/blog/post", TYPES).type());
|
||||
assertNull(PageTypes.entry(cfg, "/es/coffees/guji"));
|
||||
|
||||
String faq = render("/es/faq", "Preguntas frecuentes", cfg);
|
||||
assertFalse(faq.contains("FAQPage") || faq.contains("Do you ship abroad?"), "no English questions: " + faq);
|
||||
String product = render("/es/coffees/guji", "Guji", cfg);
|
||||
assertFalse(product.contains("Ethiopia Guji") || product.contains("\"Product\""), product);
|
||||
assertFalse(product.contains("\"name\":\"Coffees\""), "no English breadcrumb parent: " + product);
|
||||
// The default language's pages are unchanged.
|
||||
assertTrue(render("/faq", "FAQ", cfg).contains("Do you ship abroad?"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWrittenForTheTranslatedPathApplies() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"Do you ship abroad?\", a: \"Yes.\" }\n/es/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"¿Envían al extranjero?\", a: \"Sí.\" }\n/es/blog/*:\n type: BlogPosting\n");
|
||||
PageTypes.Description d = PageTypes.describe(cfg, "/es/faq", TYPES);
|
||||
assertEquals("FAQPage", d.type());
|
||||
assertEquals("/es/faq", d.pattern());
|
||||
String out = render("/es/faq", "Preguntas frecuentes", cfg);
|
||||
assertTrue(out.contains("¿Envían al extranjero?"), out);
|
||||
assertFalse(out.contains("Do you ship abroad?"), out);
|
||||
assertEquals("BlogPosting", PageTypes.describe(cfg, "/es/blog/hola", TYPES).type());
|
||||
// A catch-all reaches every language's page, as it always did.
|
||||
assertEquals("AboutPage", PageTypes.describe(Map.of("content.schema", "/*:\n type: AboutPage\n"),
|
||||
"/es/x", TYPES).type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEditorIsToldWhichDefaultLanguageEntryDoesNotReachATranslatedPage() {
|
||||
Map<String, Object> cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n/blog/*:\n type: BlogPosting\n"
|
||||
+ "/:\n type: WebPage\n/team:\n type: AboutPage\n/es/team:\n type: AboutPage\n");
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/faq", "/es/faq"), PageTypes.otherLanguageEntry(cfg, "/es/faq", SITE));
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/blog/*", "/es/blog/*"),
|
||||
PageTypes.otherLanguageEntry(cfg, "/es/blog/x", SITE));
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/", "/es"), PageTypes.otherLanguageEntry(cfg, "/es", SITE));
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/es/team", SITE), "it has its own key");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/faq", SITE), "a default-language page has no prefix");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/en/faq", SITE), "the default language is never a prefix");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/fr/faq", SITE), "fr is not a language of this site");
|
||||
assertNull(PageTypes.otherLanguageEntry(cfg, "/es/acerca", SITE), "nothing matches /acerca either");
|
||||
Map<String, Object> catchAll = Map.of("content.schema", "/*:\n type: WebPage\n/es/*:\n type: WebPage\n"
|
||||
+ "/about:\n type: AboutPage\n");
|
||||
assertNull(PageTypes.otherLanguageEntry(catchAll, "/es/x", SITE), "/es/* is at least as specific as /*");
|
||||
assertEquals(new PageTypes.OtherLanguageEntry("/about", "/es/about"),
|
||||
PageTypes.otherLanguageEntry(catchAll, "/es/about", SITE), "/es/* is less specific than /about");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockWithoutATypeIsNotReportedAsUnknown() {
|
||||
PageTypes.Description d = PageTypes.describe(Map.of("content.schema",
|
||||
"/p:\n - breadcrumb: { name: Shop, url: /shop }\n - type: Product\n name: P\n"), "/p", TYPES);
|
||||
assertTrue(d.unknown().isEmpty(), d.unknown().toString());
|
||||
assertEquals(List.of("Product"), d.addedTypes());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The plugin-owned {@code /robots.txt}: a general allow-all group + the {@code Sitemap:} line, with a
|
||||
* configurable AI/LLM-crawler policy (per-site {@code robots.ai-policy} over the app-level {@code robots.ai-default}),
|
||||
* tenant extra Disallow paths, and a full-body custom override.
|
||||
*/
|
||||
class RobotsTxtEndpointTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
|
||||
private static PluginSettings config(Map<String, Object> cfg) {
|
||||
return TestSettings.declared().site("acme", cfg);
|
||||
}
|
||||
|
||||
private static DiscoverabilityProperties props(String aiDefault) {
|
||||
DiscoverabilityProperties p = new DiscoverabilityProperties();
|
||||
p.getRobots().setAiDefault(aiDefault);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers) {
|
||||
return req(site, headers, "");
|
||||
}
|
||||
|
||||
/** A request as the kernel builds it: the trusted origin, no forwarded headers. */
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers, String origin) {
|
||||
return new RouteRequest(site, EN, "GET", "/robots.txt", Map.of(), headers, new byte[0], Map.of(), null,
|
||||
origin);
|
||||
}
|
||||
|
||||
private static String bodyOf(Map<String, Object> cfg, String aiDefault, SiteView site, Map<String, String> headers) {
|
||||
return bodyOf(cfg, aiDefault, req(site, headers));
|
||||
}
|
||||
|
||||
private static String bodyOf(Map<String, Object> cfg, String aiDefault, RouteRequest req) {
|
||||
RouteResponse r = new RobotsTxtEndpoint(config(cfg), props(aiDefault)).handle(req);
|
||||
assertEquals(200, r.status());
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultAllowsEveryoneAndPointsAtTheSitemap() {
|
||||
String out = bodyOf(Map.of(), "allow", SITE, Map.of());
|
||||
assertTrue(out.contains("User-agent: *"), out);
|
||||
assertTrue(out.contains("Allow: /"), out);
|
||||
assertTrue(out.contains("Sitemap: https://acme.test/sitemap.xml"), out);
|
||||
// The AI/LLM posture is stated EXPLICITLY: a named group is emitted even on allow, with Allow — not
|
||||
// Disallow — so nothing is actually blocked.
|
||||
assertTrue(out.contains("User-agent: GPTBot"), "explicit AI-crawler group even on allow: " + out);
|
||||
assertFalse(out.contains("Disallow: /"), "allow posture disallows nothing: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void perSiteDisallowEmitsAiCrawlerGroups() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of());
|
||||
assertTrue(out.contains("User-agent: GPTBot"), out);
|
||||
assertTrue(out.contains("User-agent: ClaudeBot"), out);
|
||||
assertTrue(out.contains("User-agent: Google-Extended"), out);
|
||||
assertTrue(out.contains("Disallow: /"), out);
|
||||
assertTrue(out.contains("User-agent: *"), "classic crawlers are still allowed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inheritsAppLevelDisallowDefault() {
|
||||
String out = bodyOf(Map.of(), "disallow", SITE, Map.of()); // policy defaults to inherit
|
||||
assertTrue(out.contains("User-agent: GPTBot"), "inherit → app default disallow: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void perSiteAllowOverridesAppLevelDisallowDefault() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "allow"), "disallow", SITE, Map.of());
|
||||
// Per-site allow wins over the app default: the named group is still present (explicit posture) but as
|
||||
// Allow, never Disallow: /.
|
||||
assertTrue(out.contains("User-agent: GPTBot"), out);
|
||||
assertFalse(out.contains("Disallow: /"), "per-site allow wins over the app default: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowedAiGroupMirrorsTenantExtraDisallows() {
|
||||
// On the allow posture the named AI group MIRRORS the general group's exclusions, so a most-specific
|
||||
// robots.txt match cannot let AI crawlers bypass the tenant's own Disallow paths. /private thus appears
|
||||
// twice: once under the AI group, once under the * group.
|
||||
String out = bodyOf(Map.of("robots.extra-disallow", List.of("/private")), "allow", SITE, Map.of());
|
||||
long count = out.lines().filter(l -> l.equals("Disallow: /private")).count();
|
||||
assertEquals(2, count, "AI group mirrors the tenant exclusion: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void omitsSitemapLineWhenSitemapDisabled() {
|
||||
String out = bodyOf(Map.of("sitemap.enabled", false), "allow", SITE, Map.of());
|
||||
assertFalse(out.contains("Sitemap:"), out);
|
||||
assertTrue(out.contains("Allow: /"), "still serves the allow group");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsTenantExtraDisallowPathsNormalized() {
|
||||
String out = bodyOf(Map.of("robots.extra-disallow", List.of("/private", "search")), "allow", SITE, Map.of());
|
||||
assertTrue(out.contains("Disallow: /private"), out);
|
||||
assertTrue(out.contains("Disallow: /search"), "a bare path is normalized to /search: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void customBodyReplacesEverythingVerbatim() {
|
||||
String out = bodyOf(Map.of("robots.custom", "User-agent: *\nDisallow: /"), "allow", SITE, Map.of());
|
||||
assertEquals("User-agent: *\nDisallow: /\n", out);
|
||||
assertFalse(out.contains("Sitemap:"), "the custom body is verbatim — no generated additions");
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesTheSitemapOriginFromTheTrustedRequestOriginWhenBaseUrlUnset() {
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN), null);
|
||||
String out = bodyOf(Map.of(), "allow", req(noBase, Map.of("Host", "acme.test"), "http://acme.test:8080"));
|
||||
assertTrue(out.contains("Sitemap: http://acme.test:8080/sitemap.xml"), "the origin as the kernel gated it, "
|
||||
+ "scheme and port included — never a guessed https from the Host header: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfiguredBaseUrlWinsOverTheRequestOrigin() {
|
||||
String out = bodyOf(Map.of(), "allow", req(SITE, Map.of(), "http://internal:8080"));
|
||||
assertTrue(out.contains("Sitemap: https://acme.test/sitemap.xml"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noBaseUrlAndNoOriginMeansNoSitemapLineRatherThanARelativeOne() {
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN), null);
|
||||
String out = bodyOf(Map.of(), "allow", req(noBase, Map.of("Host", "acme.test"), ""));
|
||||
assertFalse(out.contains("Sitemap:"), "a Host header alone is no longer trusted: " + out);
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact regression the SEO/GEO compliance audit found in 1.3.0: {@code ClaudeBot} was listed but
|
||||
* {@code Claude-User} and {@code Claude-SearchBot} were not, so a site set to {@code disallow} was still
|
||||
* reachable by two of the three Anthropic agents — an opt-out the owner believed was complete and was not.
|
||||
*
|
||||
* <p>Asserted per-vendor across all three CLASSES the article distinguishes (training / live retrieval /
|
||||
* user-triggered fetch), because the failure mode is one missing name, not a missing feature — a test that
|
||||
* only checked "some AI agent is present" would have passed against the bug.
|
||||
*/
|
||||
@Test
|
||||
void everyAgentClassIsCoveredForEachMajorVendor() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of());
|
||||
for (String agent : List.of(
|
||||
"GPTBot", "OAI-SearchBot", "ChatGPT-User", // OpenAI: train / retrieve / user
|
||||
"ClaudeBot", "Claude-SearchBot", "Claude-User", // Anthropic: train / retrieve / user
|
||||
"PerplexityBot", "Perplexity-User", // Perplexity: retrieve / user
|
||||
"Google-Extended", "Applebot-Extended")) { // training opt-outs, NOT the search bots
|
||||
assertTrue(out.contains("User-agent: " + agent + "\n"), "missing agent: " + agent);
|
||||
}
|
||||
// The training opt-out must never take the SEARCH crawler with it — that would deindex the site.
|
||||
assertFalse(out.contains("User-agent: Googlebot\n"), "Googlebot must never be in the AI opt-out group");
|
||||
assertFalse(out.contains("User-agent: Applebot\n"), "Applebot must never be in the AI opt-out group");
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator escape hatch: the built-in list is a compile-time constant that goes stale silently, so
|
||||
* {@code robots.ai-agents-extra} must be able to cover a newly announced agent without a plugin release.
|
||||
*
|
||||
* <p>Also pins the injection guard. An operator-supplied name lands in a {@code User-agent:} line, so a value
|
||||
* carrying CR/LF or a colon could forge extra robots directives into every tenant's file — the same class of
|
||||
* hole already closed for tenant exclusion paths.
|
||||
*/
|
||||
@Test
|
||||
void operatorAddedAgentsAreAppendedDedupedAndSanitised() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of(
|
||||
"BrandNewBot", // the point of the feature
|
||||
"gptbot", // already built in, different case → must not duplicate
|
||||
"Evil\nUser-agent: *\nDisallow: /", // injection attempt via CR/LF
|
||||
" Spaced Bot ")); // whitespace stripped
|
||||
RouteResponse r = new RobotsTxtEndpoint(config(Map.of("robots.ai-policy", "disallow")), p)
|
||||
.handle(req(SITE, Map.of()));
|
||||
String out = new String(r.body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(out.contains("User-agent: BrandNewBot\n"), "operator addition must be emitted");
|
||||
assertEquals(1, out.split("(?i)User-agent: GPTBot\n", -1).length - 1, "must not duplicate a built-in");
|
||||
assertTrue(out.contains("User-agent: SpacedBot\n"), "whitespace stripped: " + out);
|
||||
// The injected directive must not survive as its own line.
|
||||
assertFalse(out.contains("\nDisallow: /\nUser-agent: *"), "CR/LF injection must be neutralised");
|
||||
assertTrue(out.contains("User-agent: EvilUser-agent:*Disallow:/\n")
|
||||
|| out.contains("User-agent: EvilUser-agent"),
|
||||
"the payload is flattened into one inert token: " + out);
|
||||
}
|
||||
|
||||
// ---- the three AI classes are separately governable -----------------------------------------------
|
||||
|
||||
/** The group a named agent falls in: the lines from its {@code User-agent:} to the next blank line. */
|
||||
private static String groupContaining(String robots, String agent) {
|
||||
for (String group : robots.split("\n\n")) {
|
||||
if (group.contains("User-agent: " + agent + "\n") || group.endsWith("User-agent: " + agent)) {
|
||||
return group;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The case the split exists for: decline training, stay citable.
|
||||
*
|
||||
* <p>Before this a site had one AI switch, so the only way to refuse training was to refuse the answer
|
||||
* engines too — which removes the site from generated answers, the opposite of what a site optimising for
|
||||
* them wants. The three classes carry opposite consequences and now carry opposite settings.
|
||||
*/
|
||||
@Test
|
||||
void aSiteCanDeclineTrainingWhileStayingCitable() {
|
||||
String out = bodyOf(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "allow"),
|
||||
"allow", SITE, Map.of());
|
||||
|
||||
assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), out);
|
||||
assertTrue(groupContaining(out, "ClaudeBot").contains("Disallow: /"), out);
|
||||
assertTrue(groupContaining(out, "OAI-SearchBot").contains("Allow: /"), out);
|
||||
assertTrue(groupContaining(out, "Claude-SearchBot").contains("Allow: /"), out);
|
||||
}
|
||||
|
||||
/** A user-triggered fetch is its own decision: someone asked for this page. */
|
||||
@Test
|
||||
void theUserTriggeredClassIsGovernedSeparately() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "disallow", "robots.ai-user", "allow"),
|
||||
"allow", SITE, Map.of());
|
||||
|
||||
assertTrue(groupContaining(out, "ChatGPT-User").contains("Allow: /"), out);
|
||||
assertTrue(groupContaining(out, "Claude-User").contains("Allow: /"), out);
|
||||
assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), "training still declined: " + out);
|
||||
}
|
||||
|
||||
/**
|
||||
* A site that sets no per-class override gets exactly the file it got before classes existed.
|
||||
*
|
||||
* <p>Byte-for-byte, agent order included. Splitting a site that expressed no such preference into three
|
||||
* identical groups would churn every crawler's copy of a file to say precisely the same thing.
|
||||
*/
|
||||
@Test
|
||||
void aSiteWithNoPerClassOverrideGetsTheIdenticalSingleGroup() {
|
||||
String withoutClasses = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of());
|
||||
String allInherit = bodyOf(Map.of("robots.ai-policy", "disallow", "robots.ai-training", "inherit",
|
||||
"robots.ai-retrieval", "inherit", "robots.ai-user", "inherit"), "allow", SITE, Map.of());
|
||||
|
||||
assertEquals(withoutClasses, allInherit);
|
||||
assertEquals(1, withoutClasses.split("Disallow: /\n", -1).length - 1,
|
||||
"one AI group, not three: " + withoutClasses);
|
||||
}
|
||||
|
||||
/** Three overrides that happen to agree also collapse to one group — the test is the OUTPUT, not the keys. */
|
||||
@Test
|
||||
void perClassOverridesThatAgreeStillCollapseToOneGroup() {
|
||||
String out = bodyOf(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "disallow",
|
||||
"robots.ai-user", "disallow"), "allow", SITE, Map.of());
|
||||
|
||||
assertEquals(bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of()), out);
|
||||
}
|
||||
|
||||
/** A per-class override beats the site policy; an unset class still inherits it. */
|
||||
@Test
|
||||
void aClassOverrideBeatsTheSitePolicyAndAnUnsetClassInheritsIt() {
|
||||
String out = bodyOf(Map.of("robots.ai-policy", "allow", "robots.ai-training", "disallow"),
|
||||
"disallow", SITE, Map.of());
|
||||
|
||||
assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), "the override wins: " + out);
|
||||
assertTrue(groupContaining(out, "OAI-SearchBot").contains("Allow: /"),
|
||||
"an unset class follows the SITE policy, not the app default: " + out);
|
||||
}
|
||||
|
||||
/**
|
||||
* An operator-added agent with no declared class follows the site's overall policy.
|
||||
*
|
||||
* <p>Exactly what it did before classes existed. Guessing a class for a name the plugin does not recognise
|
||||
* would apply a policy the operator never chose — and would do it silently.
|
||||
*/
|
||||
@Test
|
||||
void anUnclassifiedOperatorAgentFollowsTheOverallPolicy() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of("BrandNewBot"));
|
||||
String out = new String(new RobotsTxtEndpoint(
|
||||
config(Map.of("robots.ai-policy", "disallow", "robots.ai-user", "allow")), p)
|
||||
.handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(groupContaining(out, "BrandNewBot").contains("Disallow: /"), out);
|
||||
assertTrue(groupContaining(out, "Claude-User").contains("Allow: /"), out);
|
||||
}
|
||||
|
||||
/** …and an operator can classify a newly-announced agent the day it is announced. */
|
||||
@Test
|
||||
void anOperatorCanDeclareTheClassOfANewAgent() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of("retrieval=BrandNewSearchBot"));
|
||||
String out = new String(new RobotsTxtEndpoint(
|
||||
config(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "allow")), p)
|
||||
.handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(out.contains("User-agent: BrandNewSearchBot"), out);
|
||||
assertTrue(groupContaining(out, "BrandNewSearchBot").contains("Allow: /"),
|
||||
"declared retrieval, so it follows the retrieval policy: " + out);
|
||||
assertFalse(out.contains("retrieval=BrandNewSearchBot"), "the prefix must not leak into the file");
|
||||
}
|
||||
|
||||
/**
|
||||
* A misspelt class still lists the agent, and the prefix is not an injection vector.
|
||||
*
|
||||
* <p>The alternative — folding the bad prefix into the name — yields a user-agent token that matches
|
||||
* nothing, so the operator believes they covered an agent they did not. That is the silent failure the
|
||||
* whole extra-agents list exists to prevent, so a typo is reported and the agent is honoured under the
|
||||
* site's overall policy.
|
||||
*/
|
||||
@Test
|
||||
void aMisspeltClassStillListsTheAgentAndCannotInject() {
|
||||
DiscoverabilityProperties p = props("allow");
|
||||
p.getRobots().setAiAgentsExtra(List.of("nonsense=EvilBot", "x\nDisallow: /secret\nUser-agent: Y"));
|
||||
String out = new String(new RobotsTxtEndpoint(config(Map.of()), p)
|
||||
.handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(out.contains("User-agent: EvilBot"), "the agent the operator named is listed: " + out);
|
||||
assertFalse(out.contains("nonsense"), "the bad prefix must not become part of the name: " + out);
|
||||
assertFalse(out.contains("Disallow: /secret"), "CR/LF injection stays closed: " + out);
|
||||
}
|
||||
|
||||
/** Every built-in agent has a class, or the split silently sends it to the catch-all group. */
|
||||
@Test
|
||||
void everyBuiltInAgentIsClassified() {
|
||||
for (String agent : RobotsTxtEndpoint.AI_CRAWLERS) {
|
||||
assertTrue(RobotsTxtEndpoint.AI_CLASSES.containsKey(agent),
|
||||
agent + " has no class — it would quietly fall under the overall policy instead");
|
||||
}
|
||||
assertEquals(RobotsTxtEndpoint.AI_CRAWLERS.size(), RobotsTxtEndpoint.AI_CLASSES.size(),
|
||||
"a class map entry naming an agent that is not in the list does nothing and will rot");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Mistakes in Per-page types never break a page, so the settings screen lists them instead. */
|
||||
class SchemaProblemsTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final DiscoverAdminModel model = new DiscoverAdminModel(config, null);
|
||||
|
||||
private List<String> problems(String schema) {
|
||||
config.site("acme", Map.of("content.schema", schema));
|
||||
return model.schemaProblems("acme");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCleanOrBlankSchemaHasNone() {
|
||||
assertEquals(List.of(), problems(""));
|
||||
assertEquals(List.of(), problems("/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n"
|
||||
+ "/shop/*:\n - type: Product\n name: P\n/p:\n type: Product\n"));
|
||||
}
|
||||
|
||||
/** A block that applies but publishes nothing of its own is listed; a product's name defaults to the title. */
|
||||
@Test
|
||||
void aBlockThatPublishesNothingOfItsOwnIsListed() {
|
||||
List<String> p = problems("/faq:\n type: FAQPage\n faq: []\n/help:\n type: FAQPage\n faq:\n"
|
||||
+ " - { question: Q, answer: A }\n/c:\n type: CollectionPage\n items:\n - { name: A }\n"
|
||||
+ "/l:\n - type: AboutPage\n - type: ItemList\n/two:\n - type: AboutPage\n - type: FAQPage\n");
|
||||
assertEquals(List.of(
|
||||
"/faq: FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.",
|
||||
"/help: FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.",
|
||||
"/c: CollectionPage has no item with a url:, so no list is published.",
|
||||
"/l: ItemList has no item with a url:, so no list is published.",
|
||||
"/two: more than one page type; only the first applies."), p);
|
||||
}
|
||||
|
||||
/** Google requires a mainEntity on both, which a type with no keys cannot give; they are not offered. */
|
||||
@Test
|
||||
void qaPageAndProfilePageAreNotTypes() {
|
||||
assertEquals(List.of("/qa: QAPage is not a type this plugin knows; ignored.",
|
||||
"/me: ProfilePage is not a type this plugin knows; ignored."),
|
||||
problems("/qa:\n type: QAPage\n/me:\n type: ProfilePage\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableYamlIsOneProblemNamingTheError() {
|
||||
List<String> p = problems("/faq: [unclosed\n");
|
||||
assertEquals(1, p.size(), p.toString());
|
||||
assertTrue(p.get(0).startsWith("Per-page types cannot be read"), p.toString());
|
||||
assertEquals(1, problems("- just\n- a list\n").size(), "a list root is not a pattern map");
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachMistakeIsNamedWithItsPattern() {
|
||||
List<String> p = problems("about:\n type: AboutPage\n/a*b:\n type: WebPage\n/x:\n type: Prodcut\n"
|
||||
+ "/y:\n - type: AboutPage\n - type: ContactPage\n/z: just text\n");
|
||||
assertTrue(p.contains("about: a pattern starts with / and matches page paths."), p.toString());
|
||||
assertTrue(p.contains("/a*b: * works only at the end of a pattern; here it is matched as a character."),
|
||||
p.toString());
|
||||
assertTrue(p.contains("/x: Prodcut is not a type this plugin knows; ignored."), p.toString());
|
||||
assertTrue(p.contains("/y: more than one page type; only the first applies."), p.toString());
|
||||
assertTrue(p.contains("/z: the value must be a type block (type: ...) or a list of them; ignored."),
|
||||
p.toString());
|
||||
assertEquals(5, p.size(), p.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Keeps the settings form's layout honest. The kernel deliberately <b>tolerates</b> a broken presentation key —
|
||||
* an unknown group, a {@code showWhen} on a missing switch, a dangling {@code inheritsFrom}, an unresolved
|
||||
* message key — by quietly rendering the plain field, so a typo here would never fail anything at runtime: the
|
||||
* tenant would simply lose the section, the hiding or the help line. This test is where such a typo fails.
|
||||
*
|
||||
* <p>Reads {@code plugin.yml} as plain YAML (the plugin links only the SPI, so the kernel's descriptor parser is not
|
||||
* on the default test classpath); the {@code host-it} profile additionally parses it with the kernel's own
|
||||
* {@code PluginDescriptor} ({@code HostDescriptorTest}).
|
||||
*/
|
||||
class SettingsDescriptorTest {
|
||||
|
||||
/** The plugin project root — the working directory when the module's tests run. */
|
||||
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
|
||||
|
||||
/** One setting definition as the YAML holds it. */
|
||||
private record Def(String key, String type, String group, String help, String label, String helpAnchor,
|
||||
String showWhen, String inheritsFrom, String requiresPlatform, String range) {
|
||||
|
||||
static Def of(Map<String, Object> raw) {
|
||||
return new Def(str(raw, "key"), str(raw, "type"), str(raw, "group"), str(raw, "help"), str(raw, "label"),
|
||||
str(raw, "helpAnchor"), str(raw, "showWhen"), str(raw, "inheritsFrom"),
|
||||
str(raw, "requiresPlatform"), str(raw, "range"));
|
||||
}
|
||||
|
||||
private static String str(Map<String, Object> raw, String key) {
|
||||
Object value = raw.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> descriptor() {
|
||||
return TestSettings.descriptor();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Def> defs(String section) {
|
||||
List<Def> out = new ArrayList<>();
|
||||
Object list = descriptor().get(section);
|
||||
if (list != null) {
|
||||
for (Map<String, Object> raw : (List<Map<String, Object>>) list) {
|
||||
out.add(Def.of(raw));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Map<String, Object>> groups() {
|
||||
return (List<Map<String, Object>>) descriptor().get("settingGroups");
|
||||
}
|
||||
|
||||
private static Properties bundle(String name) throws IOException {
|
||||
Properties props = new Properties();
|
||||
try (Reader reader = Files.newBufferedReader(ROOT.resolve("i18n").resolve(name), StandardCharsets.UTF_8)) {
|
||||
props.load(reader);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
private static Map<String, Def> byKey(List<Def> schema) {
|
||||
Map<String, Def> map = new HashMap<>();
|
||||
schema.forEach(def -> map.put(def.key(), def));
|
||||
return map;
|
||||
}
|
||||
|
||||
private static List<Def> all() {
|
||||
List<Def> all = new ArrayList<>(defs("settings"));
|
||||
all.addAll(defs("siteSettings"));
|
||||
return all;
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyFieldIsInADeclaredSectionAndEverySectionIsUsed() {
|
||||
Set<String> groups = new TreeSet<>();
|
||||
groups().forEach(g -> groups.add(String.valueOf(g.get("id"))));
|
||||
Set<String> used = new TreeSet<>();
|
||||
for (Def def : all()) {
|
||||
assertTrue(groups.contains(def.group()), def.key() + " names an undeclared group '" + def.group() + "'");
|
||||
used.add(def.group());
|
||||
}
|
||||
assertEquals(groups, used, "a declared section with no fields would never show");
|
||||
assertEquals(6, groups.size(), "the six sections of the 1.6.0 layout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDependencyPointsAtARealSwitch() {
|
||||
for (List<Def> schema : List.of(defs("settings"), defs("siteSettings"))) {
|
||||
Map<String, Def> keys = byKey(schema);
|
||||
for (Def def : schema) {
|
||||
if (def.showWhen() != null) {
|
||||
Def gate = keys.get(def.showWhen());
|
||||
assertTrue(gate != null && "boolean".equals(gate.type()),
|
||||
def.key() + ": showWhen must name a boolean in the same schema, got " + def.showWhen());
|
||||
}
|
||||
if (def.inheritsFrom() != null) {
|
||||
String ref = def.inheritsFrom();
|
||||
Def source = ref.startsWith("app:")
|
||||
? byKey(defs("settings")).get(ref.substring(4)) : keys.get(ref);
|
||||
assertTrue(source != null, def.key() + ": inheritsFrom names nothing: " + ref);
|
||||
assertTrue(def.range().contains("inherit"), def.key() + ": inheritsFrom without an inherit choice");
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Def def : defs("siteSettings")) {
|
||||
if (def.requiresPlatform() != null) {
|
||||
Def platform = byKey(defs("settings")).get(def.requiresPlatform());
|
||||
assertTrue(platform != null && "boolean".equals(platform.type()),
|
||||
def.key() + ": requiresPlatform must name an app-level boolean");
|
||||
}
|
||||
}
|
||||
assertEquals("app:robots.ai-default", byKey(defs("siteSettings")).get("robots.ai-policy").inheritsFrom(),
|
||||
"the AI policy still inherits the platform default");
|
||||
assertEquals("indexnow.enabled", byKey(defs("siteSettings")).get("indexnow.enabled").requiresPlatform());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyFieldHasAHelpLineAndEveryKeyResolvesInEnglishAndSpanish() throws IOException {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (Def def : all()) {
|
||||
assertNotNull(def.help(), def.key() + " has no help line");
|
||||
keys.add(def.label());
|
||||
keys.add(def.help());
|
||||
}
|
||||
for (Map<String, Object> g : groups()) {
|
||||
keys.add(String.valueOf(g.get("label")));
|
||||
keys.add(String.valueOf(g.get("help")));
|
||||
}
|
||||
Properties en = bundle("messages.properties");
|
||||
Properties es = bundle("messages_es.properties");
|
||||
for (String key : keys) {
|
||||
assertTrue(en.containsKey(key), "missing in messages.properties: " + key);
|
||||
assertTrue(es.containsKey(key), "missing in messages_es.properties: " + key);
|
||||
}
|
||||
assertEquals(new TreeSet<>(en.stringPropertyNames()), new TreeSet<>(es.stringPropertyNames()),
|
||||
"the English and Spanish bundles carry the same keys");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyLearnMoreLinkLandsOnASectionOfTheHelpPage() throws IOException {
|
||||
assertEquals("/__plugin/discoverability/static/discoverability-help.html", descriptor().get("helpUrl"));
|
||||
String page = Files.readString(ROOT.resolve("static").resolve("discoverability-help.html"));
|
||||
List<String> anchors = new ArrayList<>();
|
||||
groups().forEach(g -> anchors.add(g.get("helpAnchor") == null ? null : String.valueOf(g.get("helpAnchor"))));
|
||||
all().forEach(def -> anchors.add(def.helpAnchor()));
|
||||
for (String anchor : anchors) {
|
||||
if (anchor != null) {
|
||||
assertTrue(page.contains("id=\"" + anchor + "\""), "the help page has no #" + anchor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* /sitemap.xml over the host's {@code ContentCatalogView}: the whole published content surface — pages AND plugin
|
||||
* content — with the hreflang alternates and {@code x-default} the host computed, {@code <lastmod>} from
|
||||
* {@code updatedAt}, noindex and canonicalised-elsewhere items left out, the index/shards past 10,000 URLs, and the
|
||||
* conditional GET. Disabled ⇒ 404; base from the trusted origin when the site has none.
|
||||
*
|
||||
* <p>The listing itself (published only, safe and unreserved paths, a throwing source contributing nothing) and the
|
||||
* URL computation are the host's, tested in the kernel; the host-it profile runs this endpoint over the real kernel
|
||||
* catalog ({@code HostCatalogParityTest}), including the head-vs-sitemap agreement.
|
||||
*/
|
||||
class SitemapEndpointTest {
|
||||
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.forLanguageTag("es");
|
||||
private static final Instant UPDATED = Instant.parse("2026-07-17T10:00:00Z");
|
||||
private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
|
||||
@BeforeEach
|
||||
void freshValidators() {
|
||||
CrawlConditional.reset(); // per-site validator state is static — isolate from sibling tests
|
||||
}
|
||||
|
||||
/** The endpoint over a listing of {@code refs} (as pages) for {@link #SITE}'s locales, sitemap on. */
|
||||
private static SitemapEndpoint endpoint(SiteView site, ContentRef... refs) {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().site("acme");
|
||||
for (ContentRef ref : refs) {
|
||||
catalog.entry("acme", Entries.page(ref, site));
|
||||
}
|
||||
return new SitemapEndpoint(catalog, TestSettings.declared());
|
||||
}
|
||||
|
||||
private static SitemapEndpoint endpoint(ContentRef... refs) {
|
||||
return endpoint(SITE, refs);
|
||||
}
|
||||
|
||||
private static final ContentRef ABOUT = ContentRef.of("about", "/about", Map.of(), List.of(EN, ES),
|
||||
Map.of("en", "About", "es", "Acerca"), Map.of("en", "About page"), "__site__/acme/about", UPDATED);
|
||||
private static final ContentRef ENTRY = ContentRef.of("my-post", "/blog/my-post",
|
||||
Map.of("es", "/blog/mi-entrada"), List.of(EN, ES), Map.of("en", "My post"), Map.of(),
|
||||
"__plugin__/blog/entry", UPDATED);
|
||||
|
||||
/** Published, but the site tells robots not to index it — must not be advertised. */
|
||||
private static final ContentRef NOINDEXED = new ContentRef("hidden", "/hidden", Map.of(), List.of(EN),
|
||||
Map.of("en", "Hidden"), Map.of(), null, "__site__/acme/hidden", true, UPDATED, true, null, null,
|
||||
Map.of());
|
||||
/** Published and indexable, but declares a DIFFERENT canonical — it is not the authoritative URL. */
|
||||
private static final ContentRef DUPLICATE = new ContentRef("dupe", "/dupe", Map.of(), List.of(EN),
|
||||
Map.of("en", "Dupe"), Map.of(), null, "__site__/acme/dupe", true, UPDATED, false,
|
||||
"https://acme.test/about", null, Map.of());
|
||||
/** Published with a SELF-referential canonical — the ordinary case, which must still be listed. */
|
||||
private static final ContentRef SELF_CANONICAL = new ContentRef("self", "/self", Map.of(), List.of(EN),
|
||||
Map.of("en", "Self"), Map.of(), null, "__site__/acme/self", true, UPDATED, false,
|
||||
"https://acme.test/self", null, Map.of());
|
||||
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers) {
|
||||
return req(site, headers, "/sitemap.xml");
|
||||
}
|
||||
|
||||
private static RouteRequest req(SiteView site, Map<String, String> headers, String path) {
|
||||
return new RouteRequest(site, EN, "GET", path, Map.of(), headers, new byte[0], Map.of(), null, "");
|
||||
}
|
||||
|
||||
/** {@code n} trivial published pages — the fixture for the sharding tests. */
|
||||
private static ContentRef[] pages(int n) {
|
||||
ContentRef[] many = new ContentRef[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
many[i] = new ContentRef("p" + i, "/p" + i, Map.of(), List.of(EN), Map.of("en", "P" + i), Map.of(),
|
||||
null, "__site__/acme/p" + i, true, UPDATED, false, null, null, Map.of());
|
||||
}
|
||||
return many;
|
||||
}
|
||||
|
||||
private static String body(RouteResponse r) {
|
||||
return new String(r.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesTheWholeContentSurfaceWithHreflangAndLastmod() {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", Entries.page(ABOUT, SITE))
|
||||
.entry("acme", Entries.of("blog", ENTRY, SITE));
|
||||
RouteResponse r = new SitemapEndpoint(catalog, TestSettings.declared()).handle(req(SITE, Map.of()));
|
||||
|
||||
assertEquals(200, r.status());
|
||||
assertEquals("application/xml; charset=utf-8", r.headers().get("Content-Type"));
|
||||
String xml = body(r);
|
||||
// Page-like items, both locales, the default unprefixed.
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), "default locale is unprefixed");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/about</loc>"), "other locale is /<lang>-prefixed");
|
||||
assertTrue(xml.contains("hreflang=\"en\"") && xml.contains("hreflang=\"es\""));
|
||||
assertTrue(xml.contains("hreflang=\"x-default\""));
|
||||
// PLUGIN content is a first-class sitemap citizen — with its LOCALIZED slug.
|
||||
assertTrue(xml.contains("<loc>https://acme.test/blog/my-post</loc>"), "virtual entry listed");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/blog/mi-entrada</loc>"), "its localized slug too");
|
||||
assertTrue(xml.contains("<lastmod>" + UPDATED + "</lastmod>"), "lastmod emitted from updatedAt");
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact document — every byte — for a small bilingual site. 2.0.0 reads its URLs from the host's listing
|
||||
* instead of computing them; this pins the document so that move cannot change what a crawler receives.
|
||||
*/
|
||||
@Test
|
||||
void theDocumentIsByteForByteWhatOnePointSixServed() {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", Entries.of("blog", ENTRY, SITE))
|
||||
.entry("acme", Entries.page(ABOUT, SITE));
|
||||
String xml = body(new SitemapEndpoint(catalog, TestSettings.declared()).handle(req(SITE, Map.of())));
|
||||
String about = """
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://acme.test/about"/>
|
||||
<xhtml:link rel="alternate" hreflang="es" href="https://acme.test/es/about"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://acme.test/about"/>
|
||||
""";
|
||||
String post = """
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://acme.test/blog/my-post"/>
|
||||
<xhtml:link rel="alternate" hreflang="es" href="https://acme.test/es/blog/mi-entrada"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://acme.test/blog/my-post"/>
|
||||
""";
|
||||
String lastmod = " <lastmod>2026-07-17T10:00:00Z</lastmod>\n";
|
||||
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" "
|
||||
+ "xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n"
|
||||
+ " <url>\n <loc>https://acme.test/about</loc>\n" + lastmod + about + " </url>\n"
|
||||
+ " <url>\n <loc>https://acme.test/blog/my-post</loc>\n" + lastmod + post + " </url>\n"
|
||||
+ " <url>\n <loc>https://acme.test/es/about</loc>\n" + lastmod + about + " </url>\n"
|
||||
+ " <url>\n <loc>https://acme.test/es/blog/mi-entrada</loc>\n" + lastmod + post + " </url>\n"
|
||||
+ "</urlset>\n", xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalGetRevalidatesWith304AndTheHeadersMatch() {
|
||||
SitemapEndpoint endpoint = endpoint(ABOUT);
|
||||
|
||||
RouteResponse fresh = endpoint.handle(req(SITE, Map.of()));
|
||||
assertEquals(200, fresh.status());
|
||||
String lastModified = fresh.headers().get("Last-Modified");
|
||||
assertTrue(lastModified != null && !lastModified.isBlank(), "the 200 carries Last-Modified");
|
||||
assertEquals("no-cache", fresh.headers().get("Cache-Control"), "cache-but-revalidate posture");
|
||||
|
||||
RouteResponse revalidated = endpoint.handle(req(SITE, Map.of("If-Modified-Since", lastModified)));
|
||||
assertEquals(304, revalidated.status(), "an unchanged sitemap revalidates without re-serializing");
|
||||
assertEquals(0, revalidated.body().length, "the 304 carries no body");
|
||||
assertEquals(lastModified, revalidated.headers().get("Last-Modified"), "same validator");
|
||||
|
||||
RouteResponse older = endpoint.handle(req(SITE,
|
||||
Map.of("If-Modified-Since", "Mon, 01 Jan 2001 00:00:00 GMT")));
|
||||
assertEquals(200, older.status(), "an outdated copy gets the full document again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledReturns404() {
|
||||
FakePluginSettings off = TestSettings.declared().site("acme", Map.of("sitemap.enabled", false));
|
||||
RouteResponse r = new SitemapEndpoint(new FakeContentCatalog().entry("acme", Entries.page(ABOUT, SITE)), off)
|
||||
.handle(req(SITE, Map.of()));
|
||||
assertEquals(404, r.status());
|
||||
assertEquals("no-store", r.headers().get("Cache-Control"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledByDefault() {
|
||||
assertEquals(200, endpoint(ABOUT).handle(req(SITE, Map.of())).status(), "sitemap.enabled defaults on");
|
||||
}
|
||||
|
||||
/**
|
||||
* Without a configured base URL the absolute URLs use the request's TRUSTED origin (scheme, host and port as
|
||||
* the kernel's trusted-proxy gate left them). 1.x read the raw Host header and guessed {@code https}.
|
||||
*/
|
||||
@Test
|
||||
void takesTheBaseFromTheTrustedOriginWhenBaseUrlUnset() {
|
||||
SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN, ES), null);
|
||||
RouteRequest request = new RouteRequest(noBase, EN, "GET", "/sitemap.xml", Map.of(),
|
||||
Map.of("Host", "spoofed.test"), new byte[0], Map.of(), null, "http://acme.test:8080");
|
||||
String xml = body(endpoint(noBase, ABOUT).handle(request));
|
||||
assertTrue(xml.contains("<loc>http://acme.test:8080/about</loc>"), xml);
|
||||
assertFalse(xml.contains("spoofed") || xml.contains("https://"), "never the Host header, never a guess");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrailingSlashOnTheConfiguredBaseIsDropped() {
|
||||
SiteView slash = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test/");
|
||||
String xml = body(endpoint(slash, ABOUT).handle(req(slash, Map.of())));
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* A sitemap is a list of URLs the site RECOMMENDS for indexing, so listing a page it separately tells robots
|
||||
* not to index contradicts itself — sitemaps.org treats such a file as a quality signal against the site.
|
||||
*
|
||||
* <p>Filtered in the plugin rather than in {@code ContentCatalog} on purpose: the router, the search indexer
|
||||
* and llms.txt all legitimately need the full published set, so narrowing the catalog would break them.
|
||||
*/
|
||||
@Test
|
||||
void noindexContentIsPublishedButNeverAdvertised() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, ABOUT, NOINDEXED).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), "indexable content still listed");
|
||||
assertFalse(xml.contains("/hidden"), "noindex content must not appear in the sitemap");
|
||||
}
|
||||
|
||||
/**
|
||||
* An item declaring a canonical elsewhere has said it is not the authoritative URL; advertising it would put
|
||||
* a self-declared non-canonical address in the sitemap. A canonical equal to the item's OWN url is the normal
|
||||
* self-referential case and must not be swept up by the same rule — that is the half a naive check breaks.
|
||||
*/
|
||||
@Test
|
||||
void anItemCanonicalisedElsewhereIsOmittedButASelfCanonicalOneIsKept() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, ABOUT, DUPLICATE, SELF_CANONICAL).handle(req(site, Map.of())));
|
||||
|
||||
assertFalse(xml.contains("/dupe"), "an item canonicalised elsewhere is not the authoritative URL");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/self</loc>"), "a SELF-referential canonical stays listed");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), "an item with no canonical stays listed");
|
||||
}
|
||||
|
||||
/**
|
||||
* A ROOT-RELATIVE canonical names an address on this site and is resolved against the base before comparing, as
|
||||
* the kernel resolves it for the {@code <head>}. 1.x compared the raw {@code /self} with the absolute URLs, so a
|
||||
* page whose canonical was its own path was dropped from the sitemap.
|
||||
*/
|
||||
@Test
|
||||
void aRootRelativeSelfCanonicalIsKeptAndARootRelativeElsewhereOneIsOmitted() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test");
|
||||
ContentRef self = new ContentRef("self", "/self", Map.of(), List.of(EN, ES), Map.of("en", "Self"), Map.of(),
|
||||
null, "__site__/acme/self", true, UPDATED, false, "/self", null, Map.of());
|
||||
ContentRef elsewhere = new ContentRef("copy", "/copy", Map.of(), List.of(EN), Map.of("en", "Copy"), Map.of(),
|
||||
null, "__site__/acme/copy", true, UPDATED, false, "/self", null, Map.of());
|
||||
String xml = body(endpoint(site, self, elsewhere).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<loc>https://acme.test/self</loc>"), xml);
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/self</loc>"), "every locale of a self-canonical item");
|
||||
assertFalse(xml.contains("/copy"), "a root-relative canonical naming ANOTHER page still points elsewhere");
|
||||
}
|
||||
|
||||
/**
|
||||
* An item that exists only in a non-default locale: its one address and its x-default are the host's (the
|
||||
* Spanish URL), never the unprefixed default path, which the site does not serve.
|
||||
*/
|
||||
@Test
|
||||
void aNonDefaultLocaleOnlyItemUsesTheHostsAddressesForLocAndXDefault() {
|
||||
ContentRef solo = ContentRef.of("solo", "/solo", Map.of("es", "/solo-es"), List.of(ES), Map.of("es", "Solo"),
|
||||
Map.of(), "__site__/acme/solo", UPDATED);
|
||||
String xml = body(endpoint(solo).handle(req(SITE, Map.of())));
|
||||
assertTrue(xml.contains("<loc>https://acme.test/es/solo-es</loc>"), xml);
|
||||
assertTrue(xml.contains("hreflang=\"x-default\" href=\"https://acme.test/es/solo-es\""), xml);
|
||||
assertFalse(xml.contains("https://acme.test/solo\""), "the unprefixed default path does not serve: " + xml);
|
||||
assertFalse(xml.contains("hreflang=\"en\""), "no alternate for a locale the item does not exist in");
|
||||
}
|
||||
|
||||
/** A canonical naming one of the item's OTHER locales' addresses is still self-referential. */
|
||||
@Test
|
||||
void aCanonicalNamingAnotherLocaleOfTheSameItemIsSelf() {
|
||||
ContentRef ref = new ContentRef("about", "/about", Map.of(), List.of(EN, ES), Map.of("en", "About"), Map.of(),
|
||||
null, "__site__/acme/about", true, UPDATED, false, "https://acme.test/es/about", null, Map.of());
|
||||
String xml = body(endpoint(ref).handle(req(SITE, Map.of())));
|
||||
assertTrue(xml.contains("<loc>https://acme.test/about</loc>"), xml);
|
||||
}
|
||||
|
||||
// ---- sitemap index -------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A small site keeps a single {@code <urlset>} — no index, no second round trip.
|
||||
*
|
||||
* <p>This is the shape almost every tenant has, and splitting a 40-URL site across an index would cost a
|
||||
* crawler two fetches to learn nothing.
|
||||
*/
|
||||
@Test
|
||||
void asmallSiteIsStillASinglePlainUrlset() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, pages(40)).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<urlset"), xml.substring(0, Math.min(200, xml.length())));
|
||||
assertFalse(xml.contains("<sitemapindex"), "no index for a site that fits in one file");
|
||||
assertEquals(40, xml.split("<loc>", -1).length - 1);
|
||||
}
|
||||
|
||||
/** …and its shard paths 404 rather than serving the same document at a second address. */
|
||||
@Test
|
||||
void aSmallSiteAnswers404OnTheShardPaths() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
|
||||
RouteResponse response = endpoint(site, pages(40)).handle(req(site, Map.of(), "/sitemap-1.xml"));
|
||||
|
||||
assertEquals(404, response.status(),
|
||||
"two URLs serving one document is the duplicate-content shape this plugin exists to avoid");
|
||||
}
|
||||
|
||||
/**
|
||||
* Past one shard's worth, {@code /sitemap.xml} becomes an index naming exactly the shards that exist.
|
||||
*
|
||||
* <p>25,000 URLs is three shards of 10,000 — the third holding 5,000 — so the count catches both an
|
||||
* off-by-one in the ceiling division and an index that advertises a shard with nothing in it.
|
||||
*/
|
||||
@Test
|
||||
void aLargeSiteGetsAnIndexNamingExactlyTheShardsThatExist() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
String xml = body(endpoint(site, pages(25_000)).handle(req(site, Map.of())));
|
||||
|
||||
assertTrue(xml.contains("<sitemapindex"), "over one shard's worth, the entry point is an index");
|
||||
assertEquals(3, xml.split("<loc>", -1).length - 1, "25,000 URLs is 3 shards, not 2 and not 4");
|
||||
assertTrue(xml.contains("<loc>https://acme.test/sitemap-1.xml</loc>"), xml);
|
||||
assertTrue(xml.contains("<loc>https://acme.test/sitemap-3.xml</loc>"), xml);
|
||||
assertFalse(xml.contains("/sitemap-4.xml"), "an empty shard must never be advertised");
|
||||
}
|
||||
|
||||
/** Each shard carries its own slice, full shards first, and the last one holds the remainder. */
|
||||
@Test
|
||||
void eachShardCarriesItsOwnSliceAndTheLastHoldsTheRemainder() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
SitemapEndpoint endpoint = endpoint(site, pages(25_000));
|
||||
|
||||
String first = body(endpoint.handle(req(site, Map.of(), "/sitemap-1.xml")));
|
||||
String last = body(endpoint.handle(req(site, Map.of(), "/sitemap-3.xml")));
|
||||
|
||||
assertEquals(10_000, first.split("<loc>", -1).length - 1);
|
||||
assertEquals(5_000, last.split("<loc>", -1).length - 1);
|
||||
assertTrue(first.contains("<urlset") && last.contains("<urlset"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shards partition the URL set: every URL appears in exactly one, and none is lost at a boundary.
|
||||
*
|
||||
* <p>Asserted as a set rather than by counting, because a boundary bug that drops one URL and duplicates
|
||||
* another leaves the totals right.
|
||||
*/
|
||||
@Test
|
||||
void theShardsPartitionTheUrlSetWithNoGapOrOverlap() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
SitemapEndpoint endpoint = endpoint(site, pages(25_000));
|
||||
|
||||
List<String> all = new java.util.ArrayList<>();
|
||||
for (int shard = 1; shard <= 3; shard++) {
|
||||
all.addAll(locs(body(endpoint.handle(req(site, Map.of(), "/sitemap-" + shard + ".xml")))));
|
||||
}
|
||||
|
||||
assertEquals(25_000, all.size(), "no URL is served twice");
|
||||
assertEquals(25_000, new java.util.HashSet<>(all).size(), "…and none is served twice under two names");
|
||||
assertTrue(all.contains("https://acme.test/p0") && all.contains("https://acme.test/p24999"),
|
||||
"the first and last items both survive the split");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shard membership is a function of the CONTENT, not of source-registration order.
|
||||
*
|
||||
* <p>The host's listing is grouped by source in an order it does not promise, which says nothing across
|
||||
* restarts or across the nodes of a cluster. If shard boundaries followed it, two nodes behind one load
|
||||
* balancer would serve <b>different content for the same shard number</b>, and a crawler alternating
|
||||
* between them would watch URLs appear and vanish with nothing in the response to explain it.
|
||||
*/
|
||||
@Test
|
||||
void shardMembershipDoesNotDependOnSourceOrder() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
ContentRef[] refs = pages(25_000);
|
||||
ContentRef[] reversed = new ContentRef[refs.length];
|
||||
for (int i = 0; i < refs.length; i++) {
|
||||
reversed[i] = refs[refs.length - 1 - i];
|
||||
}
|
||||
|
||||
String oneWay = body(endpoint(site, refs).handle(req(site, Map.of(), "/sitemap-2.xml")));
|
||||
String other = body(endpoint(site, reversed).handle(req(site, Map.of(), "/sitemap-2.xml")));
|
||||
|
||||
assertEquals(oneWay, other, "the same shard number must mean the same URLs on every node");
|
||||
}
|
||||
|
||||
/** A shard number past the end 404s — nothing links to it, so the only way there is to type it. */
|
||||
@Test
|
||||
void aShardBeyondTheEndIs404() {
|
||||
SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test");
|
||||
SitemapEndpoint endpoint = endpoint(site, pages(25_000));
|
||||
|
||||
assertEquals(404, endpoint.handle(req(site, Map.of(), "/sitemap-4.xml")).status());
|
||||
assertEquals(200, endpoint.handle(req(site, Map.of(), "/sitemap-3.xml")).status());
|
||||
}
|
||||
|
||||
/** Every shard route is declared, because the host matches routes by exact path — no patterns. */
|
||||
@Test
|
||||
void theIndexAndEveryShardAreDeclaredRoutes() {
|
||||
List<String> paths = endpoint().routes().stream()
|
||||
.map(mx.quest.runway.spi.model.Route::pathPattern).toList();
|
||||
|
||||
assertTrue(paths.contains("/sitemap.xml"));
|
||||
assertTrue(paths.contains("/sitemap-1.xml"));
|
||||
assertTrue(paths.contains("/sitemap-20.xml"));
|
||||
assertFalse(paths.contains("/sitemap-21.xml"), "the ceiling is real and must be visible in the routes");
|
||||
}
|
||||
|
||||
/** The {@code <loc>} values of a sitemap document. */
|
||||
private static List<String> locs(String xml) {
|
||||
List<String> found = new java.util.ArrayList<>();
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("<loc>([^<]+)</loc>").matcher(xml);
|
||||
while (m.find()) {
|
||||
found.add(m.group(1));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
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.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.model.HeadContext;
|
||||
import mx.quest.runway.spi.model.Provenance;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** SEO+ structured-data head: emits the WebSite/WebPage(/Organization) graph, and nothing when it shouldn't. */
|
||||
class StructuredDataHeadTest {
|
||||
|
||||
private final FakePluginSettings config = TestSettings.declared();
|
||||
private final StructuredDataHead head = new StructuredDataHead(config, Map.of());
|
||||
private final StructuredDataHead typed = new StructuredDataHead(config, Map.ofEntries(
|
||||
Map.entry("FAQPage", new FaqPageSchema()),
|
||||
Map.entry("Product", new ProductSchema()),
|
||||
Map.entry("Article", new ArticleSchema()),
|
||||
Map.entry("BlogPosting", new ArticleSchema()),
|
||||
Map.entry("LocalBusiness", new LocalBusinessSchema()),
|
||||
Map.entry("CafeOrCoffeeShop", new LocalBusinessSchema()),
|
||||
Map.entry("Service", new ServiceSchema()),
|
||||
Map.entry("ProfessionalService", new ServiceSchema()),
|
||||
Map.entry("Person", new PersonSchema()),
|
||||
Map.entry("ItemList", new CollectionSchema()),
|
||||
Map.entry("CollectionPage", new CollectionSchema())));
|
||||
|
||||
private static HeadContext pageAt(String path, String title) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta(path.substring(1), title, "",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
String canonical = "https://acme.test" + path;
|
||||
return new HeadContext(site, page, Locale.ENGLISH, canonical, canonical, List.of(), false, false);
|
||||
}
|
||||
|
||||
private void cfg(Map<String, Object> map) {
|
||||
config.site("acme", map);
|
||||
}
|
||||
|
||||
private HeadContext ctx(boolean preview, boolean noindex) {
|
||||
SiteView site = new SiteView("acme", "Acme Corp", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("about", "About Acme", "We build things.",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, noindex);
|
||||
return new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about",
|
||||
"https://acme.test/about", List.of(), preview, noindex);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsWebSiteAndWebPageByDefault() {
|
||||
cfg(Map.of()); // all defaults → jsonld.enabled true
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("application/ld+json"));
|
||||
assertTrue(out.contains("\"@type\":\"WebSite\""));
|
||||
assertTrue(out.contains("\"@type\":\"WebPage\""));
|
||||
assertTrue(out.contains("https://acme.test/about"), "the WebPage is anchored on the canonical");
|
||||
assertTrue(out.contains("About Acme"));
|
||||
assertTrue(out.contains("\"isPartOf\""), "the WebPage references the WebSite");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsOrganizationWithSameAsWhenConfigured() {
|
||||
cfg(Map.of("org.name", "Acme Corp", "org.logo", "https://acme.test/logo.png",
|
||||
"org.sameas", List.of("https://social.example/acme", "https://network.example/acme")));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"@type\":\"Organization\""));
|
||||
assertTrue(out.contains("Acme Corp"));
|
||||
assertTrue(out.contains("logo.png"));
|
||||
assertTrue(out.contains("social.example/acme") && out.contains("network.example/acme"), "sameAs profiles emitted");
|
||||
assertTrue(out.contains("\"publisher\""), "the WebPage names the Organization as publisher");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesARootRelativeOrgLogoToAbsolute() {
|
||||
cfg(Map.of("org.name", "Acme", "org.logo", "/static/img/logo.svg"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"logo\":\"https://acme.test/static/img/logo.svg\""),
|
||||
"a root-relative org.logo resolves against the site base: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsArticleHeadlineWhenTypeIsArticle() {
|
||||
cfg(Map.of("jsonld.type", "Article"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"@type\":\"Article\""));
|
||||
assertTrue(out.contains("\"headline\":\"About Acme\""), "Article uses headline, not name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsNothingOnNoindexPreviewOrWhenDisabled() {
|
||||
cfg(Map.of());
|
||||
assertEquals("", head.render(ctx(false, true)), "no structured data on a noindex page");
|
||||
assertEquals("", head.render(ctx(true, false)), "no structured data on a preview render");
|
||||
cfg(Map.of("jsonld.enabled", false));
|
||||
assertEquals("", head.render(ctx(false, false)), "disabled by the tenant");
|
||||
}
|
||||
|
||||
@Test
|
||||
void breadcrumbsAppearForAChildPageAndNotTheHome() {
|
||||
cfg(Map.of());
|
||||
assertTrue(head.render(ctx(false, false)).contains("\"@type\":\"BreadcrumbList\""), "child page has a trail");
|
||||
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta home = new PageMeta("index", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext homeCtx = new HeadContext(site, home, Locale.ENGLISH, "https://acme.test/",
|
||||
"https://acme.test/", List.of(), false, false);
|
||||
assertFalse(head.render(homeCtx).contains("BreadcrumbList"), "the home page needs no breadcrumb");
|
||||
}
|
||||
|
||||
// --- GEO signals, now folded into the single @graph (was AnswerSchemaHead) --------------------------
|
||||
|
||||
@Test
|
||||
void foldsGeoSignalsIntoTheSameNodesWhenEnabled() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertEquals(1, countOccurrences(out, "application/ld+json"), "exactly one ld+json block: " + out);
|
||||
// WebSite/WebPage each defined exactly once, carrying the GEO signals inline (not a second block by @id)
|
||||
assertEquals(1, countOccurrences(out, "\"@type\":\"WebSite\""), out);
|
||||
assertEquals(1, countOccurrences(out, "\"@type\":\"WebPage\""), out);
|
||||
assertTrue(out.contains("\"potentialAction\"") && out.contains("SearchAction"), out);
|
||||
assertTrue(out.contains("\"speakable\"") && out.contains("SpeakableSpecification"), out);
|
||||
assertTrue(out.contains("{search_term_string}"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void speakableDefaultsToRealSelectorsNotPhantomArticle() {
|
||||
cfg(Map.of("geo.enabled", true));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("SpeakableSpecification"), out);
|
||||
assertTrue(out.contains("\"h1\"") && out.contains("\"main\""), out);
|
||||
assertFalse(out.contains("\"article\""), "the default no longer emits the phantom 'article' selector: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void geoSignalsAbsentWhenGeoDisabled() {
|
||||
cfg(Map.of()); // geo.enabled default false
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("\"@type\":\"WebSite\""), "the SEO graph still emits");
|
||||
assertFalse(out.contains("speakable"), "no GEO speakable when geo disabled");
|
||||
assertFalse(out.contains("SearchAction"), "no GEO SearchAction when geo disabled");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsCurlyQueryPlaceholderToSchemaVariable() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/find?q={query}"));
|
||||
String out = head.render(ctx(false, false));
|
||||
assertTrue(out.contains("q={search_term_string}"), out);
|
||||
assertFalse(out.contains("{query}"), "the {query} placeholder is rewritten");
|
||||
}
|
||||
|
||||
// --- SoftwareApplication (item 4): homepage-only, @id-linked ---------------------------------------
|
||||
|
||||
private HeadContext homeCtx(String canonical) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta home = new PageMeta("index", "Home", "The home page.",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
return new HeadContext(site, home, Locale.ENGLISH, canonical, canonical, List.of(), false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsSoftwareApplicationOnTheHomepageOnly() {
|
||||
cfg(Map.of("software.enabled", true, "software.name", "Acme App", "software.category", "WebApplication",
|
||||
"software.price", "0", "org.name", "Acme Corp"));
|
||||
assertFalse(head.render(ctx(false, false)).contains("SoftwareApplication"),
|
||||
"not emitted on an interior page");
|
||||
String out = head.render(homeCtx("https://acme.test/"));
|
||||
assertTrue(out.contains("\"@type\":\"SoftwareApplication\""), out);
|
||||
assertTrue(out.contains("acme.test/#software"), "carries a stable @id: " + out);
|
||||
assertTrue(out.contains("Acme App"), out);
|
||||
assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"0\""), "free offer: " + out);
|
||||
assertTrue(out.contains("\"publisher\""), "references the Organization as publisher");
|
||||
assertEquals(1, countOccurrences(out, "\"@type\":\"SoftwareApplication\""), "emitted exactly once: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void softwareApplicationAlsoFiresOnALocalizedHome() {
|
||||
cfg(Map.of("software.enabled", true, "software.name", "Acme App"));
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH,
|
||||
List.of(Locale.ENGLISH, Locale.forLanguageTag("es")), "https://acme.test");
|
||||
PageMeta page = new PageMeta("index", "Inicio", "",
|
||||
List.of(Locale.ENGLISH), Locale.forLanguageTag("es"), true, false);
|
||||
HeadContext esHome = new HeadContext(site, page, Locale.forLanguageTag("es"), "https://acme.test/es",
|
||||
"https://acme.test/", List.of(), false, false);
|
||||
assertTrue(head.render(esHome).contains("SoftwareApplication"), "the localized home /es carries the entity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCrossDomainCanonicalOverrideDoesNotLeakSoftwareApplication() {
|
||||
// A per-page canonical pointing at ANOTHER host must not be mistaken for the home (which would leak the
|
||||
// homepage-only SoftwareApplication) — the pathOf() prefix guard returns a non-"/" path so isHome is false.
|
||||
cfg(Map.of("software.enabled", true, "software.name", "Acme App"));
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("syndicated", "Syndicated", "",
|
||||
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://ex.test/x",
|
||||
"https://ex.test/x", List.of(), false, false);
|
||||
String out = head.render(ctx);
|
||||
assertFalse(out.contains("SoftwareApplication"), "no homepage entity on a cross-domain canonical: " + out);
|
||||
assertTrue(out.contains("\"@type\":\"WebPage\""), "the WebPage node still emits: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noSoftwareApplicationWhenDisabled() {
|
||||
cfg(Map.of("software.name", "Acme App")); // software.enabled defaults false
|
||||
assertFalse(head.render(homeCtx("https://acme.test/")).contains("SoftwareApplication"));
|
||||
}
|
||||
|
||||
// --- type-aware structured data (item 5): FAQPage from content.schema, path-matched -----------------
|
||||
|
||||
@Test
|
||||
void emitsFaqPageForAPathDeclaredInContentSchema() {
|
||||
String schema = "/faq:\n type: FAQPage\n faq:\n"
|
||||
+ " - { q: \"Is this real?\", a: \"No, it is a demo.\" }\n"
|
||||
+ " - { q: \"Where based?\", a: \"Portland.\" }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("faq", "FAQ", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext faqCtx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/faq",
|
||||
"https://acme.test/faq", List.of(), false, false);
|
||||
|
||||
String out = typed.render(faqCtx);
|
||||
assertTrue(out.contains("\"@type\":\"FAQPage\""), out);
|
||||
assertTrue(out.contains("\"@type\":\"Question\"") && out.contains("\"@type\":\"Answer\""), out);
|
||||
assertTrue(out.contains("Is this real?") && out.contains("No, it is a demo."), out);
|
||||
assertTrue(out.contains("acme.test/faq#webpage"), "FAQPage is mainEntityOfPage-linked to the WebPage: " + out);
|
||||
// still ONE ld+json block — the typed node joins the same @graph
|
||||
assertEquals(1, countOccurrences(out, "application/ld+json"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noTypedNodesWhenPathDoesNotMatchOrTypeUnregistered() {
|
||||
cfg(Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n - { q: \"Q\", a: \"A\" }\n"));
|
||||
// ctx() is /about — no content.schema entry matches → no FAQPage
|
||||
assertFalse(typed.render(ctx(false, false)).contains("FAQPage"), "path /about matches no pattern");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsProductWithOfferForASectionPrefixPattern() {
|
||||
cfg(Map.of("content.schema",
|
||||
"/coffee-*:\n type: Product\n price: \"22.00\"\n currency: USD\n availability: InStock\n",
|
||||
"org.name", "Roasters"));
|
||||
String out = typed.render(pageAt("/coffee-guji", "Ethiopia Guji"));
|
||||
assertTrue(out.contains("\"@type\":\"Product\""), out);
|
||||
assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"22.00\""), out);
|
||||
assertTrue(out.contains("schema.org/InStock"), "availability expanded to a URL: " + out);
|
||||
assertTrue(out.contains("\"brand\""), "brand references the Organization");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsOneLocalBusinessNodePerLocation() {
|
||||
String schema = "/cafes:\n type: CafeOrCoffeeShop\n locations:\n"
|
||||
+ " - { name: \"Roastery\", street: \"14 Lamplight Lane\", locality: Portland, region: OR, postalCode: \"97201\" }\n"
|
||||
+ " - { name: \"Downtown\", street: \"88 Meridian St\", locality: Portland, region: OR }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/cafes", "Cafes"));
|
||||
assertEquals(2, countOccurrences(out, "\"@type\":\"CafeOrCoffeeShop\""), "one node per location: " + out);
|
||||
assertTrue(out.contains("Roastery") && out.contains("Downtown"), out);
|
||||
assertTrue(out.contains("\"@type\":\"PostalAddress\"") && out.contains("14 Lamplight Lane"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emitsAPersonPerTeamMember() {
|
||||
String schema = "/team:\n type: Person\n people:\n"
|
||||
+ " - { name: \"Theo Vance\", jobTitle: \"Head Roaster\" }\n"
|
||||
+ " - { name: \"Mara Okafor\", jobTitle: \"Cafe Director\" }\n";
|
||||
cfg(Map.of("content.schema", schema, "org.name", "Nocturne"));
|
||||
String out = typed.render(pageAt("/team", "Team"));
|
||||
assertEquals(2, countOccurrences(out, "\"@type\":\"Person\""), out);
|
||||
assertTrue(out.contains("Theo Vance") && out.contains("Mara Okafor"), out);
|
||||
assertTrue(out.contains("\"worksFor\""), "worksFor references the Organization");
|
||||
}
|
||||
|
||||
// --- ItemList on a collection page ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void emitsAnItemListForACollectionPage() {
|
||||
String schema = "/coffees:\n type: ItemList\n items:\n"
|
||||
+ " - { name: \"Ethiopia Guji\", url: \"/coffee-ethiopia-guji\" }\n"
|
||||
+ " - { name: \"Colombia Huila\", url: \"/coffee-colombia-huila\" }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/coffees", "Our Coffees"));
|
||||
assertTrue(out.contains("\"@type\":\"ItemList\""), out);
|
||||
// The two members appear as positioned ListItems inside itemListElement (the page's breadcrumb also uses
|
||||
// ListItem, so assert on the member payloads rather than a raw ListItem count).
|
||||
assertTrue(out.contains("Ethiopia Guji") && out.contains("Colombia Huila"), out);
|
||||
assertTrue(out.contains("https://acme.test/coffee-ethiopia-guji")
|
||||
&& out.contains("https://acme.test/coffee-colombia-huila"),
|
||||
"root-relative member urls are absolutized against the base: " + out);
|
||||
assertTrue(out.contains("acme.test/coffees#itemlist"), "the ItemList carries a stable @id: " + out);
|
||||
assertTrue(out.contains("\"mainEntityOfPage\""), "the ItemList is linked to the page: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectionPageAliasAlsoEmitsAnItemList() {
|
||||
cfg(Map.of("content.schema", "/index:\n type: CollectionPage\n items:\n - { name: A, url: /a }\n"));
|
||||
assertTrue(typed.render(pageAt("/index", "Index")).contains("\"@type\":\"ItemList\""),
|
||||
"CollectionPage is an alias for the ItemList emitter");
|
||||
}
|
||||
|
||||
// --- several type-blocks on one path ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void emitsEveryTypeBlockWhenAPathDeclaresAList() {
|
||||
// A pricing page that is BOTH an FAQPage AND a Service — the list form yields both nodes in one @graph.
|
||||
String schema = "/pricing:\n"
|
||||
+ " - type: FAQPage\n faq:\n - { q: \"Why ranges?\", a: \"Scope drives cost.\" }\n"
|
||||
+ " - { q: \"Discounts?\", a: \"For non-profits.\" }\n"
|
||||
+ " - type: Service\n name: \"Advisory Sprint\"\n offers:\n"
|
||||
+ " - { name: \"Sprint\", price: \"18000\", currency: USD }\n";
|
||||
cfg(Map.of("content.schema", schema, "org.name", "Northbeam"));
|
||||
String out = typed.render(pageAt("/pricing", "Pricing"));
|
||||
assertTrue(out.contains("\"@type\":\"FAQPage\""), "first block emitted: " + out);
|
||||
assertTrue(out.contains("\"@type\":\"Service\""), "second block emitted: " + out);
|
||||
assertTrue(out.contains("Why ranges?") && out.contains("Advisory Sprint"), out);
|
||||
assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"18000\""),
|
||||
"the priced tier is a machine-readable Offer: " + out);
|
||||
assertEquals(1, countOccurrences(out, "application/ld+json"), "still one ld+json block: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecurringServiceOfferBecomesAUnitPriceSpecification() {
|
||||
String schema = "/pricing:\n type: Service\n name: \"Northbeam\"\n offers:\n"
|
||||
+ " - { name: \"Growth Retainer\", price: \"32000\", currency: USD, unit: month }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/pricing", "Pricing"));
|
||||
assertTrue(out.contains("\"@type\":\"UnitPriceSpecification\""), "a per-unit price is a spec: " + out);
|
||||
assertTrue(out.contains("\"unitText\":\"month\"") && out.contains("\"price\":\"32000\""), out);
|
||||
}
|
||||
|
||||
// --- breadcrumb @id link + collection parent level --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void webPageLinksToTheBreadcrumbById() {
|
||||
cfg(Map.of());
|
||||
String out = head.render(ctx(false, false)); // /about — a child page
|
||||
assertTrue(out.contains("acme.test/about#breadcrumb"), "the BreadcrumbList has a stable @id: " + out);
|
||||
assertTrue(out.contains("\"breadcrumb\":{\"@id\":\"https://acme.test/about#breadcrumb\"}"),
|
||||
"the WebPage points at the BreadcrumbList by @id: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertsTheDeclaredCollectionParentAsAMiddleBreadcrumbLevel() {
|
||||
// A product detail page declares its parent collection — the trail reads Home → Coffees → Guji.
|
||||
String schema = "/coffee-*:\n type: Product\n price: \"22.00\"\n currency: USD\n"
|
||||
+ " breadcrumb: { name: \"Coffees\", url: \"/coffees\" }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/coffee-guji", "Ethiopia Guji"));
|
||||
assertTrue(out.contains("\"@type\":\"BreadcrumbList\""), out);
|
||||
assertEquals(3, countOccurrences(out, "\"@type\":\"ListItem\""), "Home + Coffees + the page = 3 levels: " + out);
|
||||
assertTrue(out.contains("Coffees") && out.contains("https://acme.test/coffees"),
|
||||
"the parent collection is a middle level: " + out);
|
||||
assertTrue(out.contains("\"position\":1") && out.contains("\"position\":2") && out.contains("\"position\":3"),
|
||||
"positions run 1..3: " + out);
|
||||
}
|
||||
|
||||
// --- LocalBusiness @id + page link ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void localBusinessNodesCarryAnIdAndLinkToThePage() {
|
||||
String schema = "/cafes:\n type: CafeOrCoffeeShop\n locations:\n"
|
||||
+ " - { name: \"Roastery\", locality: Portland }\n"
|
||||
+ " - { name: \"Downtown\", locality: Portland }\n";
|
||||
cfg(Map.of("content.schema", schema));
|
||||
String out = typed.render(pageAt("/cafes", "Cafes"));
|
||||
assertTrue(out.contains("acme.test/cafes#business-1") && out.contains("acme.test/cafes#business-2"),
|
||||
"each location gets a distinct @id: " + out);
|
||||
assertEquals(2, countOccurrences(out, "\"mainEntityOfPage\""), "each business is linked to the page: " + out);
|
||||
}
|
||||
|
||||
private static int countOccurrences(String haystack, String needle) {
|
||||
int count = 0;
|
||||
int from = 0;
|
||||
int at;
|
||||
while ((at = haystack.indexOf(needle, from)) >= 0) {
|
||||
count++;
|
||||
from = at + needle.length();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* The defect this fixed: {@code datePublished} and {@code author} could ONLY come from the shared
|
||||
* {@code content.schema} block, which matches by {@code *}-prefix. A blog is therefore covered by one
|
||||
* {@code /blog/*} entry for EVERY post, so a site could assert only one date and one author across all of
|
||||
* them — false of nearly every page it appeared on, which is exactly what structured-data policy prohibits.
|
||||
* Per-item provenance must win so each entry states its own truth.
|
||||
*/
|
||||
@Test
|
||||
void perItemProvenanceWinsOverTheSharedContentSchemaBlock() {
|
||||
cfg(Map.of("content.schema", "/blog/*:\n type: BlogPosting\n"
|
||||
+ " author: Shared Fallback Author\n datePublished: 2020-01-01\n"));
|
||||
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("blog:post-1", "Real Post", "", List.of(Locale.ENGLISH), Locale.ENGLISH,
|
||||
true, false, "blog",
|
||||
new Provenance("Ada Lovelace", Instant.parse("2026-03-04T00:00:00Z"),
|
||||
Instant.parse("2026-05-06T12:34:56Z")));
|
||||
HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/blog/post-1",
|
||||
"https://acme.test/blog/post-1", List.of(), false, false);
|
||||
|
||||
String out = typed.render(ctx);
|
||||
assertTrue(out.contains("\"name\":\"Ada Lovelace\""), "the item's own author must win: " + out);
|
||||
assertFalse(out.contains("Shared Fallback Author"), "the shared block must not override the item");
|
||||
assertTrue(out.contains("\"datePublished\":\"2026-03-04\""), "the item's own date must win: " + out);
|
||||
assertFalse(out.contains("2020-01-01"), "the shared date must not be asserted on this post");
|
||||
// dateModified comes from the host-derived updatedAt, rendered at DAY precision (not second).
|
||||
assertTrue(out.contains("\"dateModified\":\"2026-05-06\""), out);
|
||||
}
|
||||
|
||||
/** With no per-item provenance the configured values still apply — existing sites keep working unchanged. */
|
||||
@Test
|
||||
void theSharedBlockStillAppliesWhenTheItemHasNoProvenance() {
|
||||
cfg(Map.of("content.schema", "/about:\n type: Article\n"
|
||||
+ " author: Editorial Team\n datePublished: 2024-02-03\n"));
|
||||
|
||||
String out = typed.render(pageAt("/about", "About Acme"));
|
||||
assertTrue(out.contains("\"name\":\"Editorial Team\""), out);
|
||||
assertTrue(out.contains("\"datePublished\":\"2024-02-03\""), out);
|
||||
}
|
||||
|
||||
/**
|
||||
* The emitted JSON-LD must be <b>byte-reproducible</b>, so the same inputs always render the same bytes.
|
||||
*
|
||||
* <p>This is a regression guard with a real history. {@code SearchAction.target} was built with
|
||||
* {@code Map.of(...)}, and {@code java.util.Map.of} randomizes iteration order <b>per JVM instance</b>
|
||||
* ({@code ImmutableCollections.SALT}) — so the key order was stable within one run and flipped on roughly
|
||||
* every other restart. An operator diffing live homepages across an upgrade found it and reasonably
|
||||
* concluded it was a one-off change between builds; it was not, it was every restart, indefinitely.
|
||||
*
|
||||
* <p>Semantically harmless — the graphs are equal key-sorted — but it made rendered output
|
||||
* non-reproducible, and the page's strong ETag folds metadata and templates rather than the body, so the
|
||||
* validator did <b>not</b> change when the bytes did.
|
||||
*
|
||||
* <p>Asserted on the exact ordered substring rather than by parsing, because parsing would compare the
|
||||
* graphs and pass under exactly the defect this exists to catch.
|
||||
*/
|
||||
@Test
|
||||
void theSearchActionTargetHasADeterministicKeyOrder() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}"));
|
||||
String out = head.render(ctx(false, false));
|
||||
|
||||
assertTrue(out.contains("\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":"),
|
||||
() -> "SearchAction.target must serialize @type first, deterministically; got:\n" + out);
|
||||
}
|
||||
|
||||
/** Same inputs, same bytes — the general property, asserted over repeated renders. */
|
||||
@Test
|
||||
void repeatedRendersOfTheSameInputProduceIdenticalBytes() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}"));
|
||||
String first = head.render(ctx(false, false));
|
||||
for (int i = 0; i < 20; i++) {
|
||||
assertEquals(first, head.render(ctx(false, false)), "structured data must be byte-reproducible");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A DETERMINISTIC guard that no serialized JSON-LD node is built with a multi-entry {@code Map.of(...)}.
|
||||
*
|
||||
* <h2>Why a source check and not just the behavioural test above</h2>
|
||||
* The behavioural test is the right description of intent, but it is a <b>weak</b> guard on its own,
|
||||
* because the defect it guards is probabilistic: {@code Map.of} picks one of the two orders per JVM
|
||||
* instance, so a reintroduction passes roughly half the time — and Maven reuses forked JVMs, so it can
|
||||
* pass for many consecutive runs. Measured: reverting the fix and re-running six times produced five
|
||||
* passes and one failure. A guard that reports green five times out of six is not a guard.
|
||||
*
|
||||
* <p>So this asserts the property at the only place it is reliably observable: the source. A single-entry
|
||||
* {@code Map.of("@id", …)} is fine — one key cannot be misordered — and an empty {@code Map.of()} is fine.
|
||||
* Only two-or-more entries can vary, and those must use an insertion-ordered map.
|
||||
*
|
||||
* <p>If this fails: build the node with {@code Ld.node(...)} or a {@link java.util.LinkedHashMap}. The
|
||||
* requirement is byte-reproducible output, not any particular key order.
|
||||
*/
|
||||
@Test
|
||||
void noSerializedNodeIsBuiltWithAMultiEntryMapOf() throws Exception {
|
||||
for (String file : SCANNED_SOURCES) {
|
||||
java.nio.file.Path path = java.nio.file.Path.of("src/main/java/mx/quest/discover", file);
|
||||
if (!java.nio.file.Files.exists(path)) {
|
||||
continue;
|
||||
}
|
||||
String source = stripCommentsAndStrings(java.nio.file.Files.readString(path));
|
||||
int at = 0;
|
||||
while ((at = source.indexOf("Map.of(", at)) >= 0) {
|
||||
int entries = topLevelArgumentsFrom(source, at + "Map.of(".length());
|
||||
int offending = at;
|
||||
assertTrue(entries <= 2, () -> file + " builds a multi-entry Map.of near offset " + offending
|
||||
+ ", whose iteration order is randomized PER JVM INSTANCE and would make emitted "
|
||||
+ "JSON-LD non-reproducible across restarts. Use Ld.node(...) or a LinkedHashMap.");
|
||||
at += "Map.of(".length();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The sources whose output is serialized into JSON-LD, and so must be byte-reproducible. */
|
||||
private static final java.util.List<String> SCANNED_SOURCES = java.util.List.of(
|
||||
"StructuredDataHead.java", "Ld.java", "ArticleSchema.java", "ProductSchema.java",
|
||||
"LocalBusinessSchema.java", "FaqPageSchema.java", "PersonSchema.java", "ServiceSchema.java",
|
||||
"CollectionSchema.java");
|
||||
|
||||
/**
|
||||
* Blanks comments and string literals, preserving offsets and newlines.
|
||||
*
|
||||
* <p>Done before scanning rather than per line, because the previous version read the file LINE BY LINE
|
||||
* and therefore only ever saw the single-line form of {@code Map.of(...)}. A call whose arguments wrap
|
||||
* onto following lines — the natural formatting for three or more entries under a 120-column limit, which
|
||||
* is precisely the case at risk — left one comma or none on the opening line and sailed through. The
|
||||
* guard was reliable only for the shape the defect was least likely to take.
|
||||
*
|
||||
* <p>Blanking rather than deleting keeps every offset intact, so the failure message can point at a real
|
||||
* position in the file. Strings are blanked so a {@code Map.of} mentioned inside one, or a comma inside a
|
||||
* string argument, cannot be miscounted.
|
||||
*/
|
||||
private static String stripCommentsAndStrings(String source) {
|
||||
StringBuilder out = new StringBuilder(source.length());
|
||||
int i = 0;
|
||||
while (i < source.length()) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '/' && i + 1 < source.length() && source.charAt(i + 1) == '/') {
|
||||
while (i < source.length() && source.charAt(i) != '\n') {
|
||||
out.append(' ');
|
||||
i++;
|
||||
}
|
||||
} else if (c == '/' && i + 1 < source.length() && source.charAt(i + 1) == '*') {
|
||||
while (i < source.length() && !(source.charAt(i) == '*' && i + 1 < source.length()
|
||||
&& source.charAt(i + 1) == '/')) {
|
||||
out.append(source.charAt(i) == '\n' ? '\n' : ' ');
|
||||
i++;
|
||||
}
|
||||
for (int k = 0; k < 2 && i < source.length(); k++, i++) {
|
||||
out.append(' ');
|
||||
}
|
||||
} else if (c == '"' || c == '\'') {
|
||||
char quote = c;
|
||||
out.append(' ');
|
||||
i++;
|
||||
while (i < source.length() && source.charAt(i) != quote) {
|
||||
if (source.charAt(i) == '\\') {
|
||||
out.append(' ');
|
||||
i++;
|
||||
}
|
||||
if (i < source.length()) {
|
||||
out.append(source.charAt(i) == '\n' ? '\n' : ' ');
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (i < source.length()) {
|
||||
out.append(' ');
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
out.append(c);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** How many top-level arguments the call opening at {@code from} has (0 when it is empty). */
|
||||
private static int topLevelArgumentsFrom(String source, int from) {
|
||||
int depth = 0;
|
||||
int commas = 0;
|
||||
boolean any = false;
|
||||
for (int i = from; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '(' || c == '[' || c == '{') {
|
||||
depth++;
|
||||
} else if (c == ')' || c == ']' || c == '}') {
|
||||
if (depth == 0) {
|
||||
return any ? commas + 1 : 0;
|
||||
}
|
||||
depth--;
|
||||
} else if (c == ',' && depth == 0) {
|
||||
commas++;
|
||||
}
|
||||
if (!Character.isWhitespace(c)) {
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return any ? commas + 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guard can actually fail — proven against synthetic sources rather than hoped for.
|
||||
*
|
||||
* <p>A source-level scan that silently matches nothing is indistinguishable from a codebase that is
|
||||
* clean, and this one WAS partly that: it could not see a wrapped call. So the scanner's two halves are
|
||||
* exercised directly, including the multi-line form it used to miss.
|
||||
*/
|
||||
@Test
|
||||
void theMapOfScannerCatchesBothTheSingleLineAndTheWrappedForm() {
|
||||
String singleLine = "var x = Map.of(\"a\", 1, \"b\", 2);";
|
||||
String wrapped = "var x = Map.of(\n \"a\", 1,\n \"b\", 2,\n \"c\", 3);";
|
||||
String safe = "var x = Map.of(\"only\", 1);";
|
||||
String inAComment = "// Map.of(\"a\", 1, \"b\", 2) is what NOT to do";
|
||||
String inAString = "var s = \"Map.of(a, 1, b, 2)\";";
|
||||
|
||||
assertEquals(4, argumentsOfFirstMapOf(singleLine), "two entries = four arguments");
|
||||
assertEquals(6, argumentsOfFirstMapOf(wrapped), "the wrapped form is the one it used to miss");
|
||||
assertEquals(2, argumentsOfFirstMapOf(safe), "a single entry is fine");
|
||||
assertEquals(-1, argumentsOfFirstMapOf(inAComment), "prose explaining the rule is not a violation");
|
||||
assertEquals(-1, argumentsOfFirstMapOf(inAString), "nor is a string that happens to contain it");
|
||||
}
|
||||
|
||||
/** Arguments of the first {@code Map.of(} in {@code source} after stripping, or {@code -1} if none. */
|
||||
private static int argumentsOfFirstMapOf(String source) {
|
||||
String stripped = stripCommentsAndStrings(source);
|
||||
int at = stripped.indexOf("Map.of(");
|
||||
return at < 0 ? -1 : topLevelArgumentsFrom(stripped, at + "Map.of(".length());
|
||||
}
|
||||
|
||||
/**
|
||||
* The declared head input names the very file this contributor reads.
|
||||
*
|
||||
* <p>{@code headInputs} is answered without any storage layout, so the path is a literal — and a literal
|
||||
* that does not match what the kernel reads folds a stable "absent" marker forever. The validator then
|
||||
* looks correct while covering nothing, and the symptom is a stale social card or organisation name on
|
||||
* every cached client, weeks later, with nothing pointing back here.
|
||||
*
|
||||
* <p>The kernel pins the other half of the convention ({@code <site>/plugins/<id>.yml}); this pins that
|
||||
* the id in the path is the id this contributor actually looks up its settings under, so renaming the
|
||||
* plugin cannot leave the declaration behind.
|
||||
*/
|
||||
@Test
|
||||
void theDeclaredHeadInputIsThisPluginsOwnSettingsFile() {
|
||||
assertEquals(List.of("plugins/" + StructuredDataHead.PLUGIN_ID + ".yml"), head.headInputs("acme"));
|
||||
assertEquals(List.of("plugins/discoverability.yml"), head.headInputs("acme"),
|
||||
"the kernel reads <site>/plugins/<id>.yml — see SitePluginConfigServiceTest");
|
||||
}
|
||||
|
||||
// --- a host-less site: absolute URLs from HeadContext.origin() (SPI 1.0.0, discoverability 2.1.0) ------------
|
||||
|
||||
/** A host-less site (no base URL, no host name — the platform's catch-all default): its canonical is relative. */
|
||||
private static HeadContext hostless(String path, String title, String origin) {
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "");
|
||||
PageMeta page = new PageMeta(path.substring(1), title, "", List.of(Locale.ENGLISH), Locale.ENGLISH, true,
|
||||
false);
|
||||
return new HeadContext(site, page, Locale.ENGLISH, path, path, List.of(), false, false, null, null, origin);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHostlessSitesGraphIsAbsoluteAgainstTheTrustedOrigin() {
|
||||
cfg(Map.of("org.name", "Acme", "org.logo", "/static/logo.svg"));
|
||||
String out = head.render(hostless("/about", "About", "http://10.0.0.5:8080"));
|
||||
assertTrue(out.contains("\"@id\":\"http://10.0.0.5:8080/#website\""), out);
|
||||
assertTrue(out.contains("\"url\":\"http://10.0.0.5:8080/\""), "WebSite/Organization url: " + out);
|
||||
assertTrue(out.contains("\"@id\":\"http://10.0.0.5:8080/about#webpage\""), out);
|
||||
assertTrue(out.contains("\"url\":\"http://10.0.0.5:8080/about\""), out);
|
||||
assertTrue(out.contains("\"logo\":\"http://10.0.0.5:8080/static/logo.svg\""), out);
|
||||
assertTrue(out.contains("\"@type\":\"BreadcrumbList\""), "a host-less deep page now has its trail: " + out);
|
||||
assertTrue(out.contains("\"item\":\"http://10.0.0.5:8080/\""), out);
|
||||
assertFalse(out.contains("\":\"/"), "no root-relative URL or @id is left: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHostlessSiteGainsItsSearchActionWithAnAbsoluteTemplate() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}"));
|
||||
String out = head.render(hostless("/about", "About", "https://example.test"));
|
||||
assertTrue(out.contains("\"urlTemplate\":\"https://example.test/search?q={search_term_string}\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHostlessHomeIsRecognisedAndCarriesNoTrail() {
|
||||
cfg(Map.of("software.enabled", true));
|
||||
String out = head.render(hostless("/", "Home", "https://example.test"));
|
||||
assertTrue(out.contains("\"@type\":\"SoftwareApplication\""), "the home is still the home: " + out);
|
||||
assertTrue(out.contains("\"@id\":\"https://example.test/#webpage\""), out);
|
||||
assertFalse(out.contains("BreadcrumbList"), out);
|
||||
}
|
||||
|
||||
/** A context with no origin (the constructor without one, or no request) renders exactly as 2.0.0 did. */
|
||||
@Test
|
||||
void withoutAnOriginAHostlessGraphStaysRootRelativeAsBefore() {
|
||||
cfg(Map.of("geo.enabled", true, "search.url", "/search"));
|
||||
String out = head.render(hostless("/about", "About", ""));
|
||||
assertTrue(out.contains("\"@id\":\"/about#webpage\""), out);
|
||||
assertTrue(out.contains("\"@id\":\"/#website\""), out);
|
||||
assertFalse(out.contains("SearchAction"), "no base, no SearchAction — as 2.0.0: " + out);
|
||||
assertFalse(out.contains("BreadcrumbList"), out);
|
||||
}
|
||||
|
||||
/** The site's base URL wins over the request origin: a site with a host never takes the address it was reached at. */
|
||||
@Test
|
||||
void aConfiguredBaseUrlWinsOverTheOrigin() {
|
||||
cfg(Map.of());
|
||||
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test");
|
||||
PageMeta page = new PageMeta("about", "About", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about",
|
||||
"https://acme.test/about", List.of(), false, false, null, null, "http://10.0.0.5:8080");
|
||||
String out = head.render(ctx);
|
||||
assertTrue(out.contains("https://acme.test/#website"), out);
|
||||
assertFalse(out.contains("10.0.0.5"), out);
|
||||
HeadContext noOrigin = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about",
|
||||
"https://acme.test/about", List.of(), false, false);
|
||||
assertEquals(head.render(noOrigin), out, "byte-identical to the origin-less render of the same page");
|
||||
}
|
||||
|
||||
/** A cross-domain canonical override is absolute already and passes through untouched. */
|
||||
@Test
|
||||
void anAbsoluteCanonicalIsNeverRebased() {
|
||||
assertEquals("https://other.test/x", StructuredDataHead.absolute("https://other.test/x", "http://a.test"));
|
||||
assertEquals("//cdn.test/x", StructuredDataHead.absolute("//cdn.test/x", "http://a.test"),
|
||||
"a protocol-relative URL already names a host");
|
||||
assertEquals("/x", StructuredDataHead.absolute("/x", ""), "no base known: left as it is");
|
||||
assertEquals("http://a.test/x", StructuredDataHead.absolute("/x", "http://a.test"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mx.quest.discover;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* Test settings shaped the way the kernel's {@code PluginSettings} hands them to the plugin: the {@code default:}s
|
||||
* this plugin's descriptor declares, overlaid by what a test stores for a site.
|
||||
*
|
||||
* <p>Every unit test builds its settings here rather than from an empty map, so each assertion also proves that the
|
||||
* declared defaults change nothing a tenant sees (1.x read only the stored values and applied its code fallbacks;
|
||||
* since 2.0.0 the host applies the declared defaults first).
|
||||
*/
|
||||
final class TestSettings {
|
||||
|
||||
private TestSettings() {
|
||||
}
|
||||
|
||||
/** A fake {@code PluginSettings} carrying the descriptor's declared per-site defaults and no stored value. */
|
||||
static FakePluginSettings declared() {
|
||||
return new FakePluginSettings().defaults(declaredDefaults());
|
||||
}
|
||||
|
||||
/** A fake with NO declared defaults — what the plugin would see if the host stopped applying them. */
|
||||
static FakePluginSettings bare() {
|
||||
return new FakePluginSettings();
|
||||
}
|
||||
|
||||
/** The {@code default:} of every {@code siteSettings} key that declares one (secret-typed keys never). */
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> declaredDefaults() {
|
||||
Map<String, Object> defaults = new LinkedHashMap<>();
|
||||
for (Map<String, Object> def : (List<Map<String, Object>>) descriptor().get("siteSettings")) {
|
||||
if (def.containsKey("default") && def.get("default") != null && !"secret".equals(def.get("type"))) {
|
||||
defaults.put(String.valueOf(def.get("key")), def.get("default"));
|
||||
}
|
||||
}
|
||||
return defaults;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> descriptor() {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Discoverability — help</title>
|
||||
<style>
|
||||
body { font: 16px/1.6 system-ui, sans-serif; max-width: 44rem; margin: 2rem auto; padding: 0 1rem; color: #1a2233; }
|
||||
h1 { font-size: 1.6rem; } h2 { font-size: 1.2rem; margin-top: 2rem; } h3 { font-size: 1.05rem; margin-top: 1.5rem; }
|
||||
pre { background: #f2f4f7; padding: .75rem; border-radius: .25rem; overflow-x: auto; font-size: .85rem; } pre code { padding: 0; }
|
||||
:target { scroll-margin-top: 1rem; background: #fff8db; }
|
||||
code { background: #f2f4f7; padding: .1rem .35rem; border-radius: .25rem; }
|
||||
table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: .4rem .5rem; border-bottom: 1px solid #e6e9ef; vertical-align: top; }
|
||||
.muted { color: #667085; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Discoverability — SEO+ & GEO</h1>
|
||||
<p>This plugin makes your site legible to <strong>search engines</strong> and <strong>AI answer engines</strong>.
|
||||
It adds the layer the platform's built-in SEO deliberately leaves out — it never duplicates a tag the kernel
|
||||
already emits (canonical, <code>hreflang</code>, <code>robots</code>, Open Graph and Twitter cards are already
|
||||
produced for free).</p>
|
||||
|
||||
<h2>What it adds</h2>
|
||||
<table>
|
||||
<tr><th>Surface</th><th>What & where</th></tr>
|
||||
<tr><td>Structured data</td><td>schema.org <strong>JSON-LD</strong> (<code>WebSite</code> / <code>WebPage</code>
|
||||
or <code>Article</code> / <code>Organization</code> / <code>BreadcrumbList</code>) injected into every
|
||||
indexable page's <code><head></code>.</td></tr>
|
||||
<tr><td>Sitemap</td><td><code>/sitemap.xml</code> — every published, indexable page with its
|
||||
<code>hreflang</code> alternates. Pages you mark <em>Exclude from search engines (noindex)</em>, and pages whose
|
||||
canonical URL points elsewhere, are left out on purpose: a sitemap
|
||||
recommends pages for indexing, so listing one you told robots to skip contradicts itself.</td></tr>
|
||||
<tr><td>Crawler rules</td><td><code>/robots.txt</code> — tells crawlers what they may fetch. Set the
|
||||
<strong>AI-crawler policy</strong> below to allow or refuse AI/answer engines, and list any paths to keep
|
||||
crawlers away from. Refusing AI crawlers never removes you from ordinary web search: the AI opt-out names
|
||||
the AI agents only (for example <code>Google-Extended</code>, never <code>Googlebot</code>).</td></tr>
|
||||
<tr><td>GEO · <code>llms.txt</code></td><td><code>/llms.txt</code> — a compact, machine-friendly index of your
|
||||
pages for LLM / answer engines (opt-in). <em>Honest note:</em> this is a community proposal, not a
|
||||
standard. No major engine documents reading it, and Google states explicitly that no AI-specific file is
|
||||
needed to appear in its AI features. It is cheap to publish and harmless; treat it as an optional extra,
|
||||
not as something your visibility depends on.</td></tr>
|
||||
<tr><td>GEO · answer schema</td><td>A <code>SearchAction</code> (site search) and <code>Speakable</code> hints
|
||||
that enrich the structured-data graph for AI extraction (opt-in).</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>Configure it</h2>
|
||||
<p>Everything below is per site, on this plugin's settings page (the site console's <em>Settings</em> menu,
|
||||
<em>Discoverability (SEO+ & GEO)</em>), and reaches your pages, <code>robots.txt</code>, the sitemap and
|
||||
<code>/llms.txt</code> at once. The page is in
|
||||
the same sections as this help; each field carries a one-line explanation, and the <em>Learn more</em> links
|
||||
land here. Fields that only matter when a switch is on are hidden while it is off (their values are kept).</p>
|
||||
<p id="permission"><strong>Who can change them.</strong> The settings page, and the Discoverability card on the
|
||||
dashboard, need the permission <em>Manage discoverability (SEO & GEO)</em>
|
||||
(<code>discoverability|settings</code>). No role holds it until it is granted, so out of the box only the site's
|
||||
superadmin and administrators have it. Grant it to a role or a user on the site's <em>Permissions</em>
|
||||
screen.</p>
|
||||
<p><strong>What it takes from the site itself.</strong> The site's <strong>name</strong> is the
|
||||
<code>WebSite</code> name on every page, the heading of <code>/llms.txt</code>, the name of a local business
|
||||
that gives none, and the homepage product's name when neither a product name nor an organization name is set.
|
||||
The site's <strong>address</strong> (its base URL, else <code>https://</code> plus its first host name; for a
|
||||
site with neither, the address the page was requested at) starts every full URL this plugin builds from a path
|
||||
on the site. The site's <strong>languages</strong>: each page is described in the
|
||||
language it is served in, and <code>/llms.txt</code> lists each page once, in the site's default language
|
||||
(a page that does not exist in it is listed at its own address).</p>
|
||||
|
||||
<h3 id="structured-data">Structured data for search engines</h3>
|
||||
<p>schema.org <strong>JSON-LD</strong> in every page's <code><head></code>: the site (<code>WebSite</code>),
|
||||
the page (<code>WebPage</code>, or <code>Article</code> for blogs and news), its <code>BreadcrumbList</code>, and
|
||||
the <code>Organization</code> that publishes it. It is on by default and is the switch everything structured
|
||||
depends on — the organization, the homepage product, the per-page types and GEO's search action and speakable
|
||||
hints all disappear while it is off. A page marked <em>Exclude from search engines (noindex)</em> gets no
|
||||
structured data at all, and is left out of <code>/llms.txt</code> as well as the sitemap. A preview gets no
|
||||
structured data either.</p>
|
||||
<ul>
|
||||
<li><strong>Default page type</strong> — what every page is described as unless
|
||||
<a href="#content-schema">Per-page types</a> gives it a page type of its own, which then replaces this one
|
||||
on that page. <code>WebPage</code> (the default) or <code>Article</code>. An <code>Article</code> page
|
||||
carries the page title as its <code>headline</code> instead of its <code>name</code>; its author, dates
|
||||
and images come only from an <code>Article</code>, <code>BlogPosting</code> or <code>NewsArticle</code>
|
||||
block in Per-page types. The form offers only these two;
|
||||
in a hand-edited settings file, anything but exactly <code>Article</code> means <code>WebPage</code>.</li>
|
||||
<li><strong>Breadcrumb trail</strong> — on by default. Every page except the home page (<code>/</code>), and except a page whose
|
||||
canonical URL points to another site, gets a trail: <em>Home</em>, then the parent a Per-page types <code>breadcrumb</code> names (if any), then the
|
||||
page, named by its title (or by its path when the title is blank). The first step is always the English
|
||||
word <em>Home</em>, whatever the page's language, and links to the site's root. The home page of another
|
||||
language (<code>/es</code>) is not <code>/</code>, so it gets a two-step trail.</li>
|
||||
<li><strong>Organization name / logo / profiles</strong> — identify the site as an entity (knowledge-graph
|
||||
signals, shared by search and AI). Leave the name blank to publish no organization. The logo may be a
|
||||
path on the site (<code>/img/logo.png</code>); it is turned into a full URL for you.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="content-schema">Per-page types (<code>content.schema</code>)</h3>
|
||||
<p>A small YAML document keyed by URL path that declares what particular pages are, so search engines can show
|
||||
them (and, for some types, show rich results). Each page also has a line in the page editor's quality panel that
|
||||
says what it is described as and where that comes from, and the box below this form lists any mistake in this
|
||||
field. A mistake never stops the form from saving and never breaks a page: unreadable YAML gives no page a
|
||||
per-page type, and an unknown type is skipped, so check that box after you save. Per-page types need structured
|
||||
data on, and do nothing on a page marked noindex.</p>
|
||||
|
||||
<h4>How a page is matched</h4>
|
||||
<ul>
|
||||
<li>A key is a path pattern starting with <code>/</code>: <code>/pricing</code> matches that page, and a
|
||||
<code>*</code> at the end matches every path that starts with what comes before it
|
||||
(<code>/blog/*</code>). It is a plain text prefix: <code>/blog/*</code> does not match <code>/blog</code>
|
||||
itself (give that page its own key), and <code>/blog*</code> also matches <code>/blogroll</code>;
|
||||
<code>/*</code> matches every page. An exact path wins over a prefix; among prefixes the longest wins. Only
|
||||
that one entry applies: an exact entry and a prefix entry are never combined. A <code>*</code> anywhere else
|
||||
is an ordinary character.</li>
|
||||
<li>A page is matched by its own URL path (its canonical URL, so a page whose canonical is overridden is matched
|
||||
by the override). A page whose canonical URL points to another site has no path on this site, so no
|
||||
pattern that starts with <code>/</code> matches it. A page in another language is matched by its own path
|
||||
too: <code>/pricing</code> does not reach <code>/es/pricing</code>, because what an entry says (questions,
|
||||
names, a breadcrumb parent) is written in one language. Give the translated page its own key
|
||||
(<code>/es/pricing</code>, or <code>/es/*</code> for all of them) with the text in its language; a key such
|
||||
as <code>/*</code> matches every language's pages. The page editor tells a translated page when the
|
||||
default language's entry does not reach it.</li>
|
||||
<li>The value is one type block (<code>type: …</code> plus that type's keys) or a list of blocks when one page
|
||||
is several things at once. Types and keys are case-sensitive, spelled exactly as below: <code>faqpage</code>
|
||||
or <code>Price</code> is not recognised.</li>
|
||||
<li>Quote numbers you mean as text (prices, postal codes): <code>price: "22.00"</code>. Unquoted,
|
||||
<code>22.00</code> becomes <code>22.0</code>.</li>
|
||||
<li>Any block may add <code>breadcrumb: { name: …, url: … }</code>: the page's breadcrumb trail then shows that
|
||||
parent between Home and the page. It needs both <code>name</code> and <code>url</code>; a path on the site is
|
||||
made a full URL. When several blocks give one, the first complete one is used. A block may hold only a
|
||||
<code>breadcrumb</code>, with no <code>type</code>.</li>
|
||||
</ul>
|
||||
|
||||
<h4>Page types: what the page itself is</h4>
|
||||
<p>These replace the <a href="#structured-data">Default page type</a> on the pages they match; a page has one, the
|
||||
first listed.</p>
|
||||
<table>
|
||||
<thead><tr><th>Type</th><th>Keys</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>Article</code>, <code>BlogPosting</code>, <code>NewsArticle</code></td>
|
||||
<td><code>headline</code> (default: the page title) · <code>description</code> (default: the page
|
||||
description) · <code>image</code> (a list of image URLs; a path on the site is made a full URL) ·
|
||||
<code>author</code> (a name) · <code>datePublished</code>, <code>dateModified</code>
|
||||
(<code>YYYY-MM-DD</code>; published as written, not checked). A page that knows its own author and dates
|
||||
(a blog entry) uses those instead. A page with neither a title nor a <code>headline</code> gets none of
|
||||
these.</td></tr>
|
||||
<tr><td><code>FAQPage</code></td>
|
||||
<td><code>faq</code>: a list of <code>{ q: question, a: answer }</code>. A pair missing <code>q</code> or
|
||||
<code>a</code> is left out; with no complete pair the page is still an <code>FAQPage</code>, with no
|
||||
questions, and the page editor and the box below the form say so.</td></tr>
|
||||
<tr><td><code>CollectionPage</code></td>
|
||||
<td><code>items</code>: a list of <code>{ name, url }</code>, published as the page's list (an
|
||||
<code>ItemList</code> that is the page's main entity). An item without <code>url</code> is left out; a
|
||||
path on the site is made a full URL. With no item that has a <code>url</code>, no list is published,
|
||||
and the page editor and the box below the form say so.</td></tr>
|
||||
<tr><td><code>WebPage</code>, <code>AboutPage</code>, <code>ContactPage</code>, <code>ItemPage</code>,
|
||||
<code>SearchResultsPage</code></td>
|
||||
<td>none: they only name what the page is. <code>WebPage</code> takes a page back to the plain type on a
|
||||
site whose default is <code>Article</code>. There is no <code>QAPage</code> or
|
||||
<code>ProfilePage</code>: Google requires each to name its main subject, which a type with no keys
|
||||
cannot do. Questions you write on the page are an <code>FAQPage</code>.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h4>Types that add something to the page</h4>
|
||||
<table>
|
||||
<thead><tr><th>Type</th><th>Keys</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>Product</code></td>
|
||||
<td><code>name</code> (default: the page title) · <code>description</code> (default: the page
|
||||
description) · <code>image</code> · <code>sku</code> · <code>price</code> (an offer is published only
|
||||
with a price) · <code>currency</code> (default <code>USD</code>) · <code>availability</code>
|
||||
(<code>InStock</code>, <code>OutOfStock</code>, <code>PreOrder</code>, … or a full schema.org URL; a word
|
||||
is put after <code>https://schema.org/</code>, so spell it as schema.org does). The organization, when
|
||||
named, is the brand. With neither a <code>name</code> nor a page title, no product is published.</td></tr>
|
||||
<tr><td><code>Service</code>, <code>ProfessionalService</code></td>
|
||||
<td><code>name</code> (default: the page title) · <code>description</code> (default: the page
|
||||
description) · <code>serviceType</code> · <code>areaServed</code> (a list) · <code>offers</code>: a
|
||||
list of <code>{ name, price, currency, unit }</code>; an offer without <code>price</code> is left out,
|
||||
<code>currency</code> defaults to <code>USD</code>, and with <code>unit</code> (for example
|
||||
<code>month</code>) the price is per that unit. The organization, when named, is the provider. With
|
||||
neither a <code>name</code> nor a page title, no service is published.</td></tr>
|
||||
<tr><td><code>LocalBusiness</code>, <code>CafeOrCoffeeShop</code></td>
|
||||
<td><code>name</code> (default: the site name) · <code>street</code> · <code>locality</code> ·
|
||||
<code>region</code> · <code>postalCode</code> · <code>country</code> · <code>telephone</code> ·
|
||||
<code>url</code> · <code>priceRange</code> · <code>latitude</code>, <code>longitude</code> ·
|
||||
<code>hours</code> (a list, for example <code>"Mo-Fr 08:00-17:00"</code>) · <code>image</code>. Or
|
||||
<code>locations</code>: a list of those, one business per location (the keys beside
|
||||
<code>locations</code> are then not used). <code>url</code> defaults to the page's address. The address is
|
||||
published only with a <code>street</code> or a <code>locality</code>, the map position only with both
|
||||
<code>latitude</code> and <code>longitude</code>. Even a block with nothing but its <code>type</code> publishes a
|
||||
business, named after the site. Only these two type names work.</td></tr>
|
||||
<tr><td><code>Person</code></td>
|
||||
<td><code>people</code>: a list of <code>{ name, jobTitle, image, sameAs }</code>
|
||||
(<code>sameAs</code>: a list of profile URLs). For one person you can put those keys in the block itself,
|
||||
without <code>people</code>. A person without a <code>name</code> is left out. The organization, when
|
||||
named, is where they work.</td></tr>
|
||||
<tr><td><code>ItemList</code></td>
|
||||
<td><code>items</code>: a list of <code>{ name, url }</code>, without changing what the page is. An item
|
||||
without <code>url</code> is left out; a path on the site is made a full URL. With none that has a
|
||||
<code>url</code>, nothing is published, and the box below the form says so.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<pre><code>/pricing: # one page, two types
|
||||
- type: FAQPage
|
||||
faq:
|
||||
- { q: "Why ranges?", a: "Scope drives cost." }
|
||||
- type: Service
|
||||
name: "Advisory Sprint"
|
||||
offers:
|
||||
- { name: "Sprint", price: "18000", currency: USD }
|
||||
/coffees: # a collection page
|
||||
type: CollectionPage
|
||||
items:
|
||||
- { name: "Ethiopia Guji", url: "/coffee-ethiopia-guji" }
|
||||
/coffee-ethiopia-guji: # a product, under its collection in the breadcrumb
|
||||
type: Product
|
||||
price: "22.00"
|
||||
currency: USD
|
||||
breadcrumb: { name: "Coffees", url: "/coffees" }
|
||||
/contact:
|
||||
type: ContactPage
|
||||
/team:
|
||||
type: Person
|
||||
people: [{ name: "Dana Whitlock", jobTitle: "Founder" }]</code></pre>
|
||||
<p>If a page shows an FAQ (a <code><details></code>/<code><summary></code> block) that is not declared
|
||||
here, the page editor's quality check points it out.</p>
|
||||
|
||||
<h3 id="sitemap-robots">Sitemap and robots.txt</h3>
|
||||
<p><code>/sitemap.xml</code> lists every published, indexable page with its language alternates, and
|
||||
<code>/robots.txt</code> announces it. Pages marked <em>Exclude from search engines (noindex)</em>, and pages
|
||||
whose canonical URL points elsewhere, are left out on purpose: a sitemap
|
||||
recommends pages for indexing. <strong>Paths crawlers should skip</strong> become <code>Disallow:</code> lines for
|
||||
every crawler; AI crawlers you allow get the same lines, and AI crawlers you refuse are already kept off the
|
||||
whole site. Write one path per line (or separate them with commas); a <code>/</code> is added in front when you
|
||||
leave it out, and the path is otherwise written as you typed it. Each line is a prefix, as in every
|
||||
<code>robots.txt</code>: <code>/drafts</code> also covers <code>/drafts/old</code> and <code>/drafts-2024</code>,
|
||||
while <code>/drafts/</code> covers only what is inside it. Crawlers that follow the robots.txt standard
|
||||
(RFC 9309) also read <code>*</code> as any characters and a final <code>$</code> as the end of the
|
||||
address.</p>
|
||||
<p id="robots-custom"><strong>Custom robots.txt</strong> replaces the <em>entire</em> generated file — the
|
||||
<code>Sitemap:</code> line and the AI-crawler rules included — with exactly what you type. It is for the rare site
|
||||
that needs rules this page cannot express; if you use it, re-add the <code>Sitemap:</code> line yourself.</p>
|
||||
|
||||
<h3 id="ai-crawlers">AI crawlers</h3>
|
||||
<p>Whether AI companies' crawlers may read the site. Refusing them never removes the site from ordinary web
|
||||
search: the rules name AI agents only (for example <code>Google-Extended</code>, never <code>Googlebot</code>).
|
||||
<code>inherit</code> follows the platform's default, and the settings page shows what that currently is.</p>
|
||||
<p>Under <em>Advanced</em> you can decide per class of crawler, because the three classes have opposite
|
||||
consequences:</p>
|
||||
<table>
|
||||
<tr><th>Class</th><th>What it does</th><th>If you refuse it</th></tr>
|
||||
<tr><td>Training</td><td>Collects text to train AI models.</td><td>Costs the site nothing visible.</td></tr>
|
||||
<tr><td>Answer engines</td><td>Fetches pages to answer questions (ChatGPT search, Perplexity…).</td>
|
||||
<td>The site stops appearing in those answers.</td></tr>
|
||||
<tr><td>Person-initiated</td><td>A visit someone asked an AI assistant to make.</td>
|
||||
<td>That visit fails.</td></tr>
|
||||
</table>
|
||||
<p>A class left on <code>inherit</code> follows the site's policy above it.</p>
|
||||
<p id="ai-agents">The crawlers the rules name, by class:</p>
|
||||
<table>
|
||||
<tr><th>Class</th><th>Crawlers</th></tr>
|
||||
<tr><td>Training</td><td><code>GPTBot</code>, <code>ClaudeBot</code>, <code>anthropic-ai</code>,
|
||||
<code>Claude-Web</code>, <code>Google-Extended</code>, <code>CCBot</code>, <code>Bytespider</code>,
|
||||
<code>Amazonbot</code>, <code>Applebot-Extended</code>, <code>Meta-ExternalAgent</code>,
|
||||
<code>FacebookBot</code>, <code>cohere-ai</code>, <code>Diffbot</code>, <code>Omgilibot</code>,
|
||||
<code>Timpibot</code></td></tr>
|
||||
<tr><td>Answer engines</td><td><code>OAI-SearchBot</code>, <code>Claude-SearchBot</code>,
|
||||
<code>PerplexityBot</code>, <code>YouBot</code></td></tr>
|
||||
<tr><td>Person-initiated</td><td><code>ChatGPT-User</code>, <code>Claude-User</code>,
|
||||
<code>Perplexity-User</code></td></tr>
|
||||
</table>
|
||||
<p>A crawler whose role is unclear is counted as training: that is what a site refusing AI crawlers most likely
|
||||
means. New crawlers appear faster than plugin releases, so the platform operator can add names (<em>Additional
|
||||
AI crawler names</em>: in the app console, open <em>Plugins</em> and press <em>Settings</em> on the
|
||||
Discoverability row; a restart applies it). Each line (or comma-separated
|
||||
entry) is one name, optionally with its class in front: <code>training=NewBot</code>, <code>retrieval=…</code>,
|
||||
<code>user=…</code> (the class may be written in any case). Spaces, colons and <code>=</code> signs are removed
|
||||
from the name. A name already listed, in any case, is ignored, so a built-in crawler cannot be moved to another
|
||||
class. A name without a class follows each site's overall AI policy (or, on a site whose three classes all come out
|
||||
the same, goes with them); so does one with a misspelt class, which is also logged as a warning.</p>
|
||||
|
||||
<h3 id="geo">AI answer engines (GEO)</h3>
|
||||
<p>Opt-in extras for AI assistants: <code>/llms.txt</code> (a compact index of the site, headed by your
|
||||
<strong>site summary</strong>), <strong>speakable</strong> hints (the CSS selectors of the parts of a page worth
|
||||
reading aloud or quoting) and a <code>SearchAction</code> from the <strong>site search URL</strong>. The last two
|
||||
are structured data, so they also need structured data on.</p>
|
||||
<p>Speakable parts: one CSS selector per line (or separate them with commas). Left blank, they are
|
||||
<code>h1</code> and <code>main</code>, the default.</p>
|
||||
<p>The site search URL is the address of your results page, as a path or full URL (a value starting with
|
||||
<code>http</code> is used as it is; anything else is a path on this site). Put <code>{query}</code> (or
|
||||
<code>{search_term_string}</code>) where the search words go (<code>/search?q={query}</code>); without either,
|
||||
<code>?q=</code> is appended, or <code>&q=</code> when the address already has a <code>?</code>. Blank
|
||||
publishes no search action.</p>
|
||||
<p><em>Honest note:</em> <code>llms.txt</code> is a community proposal, not a standard. No major engine documents
|
||||
reading it, and Google states that no AI-specific file is needed to appear in its AI features. It is cheap and
|
||||
harmless; treat it as an optional extra.</p>
|
||||
|
||||
<h3 id="software">Product on the homepage</h3>
|
||||
<p>For a site that presents a software product: a <code>SoftwareApplication</code> on the homepage only (and on
|
||||
the home page of each other language, such as <code>/es</code>), published by the organization. It needs
|
||||
structured data on. A blank name uses the organization's (or the site's), a blank description the homepage's,
|
||||
a blank URL the homepage; a price of <code>0</code> means free, and a blank price publishes no offer. A blank
|
||||
operating system means <code>Web</code> and a blank currency <code>USD</code>, the defaults; neither is checked,
|
||||
so write them as schema.org expects (a currency as its three-letter code). The license, product and screenshot
|
||||
URLs are published exactly as you write them: use full URLs (<code>https://…</code>), because a path such as
|
||||
<code>/license</code> stays a path, which search engines do not accept.</p>
|
||||
|
||||
<h3 id="indexnow">Notify search engines of changes (IndexNow)</h3>
|
||||
<p>When a page is published, changed or removed, the site tells the engines that use IndexNow — Bing, Yandex,
|
||||
Seznam, Naver and Yep. <strong>Google does not use IndexNow.</strong> It needs two switches: the platform
|
||||
operator's (this server then makes outbound requests) and this site's. The settings page tells you when the
|
||||
platform's is off.</p>
|
||||
<p>The <strong>key</strong> is any random string of 8 to 128 letters, digits or dashes — the protocol's rule. It
|
||||
is published at <code>/indexnow-key.txt</code> so the engines can check the site is yours. Nothing is sent
|
||||
until a key is set.</p>
|
||||
<p>IndexNow also needs the site's own address: a site with neither a base URL nor a host name (such as the
|
||||
platform's catch-all default site) never sends anything, and nothing warns about it.</p>
|
||||
<p id="indexnow-limits"><strong>For the platform operator.</strong> Besides the switch, this plugin's platform
|
||||
settings (app console, <em>Plugins</em>, <em>Settings</em> on the Discoverability row) hold the endpoint and four
|
||||
limits. The form accepts only the ranges below; a value written by hand in the settings file
|
||||
(<code>external/plugin-settings/discoverability.yml</code>) or in <code>application.yml</code> is not
|
||||
range-checked, so keep to them. A restart applies any change.</p>
|
||||
<table>
|
||||
<tr><th>Setting</th><th>Default</th><th>Range</th><th>What it does</th></tr>
|
||||
<tr><td>Seconds to gather changes</td><td>60</td><td>5–3600</td><td>Changes are collected for this long, then
|
||||
each site's are sent in one submission. Set by hand, a value below 5 counts as 5 and one above 3600 as 3600.</td></tr>
|
||||
<tr><td>Maximum URLs per submission</td><td>1000</td><td>1–10000</td><td>The rest of a batch is not sent (a
|
||||
warning is logged); those pages are still crawled the ordinary way. Set by hand, a value below 1 counts as
|
||||
1.</td></tr>
|
||||
<tr><td>Maximum URLs queued per site</td><td>5000</td><td>1–100000</td><td>Once a site has this many waiting,
|
||||
further changes are dropped until the next submission (a warning is logged). Set by hand, a value below 1
|
||||
counts as 1.</td></tr>
|
||||
<tr><td>Submission timeout (seconds)</td><td>10</td><td>1–120</td><td>How long to wait for the endpoint before a
|
||||
submission is given up (it is not retried). Set by hand, a value below 1 counts as 1.</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>Verify it</h2>
|
||||
<ul>
|
||||
<li>View any public page's source — look for <code><script type="application/ld+json"></code>.</li>
|
||||
<li>Open <code>/sitemap.xml</code> and <code>/llms.txt</code> (the latter only when GEO is enabled).</li>
|
||||
<li>Open <code>/robots.txt</code> and read it: check the AI-crawler group matches the policy you chose, and
|
||||
that any paths you excluded appear as <code>Disallow:</code> lines under <code>User-agent: *</code> and in
|
||||
every AI group you allow (a refused AI group is a single <code>Disallow: /</code>, which already covers
|
||||
them).</li>
|
||||
<li>Paste a page URL into Google's Rich Results Test to see the structured data recognized.</li>
|
||||
</ul>
|
||||
|
||||
<p class="muted">Editing these settings affects your live site immediately (no restart). Only this site is
|
||||
affected — every site configures its own discoverability. A few things are the platform operator's, apply to
|
||||
every site and change only on a restart: the default AI-crawler policy that <code>inherit</code> follows, the
|
||||
list of extra AI crawler names, and whether IndexNow is allowed at all.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
<!-- Admin status fragment — the filename `admin` makes the host render it below this plugin's per-tenant
|
||||
settings form. Bare fragment; binding in admin.th.xml. -->
|
||||
<div class="card mt-3">
|
||||
<div class="card-header"><h3 class="card-title" id="da-title">Discoverability status</h3></div>
|
||||
<div class="card-body">
|
||||
<div class="datagrid">
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="da-l-jsonld">Structured data</div>
|
||||
<div class="datagrid-content"><span id="da-jsonld">on</span> (<span id="da-type">WebPage</span>)</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="da-l-sitemap">Sitemap</div>
|
||||
<div class="datagrid-content"><a id="da-sitemap" href="/sitemap.xml" target="_blank" rel="noopener">/sitemap.xml</a></div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="da-l-geo">GEO · llms.txt</div>
|
||||
<div class="datagrid-content"><span id="da-geo">off</span></div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="da-l-pages">Pages in sitemap</div>
|
||||
<div class="datagrid-content" id="da-pages">0</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3" id="da-schema">
|
||||
<div class="fw-semibold" id="da-schema-title">Per-page types check</div>
|
||||
<div class="text-success small" id="da-schema-ok">No problems found.</div>
|
||||
<ul class="small text-warning mb-0" id="da-schema-list"><li class="da-schema-item">problem</li></ul>
|
||||
</div>
|
||||
<p class="text-secondary small mt-2 mb-0" id="da-note">
|
||||
These surfaces enrich the head/response layer; the kernel already emits canonical, hreflang and robots.</p>
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<a id="da-help" href="/__plugin/discoverability/static/discoverability-help.html" target="_blank" rel="noopener">
|
||||
<i class="fa-solid fa-circle-question me-1"></i><span id="da-help-label">Discoverability help & reference</span></a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Admin fragment logic. Values from ${@discoverabilityAdminModel...(tenantSiteId)}; on/off ternaries keep the
|
||||
condition in ${} and each branch a standalone #{} (pitfall #12). -->
|
||||
<thlogic>
|
||||
<attr sel="#da-title" th:text="#{discover.admin.title}"/>
|
||||
<attr sel="#da-l-jsonld" th:text="#{discover.admin.jsonld}"/>
|
||||
<attr sel="#da-jsonld" th:text="${@discoverabilityAdminModel.jsonldEnabled(tenantSiteId)} ? #{discover.on} : #{discover.off}"/>
|
||||
<attr sel="#da-type" th:text="${@discoverabilityAdminModel.jsonldType(tenantSiteId)}"/>
|
||||
<attr sel="#da-l-sitemap" th:text="#{discover.admin.sitemap}"/>
|
||||
<attr sel="#da-sitemap" th:text="${@discoverabilityAdminModel.sitemapEnabled(tenantSiteId)} ? '/sitemap.xml' : #{discover.off}"/>
|
||||
<attr sel="#da-l-geo" th:text="#{discover.admin.geo}"/>
|
||||
<attr sel="#da-geo" th:text="${@discoverabilityAdminModel.geoEnabled(tenantSiteId)} ? #{discover.on} : #{discover.off}"/>
|
||||
<attr sel="#da-l-pages" th:text="#{discover.admin.pages}"/>
|
||||
<attr sel="#da-pages" th:text="${@discoverabilityAdminModel.pageCount(tenantSiteId)}"/>
|
||||
<attr sel="#da-note" th:text="#{discover.admin.note}"/>
|
||||
<!-- Per-page types (content.schema) problems, one per line; never a page error, so they are shown here. -->
|
||||
<attr sel="#da-schema" th:with="problems=${@discoverabilityAdminModel.schemaProblems(tenantSiteId)}"/>
|
||||
<attr sel="#da-schema-title" th:text="#{discover.schema.title}"/>
|
||||
<attr sel="#da-schema-ok" th:if="${problems.isEmpty()}" th:text="#{discover.schema.ok}"/>
|
||||
<attr sel="#da-schema-list" th:unless="${problems.isEmpty()}"/>
|
||||
<attr sel="#da-schema-list//.da-schema-item" th:each="problem : ${problems}" th:text="${problem}"/>
|
||||
<attr sel="#da-help-label" th:text="#{discover.admin.help}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,18 @@
|
||||
<!-- Tenant dashboard card fragment — resolved as __plugin__/discoverability/dashboard. Bare fragment
|
||||
(no <html>/<body>); all binding lives in the paired dashboard.th.xml. -->
|
||||
<div class="card">
|
||||
<div class="card-status-start bg-primary"></div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="bg-primary-lt avatar"><i class="fa-solid fa-magnifying-glass-chart"></i></span>
|
||||
<div class="ms-3">
|
||||
<div class="fw-bold" id="dc-title">Discoverability</div>
|
||||
<div class="text-secondary small">
|
||||
<span id="dc-pages">0</span> <span id="dc-pages-lbl">pages</span>
|
||||
· JSON-LD <span id="dc-jsonld">on</span>
|
||||
· GEO <span id="dc-geo">off</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Dashboard card logic. Each value is a simple binding; the on/off ternaries keep the condition in ${} and
|
||||
each branch a standalone #{} message expression (pitfall #12 — never nest #{} inside ${}). -->
|
||||
<thlogic>
|
||||
<attr sel="#dc-title" th:text="#{discover.card.title}"/>
|
||||
<attr sel="#dc-pages" th:text="${@discoverabilityAdminModel.pageCount(tenantSiteId)}"/>
|
||||
<attr sel="#dc-pages-lbl" th:text="#{discover.card.pages}"/>
|
||||
<attr sel="#dc-jsonld" th:text="${@discoverabilityAdminModel.jsonldEnabled(tenantSiteId)} ? #{discover.on} : #{discover.off}"/>
|
||||
<attr sel="#dc-geo" th:text="${@discoverabilityAdminModel.geoEnabled(tenantSiteId)} ? #{discover.on} : #{discover.off}"/>
|
||||
</thlogic>
|
||||
Reference in new issue
Block a user