@alexgreensh/token-optimizer 5.13.66 → 5.13.68

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 (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +0 -10
  4. package/package.json +1 -1
  5. package/skills/token-optimizer/examples/hooks-starter.json +0 -10
  6. package/skills/token-optimizer/scripts/_measure/_compat.py +2 -2
  7. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +15 -0
  8. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +63 -0
  9. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
  10. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +39 -0
  11. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
  12. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  13. package/skills/token-optimizer/scripts/_measure/cache_policy.py +54 -1
  14. package/skills/token-optimizer/scripts/_measure/daemon.py +21 -51
  15. package/skills/token-optimizer/scripts/_measure/lifecycle.py +81 -327
  16. package/skills/token-optimizer/scripts/_tomli.py +916 -0
  17. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
  18. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  19. package/skills/token-optimizer/scripts/bash_compress.py +3 -3
  20. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
  21. package/skills/token-optimizer/scripts/cloud_kit.py +21 -21
  22. package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
  23. package/skills/token-optimizer/scripts/codex_doctor.py +33 -7
  24. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  25. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  26. package/skills/token-optimizer/scripts/command_filters.py +359 -18
  27. package/skills/token-optimizer/scripts/copilot_install.py +5 -0
  28. package/skills/token-optimizer/scripts/cursor_install.py +5 -0
  29. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  30. package/skills/token-optimizer/scripts/devin_source.py +6 -5
  31. package/skills/token-optimizer/scripts/devin_verify.py +16 -0
  32. package/skills/token-optimizer/scripts/grok_install.py +5 -0
  33. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  34. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  35. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  36. package/skills/token-optimizer/scripts/measure.py +2 -2
  37. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  38. package/skills/token-optimizer/scripts/read_cache.py +20 -21
  39. package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
  40. package/skills/token-optimizer/scripts/session_store.py +11 -48
  41. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  42. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  43. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
@@ -0,0 +1,916 @@
1
+ """Vendored Tomli 2.2.1 (MIT, Taneli Hukkinen) as a single flat module.
2
+
3
+ Full TOML 1.0 parser used as the Python 3.9/3.10 fallback where stdlib
4
+ tomllib is absent.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ # SPDX-License-Identifier: MIT
9
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
10
+ # Licensed to PSF under a Contributor Agreement.
11
+ # MIT License
12
+ #
13
+ # Copyright (c) 2021 Taneli Hukkinen
14
+ #
15
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ # of this software and associated documentation files (the "Software"), to deal
17
+ # in the Software without restriction, including without limitation the rights
18
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ # copies of the Software, and to permit persons to whom the Software is
20
+ # furnished to do so, subject to the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be included in all
23
+ # copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ # SOFTWARE.
32
+
33
+ from typing import Any, Callable, Tuple
34
+
35
+ # Type annotations
36
+ ParseFloat = Callable[[str], Any]
37
+ Key = Tuple[str, ...]
38
+ Pos = int
39
+
40
+
41
+ # SPDX-License-Identifier: MIT
42
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
43
+ # Licensed to PSF under a Contributor Agreement.
44
+
45
+
46
+ from datetime import date, datetime, time, timedelta, timezone, tzinfo
47
+ from functools import lru_cache
48
+ import re
49
+ from typing import Any, Final
50
+
51
+
52
+ # E.g.
53
+ # - 00:32:00.999999
54
+ # - 00:32:00
55
+ _TIME_RE_STR: Final = (
56
+ r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
57
+ )
58
+
59
+ RE_NUMBER: Final = re.compile(
60
+ r"""
61
+ 0
62
+ (?:
63
+ x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex
64
+ |
65
+ b[01](?:_?[01])* # bin
66
+ |
67
+ o[0-7](?:_?[0-7])* # oct
68
+ )
69
+ |
70
+ [+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part
71
+ (?P<floatpart>
72
+ (?:\.[0-9](?:_?[0-9])*)? # optional fractional part
73
+ (?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part
74
+ )
75
+ """,
76
+ flags=re.VERBOSE,
77
+ )
78
+ RE_LOCALTIME: Final = re.compile(_TIME_RE_STR)
79
+ RE_DATETIME: Final = re.compile(
80
+ rf"""
81
+ ([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
82
+ (?:
83
+ [Tt ]
84
+ {_TIME_RE_STR}
85
+ (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset
86
+ )?
87
+ """,
88
+ flags=re.VERBOSE,
89
+ )
90
+
91
+
92
+ def match_to_datetime(match: re.Match) -> datetime | date:
93
+ """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
94
+
95
+ Raises ValueError if the match does not correspond to a valid date
96
+ or datetime.
97
+ """
98
+ (
99
+ year_str,
100
+ month_str,
101
+ day_str,
102
+ hour_str,
103
+ minute_str,
104
+ sec_str,
105
+ micros_str,
106
+ zulu_time,
107
+ offset_sign_str,
108
+ offset_hour_str,
109
+ offset_minute_str,
110
+ ) = match.groups()
111
+ year, month, day = int(year_str), int(month_str), int(day_str)
112
+ if hour_str is None:
113
+ return date(year, month, day)
114
+ hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
115
+ micros = int(micros_str.ljust(6, "0")) if micros_str else 0
116
+ if offset_sign_str:
117
+ tz: tzinfo | None = cached_tz(
118
+ offset_hour_str, offset_minute_str, offset_sign_str
119
+ )
120
+ elif zulu_time:
121
+ tz = timezone.utc
122
+ else: # local date-time
123
+ tz = None
124
+ return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
125
+
126
+
127
+ # No need to limit cache size. This is only ever called on input
128
+ # that matched RE_DATETIME, so there is an implicit bound of
129
+ # 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
130
+ @lru_cache(maxsize=None)
131
+ def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
132
+ sign = 1 if sign_str == "+" else -1
133
+ return timezone(
134
+ timedelta(
135
+ hours=sign * int(hour_str),
136
+ minutes=sign * int(minute_str),
137
+ )
138
+ )
139
+
140
+
141
+ def match_to_localtime(match: re.Match) -> time:
142
+ hour_str, minute_str, sec_str, micros_str = match.groups()
143
+ micros = int(micros_str.ljust(6, "0")) if micros_str else 0
144
+ return time(int(hour_str), int(minute_str), int(sec_str), micros)
145
+
146
+
147
+ def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
148
+ if match.group("floatpart"):
149
+ return parse_float(match.group())
150
+ return int(match.group(), 0)
151
+
152
+
153
+ # SPDX-License-Identifier: MIT
154
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
155
+ # Licensed to PSF under a Contributor Agreement.
156
+
157
+
158
+ from collections.abc import Iterable
159
+ import string
160
+ import sys
161
+ from types import MappingProxyType
162
+ from typing import IO, Any, Final, NamedTuple
163
+ import warnings
164
+
165
+
166
+ # Inline tables/arrays are implemented using recursion. Pathologically
167
+ # nested documents cause pure Python to raise RecursionError (which is OK),
168
+ # but mypyc binary wheels will crash unrecoverably (not OK). According to
169
+ # mypyc docs this will be fixed in the future:
170
+ # https://mypyc.readthedocs.io/en/latest/differences_from_python.html#stack-overflows
171
+ # Before mypyc's fix is in, recursion needs to be limited by this library.
172
+ # Choosing `sys.getrecursionlimit()` as maximum inline table/array nesting
173
+ # level, as it allows more nesting than pure Python, but still seems a far
174
+ # lower number than where mypyc binaries crash.
175
+ MAX_INLINE_NESTING: Final = sys.getrecursionlimit()
176
+
177
+ ASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
178
+
179
+ # Neither of these sets include quotation mark or backslash. They are
180
+ # currently handled as separate cases in the parser functions.
181
+ ILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t")
182
+ ILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n")
183
+
184
+ ILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
185
+ ILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS
186
+
187
+ ILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
188
+
189
+ TOML_WS: Final = frozenset(" \t")
190
+ TOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n")
191
+ BARE_KEY_CHARS: Final = frozenset(string.ascii_letters + string.digits + "-_")
192
+ KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")
193
+ HEXDIGIT_CHARS: Final = frozenset(string.hexdigits)
194
+
195
+ BASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(
196
+ {
197
+ "\\b": "\u0008", # backspace
198
+ "\\t": "\u0009", # tab
199
+ "\\n": "\u000A", # linefeed
200
+ "\\f": "\u000C", # form feed
201
+ "\\r": "\u000D", # carriage return
202
+ '\\"': "\u0022", # quote
203
+ "\\\\": "\u005C", # backslash
204
+ }
205
+ )
206
+
207
+
208
+ class DEPRECATED_DEFAULT:
209
+ """Sentinel to be used as default arg during deprecation
210
+ period of TOMLDecodeError's free-form arguments."""
211
+
212
+
213
+ class TOMLDecodeError(ValueError):
214
+ """An error raised if a document is not valid TOML.
215
+
216
+ Adds the following attributes to ValueError:
217
+ msg: The unformatted error message
218
+ doc: The TOML document being parsed
219
+ pos: The index of doc where parsing failed
220
+ lineno: The line corresponding to pos
221
+ colno: The column corresponding to pos
222
+ """
223
+
224
+ def __init__(
225
+ self,
226
+ msg: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
227
+ doc: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
228
+ pos: Pos | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
229
+ *args: Any,
230
+ ):
231
+ if (
232
+ args
233
+ or not isinstance(msg, str)
234
+ or not isinstance(doc, str)
235
+ or not isinstance(pos, int)
236
+ ):
237
+ warnings.warn(
238
+ "Free-form arguments for TOMLDecodeError are deprecated. "
239
+ "Please set 'msg' (str), 'doc' (str) and 'pos' (int) arguments only.",
240
+ DeprecationWarning,
241
+ stacklevel=2,
242
+ )
243
+ if pos is not DEPRECATED_DEFAULT:
244
+ args = pos, *args
245
+ if doc is not DEPRECATED_DEFAULT:
246
+ args = doc, *args
247
+ if msg is not DEPRECATED_DEFAULT:
248
+ args = msg, *args
249
+ ValueError.__init__(self, *args)
250
+ return
251
+
252
+ lineno = doc.count("\n", 0, pos) + 1
253
+ if lineno == 1:
254
+ colno = pos + 1
255
+ else:
256
+ colno = pos - doc.rindex("\n", 0, pos)
257
+
258
+ if pos >= len(doc):
259
+ coord_repr = "end of document"
260
+ else:
261
+ coord_repr = f"line {lineno}, column {colno}"
262
+ errmsg = f"{msg} (at {coord_repr})"
263
+ ValueError.__init__(self, errmsg)
264
+
265
+ self.msg = msg
266
+ self.doc = doc
267
+ self.pos = pos
268
+ self.lineno = lineno
269
+ self.colno = colno
270
+
271
+
272
+ def load(__fp: IO[bytes], *, parse_float: ParseFloat = float) -> dict[str, Any]:
273
+ """Parse TOML from a binary file object."""
274
+ b = __fp.read()
275
+ try:
276
+ s = b.decode()
277
+ except AttributeError:
278
+ raise TypeError(
279
+ "File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"
280
+ ) from None
281
+ return loads(s, parse_float=parse_float)
282
+
283
+
284
+ def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]: # noqa: C901
285
+ """Parse TOML from a string."""
286
+
287
+ # The spec allows converting "\r\n" to "\n", even in string
288
+ # literals. Let's do so to simplify parsing.
289
+ try:
290
+ src = __s.replace("\r\n", "\n")
291
+ except (AttributeError, TypeError):
292
+ raise TypeError(
293
+ f"Expected str object, not '{type(__s).__qualname__}'"
294
+ ) from None
295
+ pos = 0
296
+ out = Output(NestedDict(), Flags())
297
+ header: Key = ()
298
+ parse_float = make_safe_parse_float(parse_float)
299
+
300
+ # Parse one statement at a time
301
+ # (typically means one line in TOML source)
302
+ while True:
303
+ # 1. Skip line leading whitespace
304
+ pos = skip_chars(src, pos, TOML_WS)
305
+
306
+ # 2. Parse rules. Expect one of the following:
307
+ # - end of file
308
+ # - end of line
309
+ # - comment
310
+ # - key/value pair
311
+ # - append dict to list (and move to its namespace)
312
+ # - create dict (and move to its namespace)
313
+ # Skip trailing whitespace when applicable.
314
+ try:
315
+ char = src[pos]
316
+ except IndexError:
317
+ break
318
+ if char == "\n":
319
+ pos += 1
320
+ continue
321
+ if char in KEY_INITIAL_CHARS:
322
+ pos = key_value_rule(src, pos, out, header, parse_float)
323
+ pos = skip_chars(src, pos, TOML_WS)
324
+ elif char == "[":
325
+ try:
326
+ second_char: str | None = src[pos + 1]
327
+ except IndexError:
328
+ second_char = None
329
+ out.flags.finalize_pending()
330
+ if second_char == "[":
331
+ pos, header = create_list_rule(src, pos, out)
332
+ else:
333
+ pos, header = create_dict_rule(src, pos, out)
334
+ pos = skip_chars(src, pos, TOML_WS)
335
+ elif char != "#":
336
+ raise TOMLDecodeError("Invalid statement", src, pos)
337
+
338
+ # 3. Skip comment
339
+ pos = skip_comment(src, pos)
340
+
341
+ # 4. Expect end of line or end of file
342
+ try:
343
+ char = src[pos]
344
+ except IndexError:
345
+ break
346
+ if char != "\n":
347
+ raise TOMLDecodeError(
348
+ "Expected newline or end of document after a statement", src, pos
349
+ )
350
+ pos += 1
351
+
352
+ return out.data.dict
353
+
354
+
355
+ class Flags:
356
+ """Flags that map to parsed keys/namespaces."""
357
+
358
+ # Marks an immutable namespace (inline array or inline table).
359
+ FROZEN: Final = 0
360
+ # Marks a nest that has been explicitly created and can no longer
361
+ # be opened using the "[table]" syntax.
362
+ EXPLICIT_NEST: Final = 1
363
+
364
+ def __init__(self) -> None:
365
+ self._flags: dict[str, dict] = {}
366
+ self._pending_flags: set[tuple[Key, int]] = set()
367
+
368
+ def add_pending(self, key: Key, flag: int) -> None:
369
+ self._pending_flags.add((key, flag))
370
+
371
+ def finalize_pending(self) -> None:
372
+ for key, flag in self._pending_flags:
373
+ self.set(key, flag, recursive=False)
374
+ self._pending_flags.clear()
375
+
376
+ def unset_all(self, key: Key) -> None:
377
+ cont = self._flags
378
+ for k in key[:-1]:
379
+ if k not in cont:
380
+ return
381
+ cont = cont[k]["nested"]
382
+ cont.pop(key[-1], None)
383
+
384
+ def set(self, key: Key, flag: int, *, recursive: bool) -> None: # noqa: A003
385
+ cont = self._flags
386
+ key_parent, key_stem = key[:-1], key[-1]
387
+ for k in key_parent:
388
+ if k not in cont:
389
+ cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}}
390
+ cont = cont[k]["nested"]
391
+ if key_stem not in cont:
392
+ cont[key_stem] = {"flags": set(), "recursive_flags": set(), "nested": {}}
393
+ cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag)
394
+
395
+ def is_(self, key: Key, flag: int) -> bool:
396
+ if not key:
397
+ return False # document root has no flags
398
+ cont = self._flags
399
+ for k in key[:-1]:
400
+ if k not in cont:
401
+ return False
402
+ inner_cont = cont[k]
403
+ if flag in inner_cont["recursive_flags"]:
404
+ return True
405
+ cont = inner_cont["nested"]
406
+ key_stem = key[-1]
407
+ if key_stem in cont:
408
+ inner_cont = cont[key_stem]
409
+ return flag in inner_cont["flags"] or flag in inner_cont["recursive_flags"]
410
+ return False
411
+
412
+
413
+ class NestedDict:
414
+ def __init__(self) -> None:
415
+ # The parsed content of the TOML document
416
+ self.dict: dict[str, Any] = {}
417
+
418
+ def get_or_create_nest(
419
+ self,
420
+ key: Key,
421
+ *,
422
+ access_lists: bool = True,
423
+ ) -> dict:
424
+ cont: Any = self.dict
425
+ for k in key:
426
+ if k not in cont:
427
+ cont[k] = {}
428
+ cont = cont[k]
429
+ if access_lists and isinstance(cont, list):
430
+ cont = cont[-1]
431
+ if not isinstance(cont, dict):
432
+ raise KeyError("There is no nest behind this key")
433
+ return cont
434
+
435
+ def append_nest_to_list(self, key: Key) -> None:
436
+ cont = self.get_or_create_nest(key[:-1])
437
+ last_key = key[-1]
438
+ if last_key in cont:
439
+ list_ = cont[last_key]
440
+ if not isinstance(list_, list):
441
+ raise KeyError("An object other than list found behind this key")
442
+ list_.append({})
443
+ else:
444
+ cont[last_key] = [{}]
445
+
446
+
447
+ class Output(NamedTuple):
448
+ data: NestedDict
449
+ flags: Flags
450
+
451
+
452
+ def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:
453
+ try:
454
+ while src[pos] in chars:
455
+ pos += 1
456
+ except IndexError:
457
+ pass
458
+ return pos
459
+
460
+
461
+ def skip_until(
462
+ src: str,
463
+ pos: Pos,
464
+ expect: str,
465
+ *,
466
+ error_on: frozenset[str],
467
+ error_on_eof: bool,
468
+ ) -> Pos:
469
+ try:
470
+ new_pos = src.index(expect, pos)
471
+ except ValueError:
472
+ new_pos = len(src)
473
+ if error_on_eof:
474
+ raise TOMLDecodeError(f"Expected {expect!r}", src, new_pos) from None
475
+
476
+ if not error_on.isdisjoint(src[pos:new_pos]):
477
+ while src[pos] not in error_on:
478
+ pos += 1
479
+ raise TOMLDecodeError(f"Found invalid character {src[pos]!r}", src, pos)
480
+ return new_pos
481
+
482
+
483
+ def skip_comment(src: str, pos: Pos) -> Pos:
484
+ try:
485
+ char: str | None = src[pos]
486
+ except IndexError:
487
+ char = None
488
+ if char == "#":
489
+ return skip_until(
490
+ src, pos + 1, "\n", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False
491
+ )
492
+ return pos
493
+
494
+
495
+ def skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:
496
+ while True:
497
+ pos_before_skip = pos
498
+ pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
499
+ pos = skip_comment(src, pos)
500
+ if pos == pos_before_skip:
501
+ return pos
502
+
503
+
504
+ def create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
505
+ pos += 1 # Skip "["
506
+ pos = skip_chars(src, pos, TOML_WS)
507
+ pos, key = parse_key(src, pos)
508
+
509
+ if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):
510
+ raise TOMLDecodeError(f"Cannot declare {key} twice", src, pos)
511
+ out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
512
+ try:
513
+ out.data.get_or_create_nest(key)
514
+ except KeyError:
515
+ raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
516
+
517
+ if not src.startswith("]", pos):
518
+ raise TOMLDecodeError(
519
+ "Expected ']' at the end of a table declaration", src, pos
520
+ )
521
+ return pos + 1, key
522
+
523
+
524
+ def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
525
+ pos += 2 # Skip "[["
526
+ pos = skip_chars(src, pos, TOML_WS)
527
+ pos, key = parse_key(src, pos)
528
+
529
+ if out.flags.is_(key, Flags.FROZEN):
530
+ raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
531
+ # Free the namespace now that it points to another empty list item...
532
+ out.flags.unset_all(key)
533
+ # ...but this key precisely is still prohibited from table declaration
534
+ out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
535
+ try:
536
+ out.data.append_nest_to_list(key)
537
+ except KeyError:
538
+ raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
539
+
540
+ if not src.startswith("]]", pos):
541
+ raise TOMLDecodeError(
542
+ "Expected ']]' at the end of an array declaration", src, pos
543
+ )
544
+ return pos + 2, key
545
+
546
+
547
+ def key_value_rule(
548
+ src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat
549
+ ) -> Pos:
550
+ pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl=0)
551
+ key_parent, key_stem = key[:-1], key[-1]
552
+ abs_key_parent = header + key_parent
553
+
554
+ relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))
555
+ for cont_key in relative_path_cont_keys:
556
+ # Check that dotted key syntax does not redefine an existing table
557
+ if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):
558
+ raise TOMLDecodeError(f"Cannot redefine namespace {cont_key}", src, pos)
559
+ # Containers in the relative path can't be opened with the table syntax or
560
+ # dotted key/value syntax in following table sections.
561
+ out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)
562
+
563
+ if out.flags.is_(abs_key_parent, Flags.FROZEN):
564
+ raise TOMLDecodeError(
565
+ f"Cannot mutate immutable namespace {abs_key_parent}", src, pos
566
+ )
567
+
568
+ try:
569
+ nest = out.data.get_or_create_nest(abs_key_parent)
570
+ except KeyError:
571
+ raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
572
+ if key_stem in nest:
573
+ raise TOMLDecodeError("Cannot overwrite a value", src, pos)
574
+ # Mark inline table and array namespaces recursively immutable
575
+ if isinstance(value, (dict, list)):
576
+ out.flags.set(header + key, Flags.FROZEN, recursive=True)
577
+ nest[key_stem] = value
578
+ return pos
579
+
580
+
581
+ def parse_key_value_pair(
582
+ src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
583
+ ) -> tuple[Pos, Key, Any]:
584
+ pos, key = parse_key(src, pos)
585
+ try:
586
+ char: str | None = src[pos]
587
+ except IndexError:
588
+ char = None
589
+ if char != "=":
590
+ raise TOMLDecodeError("Expected '=' after a key in a key/value pair", src, pos)
591
+ pos += 1
592
+ pos = skip_chars(src, pos, TOML_WS)
593
+ pos, value = parse_value(src, pos, parse_float, nest_lvl)
594
+ return pos, key, value
595
+
596
+
597
+ def parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:
598
+ pos, key_part = parse_key_part(src, pos)
599
+ key: Key = (key_part,)
600
+ pos = skip_chars(src, pos, TOML_WS)
601
+ while True:
602
+ try:
603
+ char: str | None = src[pos]
604
+ except IndexError:
605
+ char = None
606
+ if char != ".":
607
+ return pos, key
608
+ pos += 1
609
+ pos = skip_chars(src, pos, TOML_WS)
610
+ pos, key_part = parse_key_part(src, pos)
611
+ key += (key_part,)
612
+ pos = skip_chars(src, pos, TOML_WS)
613
+
614
+
615
+ def parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:
616
+ try:
617
+ char: str | None = src[pos]
618
+ except IndexError:
619
+ char = None
620
+ if char in BARE_KEY_CHARS:
621
+ start_pos = pos
622
+ pos = skip_chars(src, pos, BARE_KEY_CHARS)
623
+ return pos, src[start_pos:pos]
624
+ if char == "'":
625
+ return parse_literal_str(src, pos)
626
+ if char == '"':
627
+ return parse_one_line_basic_str(src, pos)
628
+ raise TOMLDecodeError("Invalid initial character for a key part", src, pos)
629
+
630
+
631
+ def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:
632
+ pos += 1
633
+ return parse_basic_str(src, pos, multiline=False)
634
+
635
+
636
+ def parse_array(
637
+ src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
638
+ ) -> tuple[Pos, list]:
639
+ pos += 1
640
+ array: list = []
641
+
642
+ pos = skip_comments_and_array_ws(src, pos)
643
+ if src.startswith("]", pos):
644
+ return pos + 1, array
645
+ while True:
646
+ pos, val = parse_value(src, pos, parse_float, nest_lvl)
647
+ array.append(val)
648
+ pos = skip_comments_and_array_ws(src, pos)
649
+
650
+ c = src[pos : pos + 1]
651
+ if c == "]":
652
+ return pos + 1, array
653
+ if c != ",":
654
+ raise TOMLDecodeError("Unclosed array", src, pos)
655
+ pos += 1
656
+
657
+ pos = skip_comments_and_array_ws(src, pos)
658
+ if src.startswith("]", pos):
659
+ return pos + 1, array
660
+
661
+
662
+ def parse_inline_table(
663
+ src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
664
+ ) -> tuple[Pos, dict]:
665
+ pos += 1
666
+ nested_dict = NestedDict()
667
+ flags = Flags()
668
+
669
+ pos = skip_chars(src, pos, TOML_WS)
670
+ if src.startswith("}", pos):
671
+ return pos + 1, nested_dict.dict
672
+ while True:
673
+ pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl)
674
+ key_parent, key_stem = key[:-1], key[-1]
675
+ if flags.is_(key, Flags.FROZEN):
676
+ raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
677
+ try:
678
+ nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
679
+ except KeyError:
680
+ raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
681
+ if key_stem in nest:
682
+ raise TOMLDecodeError(f"Duplicate inline table key {key_stem!r}", src, pos)
683
+ nest[key_stem] = value
684
+ pos = skip_chars(src, pos, TOML_WS)
685
+ c = src[pos : pos + 1]
686
+ if c == "}":
687
+ return pos + 1, nested_dict.dict
688
+ if c != ",":
689
+ raise TOMLDecodeError("Unclosed inline table", src, pos)
690
+ if isinstance(value, (dict, list)):
691
+ flags.set(key, Flags.FROZEN, recursive=True)
692
+ pos += 1
693
+ pos = skip_chars(src, pos, TOML_WS)
694
+
695
+
696
+ def parse_basic_str_escape(
697
+ src: str, pos: Pos, *, multiline: bool = False
698
+ ) -> tuple[Pos, str]:
699
+ escape_id = src[pos : pos + 2]
700
+ pos += 2
701
+ if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}:
702
+ # Skip whitespace until next non-whitespace character or end of
703
+ # the doc. Error if non-whitespace is found before newline.
704
+ if escape_id != "\\\n":
705
+ pos = skip_chars(src, pos, TOML_WS)
706
+ try:
707
+ char = src[pos]
708
+ except IndexError:
709
+ return pos, ""
710
+ if char != "\n":
711
+ raise TOMLDecodeError("Unescaped '\\' in a string", src, pos)
712
+ pos += 1
713
+ pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
714
+ return pos, ""
715
+ if escape_id == "\\u":
716
+ return parse_hex_char(src, pos, 4)
717
+ if escape_id == "\\U":
718
+ return parse_hex_char(src, pos, 8)
719
+ try:
720
+ return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]
721
+ except KeyError:
722
+ raise TOMLDecodeError("Unescaped '\\' in a string", src, pos) from None
723
+
724
+
725
+ def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:
726
+ return parse_basic_str_escape(src, pos, multiline=True)
727
+
728
+
729
+ def parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:
730
+ hex_str = src[pos : pos + hex_len]
731
+ if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):
732
+ raise TOMLDecodeError("Invalid hex value", src, pos)
733
+ pos += hex_len
734
+ hex_int = int(hex_str, 16)
735
+ if not is_unicode_scalar_value(hex_int):
736
+ raise TOMLDecodeError(
737
+ "Escaped character is not a Unicode scalar value", src, pos
738
+ )
739
+ return pos, chr(hex_int)
740
+
741
+
742
+ def parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:
743
+ pos += 1 # Skip starting apostrophe
744
+ start_pos = pos
745
+ pos = skip_until(
746
+ src, pos, "'", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True
747
+ )
748
+ return pos + 1, src[start_pos:pos] # Skip ending apostrophe
749
+
750
+
751
+ def parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:
752
+ pos += 3
753
+ if src.startswith("\n", pos):
754
+ pos += 1
755
+
756
+ if literal:
757
+ delim = "'"
758
+ end_pos = skip_until(
759
+ src,
760
+ pos,
761
+ "'''",
762
+ error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,
763
+ error_on_eof=True,
764
+ )
765
+ result = src[pos:end_pos]
766
+ pos = end_pos + 3
767
+ else:
768
+ delim = '"'
769
+ pos, result = parse_basic_str(src, pos, multiline=True)
770
+
771
+ # Add at maximum two extra apostrophes/quotes if the end sequence
772
+ # is 4 or 5 chars long instead of just 3.
773
+ if not src.startswith(delim, pos):
774
+ return pos, result
775
+ pos += 1
776
+ if not src.startswith(delim, pos):
777
+ return pos, result + delim
778
+ pos += 1
779
+ return pos, result + (delim * 2)
780
+
781
+
782
+ def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
783
+ if multiline:
784
+ error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS
785
+ parse_escapes = parse_basic_str_escape_multiline
786
+ else:
787
+ error_on = ILLEGAL_BASIC_STR_CHARS
788
+ parse_escapes = parse_basic_str_escape
789
+ result = ""
790
+ start_pos = pos
791
+ while True:
792
+ try:
793
+ char = src[pos]
794
+ except IndexError:
795
+ raise TOMLDecodeError("Unterminated string", src, pos) from None
796
+ if char == '"':
797
+ if not multiline:
798
+ return pos + 1, result + src[start_pos:pos]
799
+ if src.startswith('"""', pos):
800
+ return pos + 3, result + src[start_pos:pos]
801
+ pos += 1
802
+ continue
803
+ if char == "\\":
804
+ result += src[start_pos:pos]
805
+ pos, parsed_escape = parse_escapes(src, pos)
806
+ result += parsed_escape
807
+ start_pos = pos
808
+ continue
809
+ if char in error_on:
810
+ raise TOMLDecodeError(f"Illegal character {char!r}", src, pos)
811
+ pos += 1
812
+
813
+
814
+ def parse_value( # noqa: C901
815
+ src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
816
+ ) -> tuple[Pos, Any]:
817
+ if nest_lvl > MAX_INLINE_NESTING:
818
+ # Pure Python should have raised RecursionError already.
819
+ # This ensures mypyc binaries eventually do the same.
820
+ raise RecursionError( # pragma: no cover
821
+ "TOML inline arrays/tables are nested more than the allowed"
822
+ f" {MAX_INLINE_NESTING} levels"
823
+ )
824
+
825
+ try:
826
+ char: str | None = src[pos]
827
+ except IndexError:
828
+ char = None
829
+
830
+ # IMPORTANT: order conditions based on speed of checking and likelihood
831
+
832
+ # Basic strings
833
+ if char == '"':
834
+ if src.startswith('"""', pos):
835
+ return parse_multiline_str(src, pos, literal=False)
836
+ return parse_one_line_basic_str(src, pos)
837
+
838
+ # Literal strings
839
+ if char == "'":
840
+ if src.startswith("'''", pos):
841
+ return parse_multiline_str(src, pos, literal=True)
842
+ return parse_literal_str(src, pos)
843
+
844
+ # Booleans
845
+ if char == "t":
846
+ if src.startswith("true", pos):
847
+ return pos + 4, True
848
+ if char == "f":
849
+ if src.startswith("false", pos):
850
+ return pos + 5, False
851
+
852
+ # Arrays
853
+ if char == "[":
854
+ return parse_array(src, pos, parse_float, nest_lvl + 1)
855
+
856
+ # Inline tables
857
+ if char == "{":
858
+ return parse_inline_table(src, pos, parse_float, nest_lvl + 1)
859
+
860
+ # Dates and times
861
+ datetime_match = RE_DATETIME.match(src, pos)
862
+ if datetime_match:
863
+ try:
864
+ datetime_obj = match_to_datetime(datetime_match)
865
+ except ValueError as e:
866
+ raise TOMLDecodeError("Invalid date or datetime", src, pos) from e
867
+ return datetime_match.end(), datetime_obj
868
+ localtime_match = RE_LOCALTIME.match(src, pos)
869
+ if localtime_match:
870
+ return localtime_match.end(), match_to_localtime(localtime_match)
871
+
872
+ # Integers and "normal" floats.
873
+ # The regex will greedily match any type starting with a decimal
874
+ # char, so needs to be located after handling of dates and times.
875
+ number_match = RE_NUMBER.match(src, pos)
876
+ if number_match:
877
+ return number_match.end(), match_to_number(number_match, parse_float)
878
+
879
+ # Special floats
880
+ first_three = src[pos : pos + 3]
881
+ if first_three in {"inf", "nan"}:
882
+ return pos + 3, parse_float(first_three)
883
+ first_four = src[pos : pos + 4]
884
+ if first_four in {"-inf", "+inf", "-nan", "+nan"}:
885
+ return pos + 4, parse_float(first_four)
886
+
887
+ raise TOMLDecodeError("Invalid value", src, pos)
888
+
889
+
890
+ def is_unicode_scalar_value(codepoint: int) -> bool:
891
+ return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)
892
+
893
+
894
+ def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
895
+ """A decorator to make `parse_float` safe.
896
+
897
+ `parse_float` must not return dicts or lists, because these types
898
+ would be mixed with parsed TOML tables and arrays, thus confusing
899
+ the parser. The returned decorated callable raises `ValueError`
900
+ instead of returning illegal types.
901
+ """
902
+ # The default `float` callable never returns illegal types. Optimize it.
903
+ if parse_float is float:
904
+ return float
905
+
906
+ def safe_parse_float(float_str: str) -> Any:
907
+ float_value = parse_float(float_str)
908
+ if isinstance(float_value, (dict, list)):
909
+ raise ValueError("parse_float must not return dicts or lists")
910
+ return float_value
911
+
912
+ return safe_parse_float
913
+
914
+
915
+ __all__ = ("loads", "load", "TOMLDecodeError")
916
+ __version__ = "2.2.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT