omnirank 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,692 @@
1
+ """Next.js App Router adapter: the page's `export const metadata` object, and a
2
+ JSON-LD `<script>` in the page component.
3
+
4
+ The metadata object is parsed by a deliberately small recogniser, not a
5
+ JavaScript parser: an object literal whose keys are identifiers or strings and
6
+ whose values are strings, numbers, booleans, null, arrays and nested objects of
7
+ the same. Anything else -- a spread, a variable, a function call, a template
8
+ literal with `${}`, a computed or shorthand key -- refuses the whole edit,
9
+ because what the page renders can no longer be read off the source.
10
+
11
+ `generateMetadata` computes metadata at request time; this adapter never
12
+ rewrites a function body and refuses with that reason.
13
+
14
+ Next.js merges metadata SHALLOWLY down the layout tree: a page that declares
15
+ `openGraph` (or `alternates`, `robots`, `twitter`) replaces the layout's whole
16
+ object, silently dropping fields the layout set. So adding one of those keys
17
+ to a page is refused when an ancestor layout declares it (or computes its
18
+ metadata, so it cannot be ruled out). A layout `title.template` would wrap a
19
+ plain page title; when one exists (or cannot be ruled out) the title is
20
+ written as `{ absolute: "..." }`, which renders exactly the requested text.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import re
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+
29
+ from ..fixes.base import newline_style
30
+ from .base import (
31
+ Adapter,
32
+ Context,
33
+ Edit,
34
+ Refused,
35
+ check_mode,
36
+ compact_jsonld,
37
+ js_string,
38
+ jsonld_match,
39
+ jsonld_type,
40
+ line_indent,
41
+ line_start,
42
+ parse_js_string,
43
+ )
44
+ from .jsx import JsxTag, Lexed, Unreadable, lex
45
+
46
+ LAYOUT_FILES = ("layout.tsx", "layout.jsx", "layout.ts", "layout.js")
47
+ MERGE_HAZARD = ("alternates", "openGraph", "robots", "twitter")
48
+
49
+ _GENERATE = re.compile(
50
+ r"\bexport\s+(?:async\s+)?function\s+generateMetadata\b"
51
+ r"|\bexport\s+(?:const|let|var)\s+generateMetadata\b")
52
+ _REEXPORT = re.compile(r"\bexport\s*\{[^}]*\b(?:metadata|generateMetadata)\b[^}]*\}"
53
+ r"|\bexport\s*\*")
54
+ _PROLOGUE_GAP = re.compile(r"(?:[\s\ufeff;]|//[^\n]*(?:\n|$)|/\*.*?\*/)*", re.DOTALL)
55
+ _DIRECTIVE = re.compile(r"'[^'\\\n]*'|\"[^\"\\\n]*\"")
56
+ _TEXT_EXPORT = re.compile(r"\bexport\s+const\s+metadata\b")
57
+ _METADATA_WORD = re.compile(r"(?<![\w$])metadata(?![\w$])")
58
+
59
+
60
+ def is_client_component(text: str) -> bool:
61
+ """True when the directive prologue (string-literal statements before the
62
+ first other statement, e.g. 'use strict' then 'use client') has 'use client'."""
63
+ i = 0
64
+ while True:
65
+ i = _PROLOGUE_GAP.match(text, i).end()
66
+ directive = _DIRECTIVE.match(text, i)
67
+ if directive is None:
68
+ return False
69
+ if directive.group(0)[1:-1] == "use client":
70
+ return True
71
+ i = directive.end()
72
+ _IDENT = re.compile(r"[A-Za-z_$][\w$]*")
73
+ _NUMBER = re.compile(r"-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
74
+
75
+ OG_KEYS = {"og:title": "title", "og:description": "description", "og:url": "url",
76
+ "og:type": "type", "og:site_name": "siteName", "og:locale": "locale",
77
+ "og:image": "images"}
78
+
79
+
80
+ class Dynamic(Exception):
81
+ """The source is not a simple object literal."""
82
+
83
+
84
+ # --- a minimal object-literal recogniser -------------------------------------------------
85
+
86
+
87
+ @dataclass
88
+ class Node:
89
+ start: int
90
+ end: int
91
+
92
+
93
+ @dataclass
94
+ class Str(Node):
95
+ value: str
96
+ quote: str
97
+
98
+
99
+ @dataclass
100
+ class Prop:
101
+ key: str
102
+ start: int
103
+ end: int
104
+ value: Node
105
+
106
+
107
+ @dataclass
108
+ class Obj(Node):
109
+ props: list[Prop] = field(default_factory=list)
110
+ trailing_comma: int | None = None # index of a comma after the last prop
111
+
112
+ def get(self, key: str) -> Prop | None:
113
+ found = [p for p in self.props if p.key == key]
114
+ if len(found) > 1:
115
+ raise Refused(f"the metadata object declares {key!r} twice")
116
+ return found[0] if found else None
117
+
118
+
119
+ @dataclass
120
+ class Other(Node):
121
+ pass
122
+
123
+
124
+ class _Parser:
125
+ def __init__(self, text: str, pos: int):
126
+ self.text = text
127
+ self.pos = pos
128
+
129
+ def skip(self) -> None:
130
+ text = self.text
131
+ while self.pos < len(text):
132
+ ch = text[self.pos]
133
+ if ch in " \t\r\n":
134
+ self.pos += 1
135
+ elif text.startswith("//", self.pos):
136
+ end = text.find("\n", self.pos)
137
+ self.pos = len(text) if end == -1 else end
138
+ elif text.startswith("/*", self.pos):
139
+ end = text.find("*/", self.pos + 2)
140
+ if end == -1:
141
+ raise Dynamic("an unterminated comment")
142
+ self.pos = end + 2
143
+ else:
144
+ return
145
+
146
+ def peek(self) -> str:
147
+ self.skip()
148
+ return self.text[self.pos:self.pos + 1]
149
+
150
+ def string(self) -> Str:
151
+ quote = self.text[self.pos]
152
+ i = self.pos + 1
153
+ while i < len(self.text):
154
+ ch = self.text[i]
155
+ if ch == "\\":
156
+ i += 2
157
+ continue
158
+ if ch == quote:
159
+ raw = self.text[self.pos:i + 1]
160
+ value = parse_js_string(raw)
161
+ if value is None:
162
+ raise Dynamic("a template literal with ${...} or a malformed string")
163
+ node = Str(self.pos, i + 1, value, quote)
164
+ self.pos = i + 1
165
+ return node
166
+ if ch == "\n" and quote != "`":
167
+ break
168
+ i += 1
169
+ raise Dynamic("an unterminated string")
170
+
171
+ def value(self) -> Node:
172
+ ch = self.peek()
173
+ start = self.pos
174
+ if ch == "{":
175
+ return self.obj()
176
+ if ch == "[":
177
+ self.pos += 1
178
+ while self.peek() != "]":
179
+ if self.peek() == "":
180
+ raise Dynamic("an unterminated array")
181
+ self.value()
182
+ if self.peek() == ",":
183
+ self.pos += 1
184
+ elif self.peek() != "]":
185
+ raise Dynamic("an array that is not a plain list of literals")
186
+ self.pos += 1
187
+ return Other(start, self.pos)
188
+ if ch in "'\"`":
189
+ return self.string()
190
+ number = _NUMBER.match(self.text, self.pos)
191
+ if number:
192
+ self.pos = number.end()
193
+ return Other(start, self.pos)
194
+ ident = _IDENT.match(self.text, self.pos)
195
+ if ident and ident.group(0) in ("true", "false", "null"):
196
+ self.pos = ident.end()
197
+ return Other(start, self.pos)
198
+ found = ident.group(0) if ident else self.text[self.pos:self.pos + 12]
199
+ raise Dynamic(f"a computed value ({found.strip() or 'end of file'}...)")
200
+
201
+ def obj(self) -> Obj:
202
+ start = self.pos
203
+ self.pos += 1
204
+ node = Obj(start, start)
205
+ while True:
206
+ ch = self.peek()
207
+ if ch == "}":
208
+ self.pos += 1
209
+ node.end = self.pos
210
+ return node
211
+ if ch == "":
212
+ raise Dynamic("an unterminated object")
213
+ if self.text.startswith("...", self.pos):
214
+ raise Dynamic("a spread (...)")
215
+ prop_start = self.pos
216
+ if ch in "'\"":
217
+ key = self.string().value
218
+ else:
219
+ ident = _IDENT.match(self.text, self.pos)
220
+ if ident is None:
221
+ raise Dynamic("a computed key")
222
+ key = ident.group(0)
223
+ self.pos = ident.end()
224
+ if self.peek() != ":":
225
+ raise Dynamic(f"a shorthand or method property ({key})")
226
+ self.pos += 1
227
+ value = self.value()
228
+ node.props.append(Prop(key, prop_start, value.end, value))
229
+ node.trailing_comma = None
230
+ if self.peek() == ",":
231
+ node.trailing_comma = self.pos
232
+ self.pos += 1
233
+ elif self.peek() != "}":
234
+ raise Dynamic(f"an expression after {key!r}")
235
+
236
+
237
+ def parse_object(text: str, start: int) -> Obj:
238
+ parser = _Parser(text, start)
239
+ if parser.peek() != "{":
240
+ raise Dynamic("metadata is not an object literal")
241
+ return parser.obj()
242
+
243
+
244
+ # --- the metadata export ------------------------------------------------------------------
245
+
246
+
247
+ def lexed(text: str) -> Lexed:
248
+ try:
249
+ return lex(text)
250
+ except Unreadable as exc:
251
+ raise Refused(f"the file cannot be read reliably ({exc}); OmniRank refuses "
252
+ "rather than guess where its code is") from exc
253
+
254
+
255
+ def _top_exports(lx: Lexed) -> list[list]:
256
+ """For each module-level `export`, the tokens up to the next `;`/`=`/`(`/`{`
257
+ at that level (enough to name what it exports)."""
258
+ out, tokens = [], lx.tokens
259
+ for index, token in enumerate(tokens):
260
+ if token.kind != "ident" or token.text != "export" or token.depth != 0:
261
+ continue
262
+ head = []
263
+ for nxt in tokens[index + 1:index + 8]:
264
+ head.append(nxt)
265
+ if nxt.kind == "punct" and nxt.text in ";=(":
266
+ break
267
+ out.append([token, *head])
268
+ return out
269
+
270
+
271
+ def _generate_refusal(text: str) -> str | None:
272
+ try:
273
+ lx = lex(text)
274
+ except Unreadable as exc:
275
+ return f"refused: the file cannot be read reliably ({exc})"
276
+ for export in _top_exports(lx):
277
+ words = [t.text for t in export[1:]]
278
+ if "generateMetadata" in words[:4] and words[:1] != ["{"]:
279
+ return ("refused: this file exports generateMetadata, which computes the "
280
+ "metadata at request time; OmniRank never rewrites a function body. "
281
+ "Edit the object it returns by hand")
282
+ if words[:1] == ["*"]:
283
+ return ("refused: the file re-exports `*` from another module, which may "
284
+ "include metadata; the object that renders cannot be proven to be "
285
+ "in this file")
286
+ if words[:1] == ["{"]:
287
+ close = next((i for i, t in enumerate(lx.tokens)
288
+ if t.start > export[1].start and t.text == "}"), None)
289
+ names = {t.text for t in lx.tokens[lx.tokens.index(export[1]):close]}
290
+ if names & {"metadata", "generateMetadata"}:
291
+ return ("refused: metadata is re-exported from another module; the "
292
+ "object that renders is not in this file")
293
+ return None
294
+
295
+
296
+ def find_metadata(text: str) -> Obj | None:
297
+ """The page's metadata object literal, or None when it has none.
298
+
299
+ Exports are found with the lexer, so an `export const metadata` inside a
300
+ string, a template literal or a comment is never seen.
301
+ """
302
+ lx = lexed(text)
303
+ found = []
304
+ for export in _top_exports(lx):
305
+ words = [t.text for t in export[1:]]
306
+ if "metadata" not in words[:3]:
307
+ continue
308
+ if words[:2] != ["const", "metadata"]:
309
+ raise Refused("metadata is exported in a form this adapter does not "
310
+ "recognise (expected `export const metadata = { ... }`)")
311
+ found.append(export)
312
+ if len(found) > 1:
313
+ raise Refused("the file declares `export const metadata` more than once")
314
+ if not found:
315
+ return None
316
+ # Belt and braces: the raw text must agree with the lexer.
317
+ textual = list(_TEXT_EXPORT.finditer(text))
318
+ if len(textual) != 1 or textual[0].start() != found[0][0].start:
319
+ raise Refused(f"the text holds {len(textual)} `export const metadata` "
320
+ "occurrence(s) and the code scan disagrees about which one is "
321
+ "real; refusing rather than guess")
322
+ name = found[0][2]
323
+ match = re.compile(r"\s*(?::\s*[A-Za-z_$][\w$.]*\s*)?=\s*").match(text, name.end)
324
+ if match is None:
325
+ raise Refused("the metadata export has a type annotation or initialiser this "
326
+ "adapter does not recognise")
327
+ try:
328
+ node = parse_object(text, match.end())
329
+ except Dynamic as exc:
330
+ raise Refused(f"the metadata export is not a simple object literal ({exc}); "
331
+ "OmniRank only edits literal values it can read") from exc
332
+ tail = text[node.end:]
333
+ if not re.match(r"[ \t]*(?:satisfies\s+[A-Za-z_$][\w$.]*\s*)?(?:;|\r?\n|$)", tail):
334
+ raise Refused("the metadata object is followed by an expression OmniRank "
335
+ "does not recognise")
336
+ return node
337
+
338
+
339
+ def _ancestor_layouts(ctx: Context) -> list[tuple[str, str]]:
340
+ """(rel path, text) of every layout from the page's directory up to app/."""
341
+ out = []
342
+ page_dir = ctx.path.parent
343
+ app_dirs = [ctx.root / "app", ctx.root / "src" / "app"]
344
+ app_root = next((d for d in app_dirs if page_dir == d or d in page_dir.parents), None)
345
+ if app_root is None:
346
+ raise Refused(f"{ctx.rel} is not under app/ or src/app/")
347
+ current = page_dir
348
+ while True:
349
+ for name in LAYOUT_FILES:
350
+ path = current / name
351
+ if path.is_file():
352
+ try:
353
+ out.append((path.relative_to(ctx.root).as_posix(),
354
+ path.read_text(encoding="utf-8")))
355
+ except (OSError, UnicodeDecodeError) as exc:
356
+ raise Refused(f"cannot read layout {path.name} ({exc})") from exc
357
+ if current == app_root:
358
+ return out
359
+ current = current.parent
360
+
361
+
362
+ def _layout_declares(layouts, key: str) -> str | None:
363
+ """The first layout that sets `key` (or might, via generateMetadata)."""
364
+ for rel, text in layouts:
365
+ if _GENERATE.search(text) or _REEXPORT.search(text):
366
+ return f"{rel} (computes its metadata, so {key} cannot be ruled out)"
367
+ if re.search(rf"\b{re.escape(key)}\s*:", text):
368
+ return rel
369
+ return None
370
+
371
+
372
+ def _render_value(value) -> str:
373
+ if isinstance(value, str):
374
+ return js_string(value)
375
+ if isinstance(value, dict):
376
+ inner = ", ".join(f"{k}: {_render_value(v)}" for k, v in value.items())
377
+ return "{ " + inner + " }"
378
+ raise TypeError(value)
379
+
380
+
381
+ def _insert_prop(text: str, obj: Obj, key: str, value) -> str:
382
+ """Add `key: value` as the object's last property, matching its layout."""
383
+ rendered = f"{key}: {_render_value(value)}"
384
+ eol = newline_style(text)
385
+ if not obj.props:
386
+ inner = text[obj.start + 1:obj.end - 1]
387
+ if "\n" in inner:
388
+ indent = line_indent(text, obj.start) + " "
389
+ return text[:obj.start + 1] + f"{eol}{indent}{rendered},{eol}" + \
390
+ line_indent(text, obj.start) + text[obj.end - 1:]
391
+ return text[:obj.start + 1] + f" {rendered} " + text[obj.end - 1:]
392
+ last = obj.props[-1]
393
+ multiline = "\n" in text[obj.start:last.start]
394
+ if multiline:
395
+ indent = line_indent(text, last.start)
396
+ if obj.trailing_comma is not None:
397
+ at = obj.trailing_comma + 1
398
+ return text[:at] + f"{eol}{indent}{rendered}," + text[at:]
399
+ return text[:last.end] + f",{eol}{indent}{rendered}" + text[last.end:]
400
+ if obj.trailing_comma is not None:
401
+ at = obj.trailing_comma + 1
402
+ return text[:at] + f" {rendered}," + text[at:]
403
+ return text[:last.end] + f", {rendered}" + text[last.end:]
404
+
405
+
406
+ def _set_path(text: str, obj: Obj, path: list[str], value: str,
407
+ hazard: str | None, edit: Edit | None = None) -> str:
408
+ """Set the string at `path` inside `obj`, creating objects on the way."""
409
+ node = obj
410
+ what = f"metadata.{'.'.join(path)}"
411
+ for depth, key in enumerate(path):
412
+ prop = node.get(key)
413
+ last = depth == len(path) - 1
414
+ if prop is None:
415
+ if edit is not None:
416
+ check_mode(edit, False, what)
417
+ if depth == 0 and hazard is not None:
418
+ raise Refused(f"adding `{key}` to this page would replace the whole "
419
+ f"`{key}` object set by {hazard} (Next.js merges "
420
+ "metadata shallowly); add it there or by hand")
421
+ nested: object = value
422
+ for inner in reversed(path[depth + 1:]):
423
+ nested = {inner: nested}
424
+ return _insert_prop(text, node, key, nested)
425
+ if last:
426
+ if edit is not None:
427
+ check_mode(edit, True, what)
428
+ if not isinstance(prop.value, Str):
429
+ raise Refused(f"metadata.{'.'.join(path)} is not a plain string")
430
+ if prop.value.value == value:
431
+ return text
432
+ quote = prop.value.quote if prop.value.quote in "'\"" else '"'
433
+ return text[:prop.value.start] + js_string(value, quote) + text[prop.value.end:]
434
+ if not isinstance(prop.value, Obj):
435
+ raise Refused(f"metadata.{'.'.join(path[:depth + 1])} is not a plain object")
436
+ node = prop.value
437
+ return text
438
+
439
+
440
+ def _edit_title(text: str, obj: Obj, value: str, layouts) -> str:
441
+ template = None
442
+ for rel, layout in layouts:
443
+ if _GENERATE.search(layout) or re.search(r"\btemplate\s*:", layout):
444
+ template = rel
445
+ break
446
+ prop = obj.get("title")
447
+ if template is None:
448
+ if prop is not None and isinstance(prop.value, Obj):
449
+ keys = [p.key for p in prop.value.props]
450
+ if keys == ["absolute"]:
451
+ return _set_path(text, obj, ["title", "absolute"], value, None)
452
+ raise Refused("metadata.title is an object with "
453
+ f"{', '.join(keys) or 'no keys'}; only a string or "
454
+ "{ absolute } title is edited")
455
+ return _set_path(text, obj, ["title"], value, None)
456
+ # A layout may wrap a plain title in its template: write { absolute }.
457
+ if prop is None:
458
+ return _insert_prop(text, obj, "title", {"absolute": value})
459
+ if isinstance(prop.value, Str):
460
+ return text[:prop.value.start] + _render_value({"absolute": value}) + \
461
+ text[prop.value.end:]
462
+ if isinstance(prop.value, Obj) and [p.key for p in prop.value.props] == ["absolute"]:
463
+ return _set_path(text, obj, ["title", "absolute"], value, None)
464
+ raise Refused("metadata.title is an object this adapter does not edit")
465
+
466
+
467
+ def _insert_metadata(text: str, edit_path: list[str], value) -> str:
468
+ """A page with no metadata export: add one before `export default`."""
469
+ mentions = len(_METADATA_WORD.findall(text))
470
+ if mentions:
471
+ raise Refused(f"the page has no recognised metadata export but mentions "
472
+ f"`metadata` {mentions} time(s) (in a comment, string or another "
473
+ "declaration); adding an export could duplicate or shadow it")
474
+ tokens = lexed(text).tokens
475
+ defaults = [t for i, t in enumerate(tokens[:-1])
476
+ if t.depth == 0 and t.text == "export" and tokens[i + 1].text == "default"
477
+ and not text[line_start(text, t.start):t.start].strip()]
478
+ if len(defaults) != 1:
479
+ raise Refused("the page has no metadata export and no single `export default` "
480
+ "starting a line to place one before")
481
+ nested: object = value
482
+ for key in reversed(edit_path[1:]):
483
+ nested = {key: nested}
484
+ eol = newline_style(text)
485
+ block = (f"export const metadata = {{{eol} {edit_path[0]}: {_render_value(nested)},"
486
+ f"{eol}}};{eol}{eol}")
487
+ at = line_start(text, defaults[0].start)
488
+ return text[:at] + block + text[at:]
489
+
490
+
491
+ # --- JSON-LD in the page component -----------------------------------------------------
492
+
493
+
494
+ @dataclass
495
+ class _Script:
496
+ start: int
497
+ end: int
498
+ literal: Str | None # the __html string literal, when it is one
499
+
500
+
501
+ def _attr_string(tag: JsxTag, name: str) -> str | None:
502
+ """A JSX attribute's value when it is a plain string ("x" or {"x"})."""
503
+ attr = tag.attr(name)
504
+ if attr is None or not attr.raw:
505
+ return None
506
+ raw = attr.raw[1:-1].strip() if attr.raw.startswith("{") else attr.raw
507
+ return parse_js_string(raw)
508
+
509
+
510
+ def _jsx_ld_scripts(text: str, lx: Lexed) -> list[_Script]:
511
+ """Every JSON-LD <script>/<Script>; refuses when the file mentions
512
+ `application/ld+json` anywhere this could not account for."""
513
+ out = []
514
+ for tag in lx.tags:
515
+ if tag.name not in ("script", "Script"):
516
+ continue
517
+ if _attr_string(tag, "type") != "application/ld+json":
518
+ continue
519
+ literal = None
520
+ html = tag.attr("dangerouslySetInnerHTML")
521
+ if tag.self_closing and html is not None:
522
+ inner = re.fullmatch(r"\{\{\s*__html\s*:\s*(.*?)\s*,?\s*\}\}", html.raw,
523
+ re.DOTALL)
524
+ if inner is not None:
525
+ at = html.start + html.raw.index(inner.group(1))
526
+ parser = _Parser(text, at)
527
+ try:
528
+ node = parser.string() if text[at:at + 1] in "'\"`" else None
529
+ except Dynamic:
530
+ node = None
531
+ if node is not None and text[node.start:node.end] == inner.group(1):
532
+ literal = node
533
+ out.append(_Script(tag.start, tag.end, literal))
534
+ mentions = text.count("application/ld+json")
535
+ if mentions != len(out):
536
+ raise Refused(f"the file mentions application/ld+json {mentions} time(s) but "
537
+ f"{len(out)} JSON-LD <script> element(s) were recognised; refusing "
538
+ "rather than risk adding a duplicate")
539
+ return out
540
+
541
+
542
+ def _place_script(text: str, lx: Lexed) -> tuple[int, str]:
543
+ """(insert index, indent) for a new first child of the JSX root that the
544
+ default-exported function component returns at its own body level."""
545
+ tokens = lx.tokens
546
+ starts = [i for i, t in enumerate(tokens)
547
+ if t.depth == 0 and t.text == "export" and i + 2 < len(tokens)
548
+ and tokens[i + 1].text == "default"]
549
+ shape = ("the page does not have one `export default function` component to place a "
550
+ "JSON-LD <script> in")
551
+ if len(starts) != 1:
552
+ raise Refused(shape)
553
+ i = starts[0] + 2
554
+ if tokens[i].text == "async":
555
+ i += 1
556
+ if tokens[i].text != "function":
557
+ raise Refused(shape)
558
+ i += 1
559
+ if tokens[i].kind == "ident":
560
+ i += 1
561
+ if tokens[i].text != "(":
562
+ raise Refused(shape)
563
+ level = 0
564
+ while i < len(tokens):
565
+ if tokens[i].text == "(":
566
+ level += 1
567
+ elif tokens[i].text == ")":
568
+ level -= 1
569
+ if level == 0:
570
+ break
571
+ i += 1
572
+ body = next((k for k in range(i + 1, len(tokens))
573
+ if tokens[k].text == "{" and tokens[k].depth == 0), None)
574
+ if body is None:
575
+ raise Refused(shape)
576
+ close = next((k for k in range(body + 1, len(tokens))
577
+ if tokens[k].text == "}" and tokens[k].depth == 0), len(tokens))
578
+ returns = [k for k in range(body + 1, close)
579
+ if tokens[k].text == "return" and tokens[k].depth == 1
580
+ and k + 1 < len(tokens) and tokens[k + 1].text == "("]
581
+ if not returns:
582
+ raise Refused("the default export does not `return (` a JSX element at its own "
583
+ "body level to place a JSON-LD <script> in")
584
+ if len(returns) > 1:
585
+ raise Refused(f"the default export has {len(returns)} `return (` statements; "
586
+ "where the JSON-LD <script> belongs is ambiguous")
587
+ paren = tokens[returns[0] + 1]
588
+ root = next((tag for tag in lx.tags if tag.start > paren.start), None)
589
+ if root is None or text[paren.end:root.start].strip():
590
+ raise Refused("the default export does not return a JSX element")
591
+ if root.self_closing:
592
+ raise Refused("the returned JSX element has no children to add a <script> to")
593
+ return root.end, line_indent(text, root.start) + " "
594
+
595
+
596
+ class NextAdapter(Adapter):
597
+ name = "nextjs"
598
+ frameworks = ("next-app-router",)
599
+ suffixes = (".tsx", ".jsx", ".ts", ".js")
600
+
601
+ def describe(self, ctx: Context, text: str) -> str | None:
602
+ return _generate_refusal(text)
603
+
604
+ def edit_one(self, ctx: Context, text: str, edit: Edit) -> str:
605
+ if edit.kind == "jsonld":
606
+ return self._jsonld(ctx, text, edit)
607
+ if edit.kind == "lang":
608
+ raise Refused("in the App Router, <html lang> lives in the root layout and "
609
+ "applies to every route (and differs per locale on a "
610
+ "multilingual site); set it there by hand")
611
+ lexed(text)
612
+ generated = _generate_refusal(text)
613
+ if generated is not None:
614
+ raise Refused(generated)
615
+ if is_client_component(text):
616
+ raise Refused("the page is a Client Component ('use client'); Next.js only "
617
+ "reads metadata from Server Components")
618
+ if edit.kind == "og" and edit.name == "og:image":
619
+ path = ["openGraph", "images"]
620
+ elif edit.kind == "og":
621
+ path = ["openGraph", OG_KEYS[edit.name or ""]]
622
+ else:
623
+ path = {"title": ["title"], "description": ["description"],
624
+ "canonical": ["alternates", "canonical"],
625
+ "robots": ["robots"]}[edit.kind]
626
+ layouts = _ancestor_layouts(ctx)
627
+ obj = find_metadata(text)
628
+ hazard = _layout_declares(layouts, path[0]) if path[0] in MERGE_HAZARD else None
629
+ if obj is None:
630
+ check_mode(edit, False, f"metadata.{'.'.join(path)}")
631
+ if hazard is not None:
632
+ raise Refused(f"adding `{path[0]}` to this page would replace the whole "
633
+ f"`{path[0]}` object set by {hazard} (Next.js merges "
634
+ "metadata shallowly); add it there or by hand")
635
+ if edit.kind == "title" and any(
636
+ _GENERATE.search(t) or re.search(r"\btemplate\s*:", t)
637
+ for _, t in layouts):
638
+ return _insert_metadata(text, ["title"], {"absolute": edit.text})
639
+ return _insert_metadata(text, path, edit.text)
640
+ if edit.kind == "title":
641
+ return _edit_title(text, obj, edit.text, layouts)
642
+ return _set_path(text, obj, path, edit.text, hazard, edit)
643
+
644
+ def _jsonld(self, ctx: Context, text: str, edit: Edit) -> str:
645
+ if not ctx.rel.lower().endswith((".tsx", ".jsx", ".js")):
646
+ raise Refused(f"{Path(ctx.rel).name} cannot contain JSX")
647
+ wanted = edit.value
648
+ lx = lexed(text)
649
+ matches = []
650
+ for script in _jsx_ld_scripts(text, lx):
651
+ if script.literal is None:
652
+ raise Refused("an existing JSON-LD <script> is computed (not a string "
653
+ "literal), so it cannot be proven to be a different node; "
654
+ "refusing to add a second one")
655
+ try:
656
+ existing = json.loads(script.literal.value)
657
+ except (json.JSONDecodeError, RecursionError) as exc:
658
+ raise Refused("an existing JSON-LD block does not parse") from exc
659
+ if jsonld_match(existing, wanted):
660
+ matches.append((script, existing))
661
+ if len(matches) > 1:
662
+ raise Refused(f"{len(matches)} JSON-LD blocks hold {jsonld_type(wanted)}; "
663
+ "which one to replace is ambiguous")
664
+ literal = js_string(compact_jsonld(wanted))
665
+ if matches:
666
+ script, existing = matches[0]
667
+ if existing == wanted:
668
+ return text
669
+ node = script.literal
670
+ return text[:node.start] + literal + text[node.end:]
671
+ at, indent = _place_script(text, lx)
672
+ eol = newline_style(text)
673
+ element = (f'<script type="application/ld+json" '
674
+ f"dangerouslySetInnerHTML={{{{ __html: {literal} }}}} />")
675
+ return text[:at] + f"{eol}{indent}{element}" + text[at:]
676
+
677
+ def jsonld_health(self, text: str) -> tuple[int, int]:
678
+ try:
679
+ scripts = _jsx_ld_scripts(text, lex(text))
680
+ except (Refused, Unreadable):
681
+ return (-1, -1)
682
+ ok = 0
683
+ for script in scripts:
684
+ if script.literal is None:
685
+ ok += 1 # computed: cannot be evaluated, counted as is
686
+ continue
687
+ try:
688
+ json.loads(script.literal.value)
689
+ ok += 1
690
+ except (json.JSONDecodeError, RecursionError):
691
+ pass
692
+ return len(scripts), ok