diff --git a/CHANGELOG.md b/CHANGELOG.md index 97b3d21..7e2515a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.145.0 (2026-11-23) + +- **A share carries under `elements/` and `spatial/` only what the folder reader serves.** `write_world_file(include_hidden=False)` and `world_file_bytes` now ask `read_folder` which files are elements, and carry those that hold no hidden mark. Every other file there is left out and listed in `unread_left_out=`: a file with another extension (`notes.txt`, a browser's swap file), one deeper than a type folder (a hidden element's file moved into `old/` by hand), one directly under `elements/`, one in a folder that is no type and an object with no non-empty string `id`. Until now a share carried a file with another extension, or one not directly in a type folder, whatever it held, a hidden element's text included, and judged the other kinds by their own mark alone. A file that holds a mark and is not served as an element is listed with the unread, not the hidden. +- **An id that two files hold travels in neither file on a share.** Each file was judged by its own mark, so a hidden element's second, unmarked file travelled. Both files are now left out and listed in `unread_left_out=`, within one layout or across `elements/` and `spatial/`: with two files for one id, which mark is the element's cannot be said. +- **A copy never rewrites a file that was not read as an element.** The default copy takes the author fields out of element files only. A file of the kinds above keeps its bytes, author fields included; before, any JSON object directly in a folder of `elements/` or `spatial/` was rewritten. +- **`read_folder` reads names as written.** The extension is `.json` in lower case and a type folder is the type word in lower case, as the format says. `elements/map/M.JSON` was served as an element and is now skipped and listed (`the extension is not .json in lower case: not read`); `elements/Character/` was read as the character folder and now lands in `ignored_dirs`. A folder this package wrote is read as before: its writers write both in lower case. + ## 0.144.0 (2026-11-23) - **A share leaves out a file it could not read as an element.** `write_world_file(include_hidden=False)` and `world_file_bytes` carry a `.json` file in a type folder only when they read it as an element and found no hidden mark. A file there that could not be read is left out too, since its mark cannot be told: one that is not UTF-8 JSON (a write cut short), is nested more than 200 deep, holds a number that is not finite or an integer of more than 4,300 digits, or is not an object. Until now a share carried a file that was no JSON as it was, so a hidden element whose file was cut short travelled with its text. `unread_left_out=`, a second list the caller passes, receives those files' paths, sorted, apart from `hidden_left_out=`: a broken file is one a person may want to mend. This is the folder format's rule for a share, as ruled on 2026-11-23. diff --git a/README.md b/README.md index 9bae8e1..03e4dda 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ world = read_world_file("moppetopia.owworld") world.to_folder("moppetopia-copy") ``` -`write_world_file` carries `world.json` byte for byte (its `producer`, `source` and `format_version` included) and the folder's parts, `elements/`, `spatial/`, `media/` and `records/`, and nothing else: never an `api` block, never a tool's own folder unless you hand it in (`private_dir=".atlas"`, which makes the file a private copy rather than one to send around), and never a producer's records its `records/RECORDS.json` entry marks `"private": true` unless you ask (`include_private_records=True`); the manifest itself always travels as it is. A hidden element (`hidden: true` in its file) travels byte for byte, since the file is a copy; for a file you hand to someone else, `include_hidden=False` leaves every hidden element's file out whole, and a list passed as `hidden_left_out=` receives their paths. Nothing else changes, so a link from a visible element to a hidden one keeps an id the file no longer holds. An element's author fields (`created_by`, `changed_by`, `changed_via`, `changed_client` and `doors`) record which member and which tool wrote it, which means nothing to someone the world is handed to, so every element file leaves them out by default (`created_at` and `updated_at` stay): a file holding any of them is rewritten without them in the folder's own form, and a file holding none travels byte for byte. To archive your own world as it is on disk, pass `include_author_fields=True`. A share carries a file in a type folder only when it was read as an element and no mark was found: one that could not be read (not UTF-8 JSON, a write cut short, nested more than 200 deep, a number that is not finite, not an object) is left out as well, and a second list, `unread_left_out=`, receives those paths. A copy carries such a file byte for byte. The same folder gives the same bytes on one Python. `read_world_file` checks the whole archive before it unpacks anything and refuses a file it cannot open safely with a `WorldFileError`, whose `reason` names one of the spec's twelve causes (`unsafe_path`, `collision`, `too_big`, ...). It gives the same verdict as the TypeScript and Unity SDKs on every case of the format's conformance set. +`write_world_file` carries `world.json` byte for byte (its `producer`, `source` and `format_version` included) and the folder's parts, `elements/`, `spatial/`, `media/` and `records/`, and nothing else: never an `api` block, never a tool's own folder unless you hand it in (`private_dir=".atlas"`, which makes the file a private copy rather than one to send around), and never a producer's records its `records/RECORDS.json` entry marks `"private": true` unless you ask (`include_private_records=True`); the manifest itself always travels as it is. A hidden element (`hidden: true` in its file) travels byte for byte, since the file is a copy; for a file you hand to someone else, `include_hidden=False` leaves every hidden element's file out whole, and a list passed as `hidden_left_out=` receives their paths. Nothing else changes, so a link from a visible element to a hidden one keeps an id the file no longer holds. An element's author fields (`created_by`, `changed_by`, `changed_via`, `changed_client` and `doors`) record which member and which tool wrote it, which means nothing to someone the world is handed to, so every element file leaves them out by default (`created_at` and `updated_at` stay): a file holding any of them is rewritten without them in the folder's own form, and a file holding none travels byte for byte. To archive your own world as it is on disk, pass `include_author_fields=True`. A share carries a file under `elements/` or the old `spatial/` only when the package's folder reader (`read_folder`) serves it as an element and it holds no mark. Every other file there is left out as well, and a second list, `unread_left_out=`, receives those paths: a file that is not UTF-8 JSON (a write cut short, or text after the one JSON value), is nested more than 200 deep, holds a number that is not finite, is not an object or has no `id`; a file with another extension, deeper than a type folder (a hidden element's file moved into `old/` by hand) or in a folder that is no type; and both files of an id that two files hold, since which mark is the element's cannot be said (since 0.145.0; 0.144.0 left out only a file in a type folder that it could not parse). A copy carries every such file byte for byte and never rewrites it. The same folder gives the same bytes on one Python. `read_world_file` checks the whole archive before it unpacks anything and refuses a file it cannot open safely with a `WorldFileError`, whose `reason` names one of the spec's twelve causes (`unsafe_path`, `collision`, `too_big`, ...). It gives the same verdict as the TypeScript and Unity SDKs on every case of the format's conformance set. To send a folder's edits back, keep a copy exported before you edited, then push the difference: @@ -253,7 +253,7 @@ for finding in report.findings: It looks for links to elements that are not there, Events that end before they start, elements with no links in or out, two elements of one type whose names collide once case, character width, spacing and punctuation are folded (a name shared across types, such as a Location and its Pin, is not one), stubs never filled (a known-of element older than `--days`, or an element with no text in any of its type's text fields, on every type but map, marker, pin and relation), and a charter Law untouched after `--changes` changes in the feed. On a folder it also checks `world.json`: a `format_version` older than this package's (flag 9), and an `api_key` in a `world.json` that git tracks (flag 10). On both doors it reads the world's own house rules (flag 11, the checks profile: `x_checks_rules` on the world's Charter, the newest Law with supertype Charter that carries the mark `x_charter_of`, applied by `onlyworlds.apply_checks`) and names every element a rule finds short, with each rule's scoped and short counts, and every rule it cannot apply, with why; an older marked Charter is a finding, its rules not applied; a Law with supertype Charter and no mark is lore, not a Charter and not a finding, and its rules are never applied. Flag 14 names a marked Guide or Domain whose links name an element that is not in the world or a hidden one (every other reader is served the Guide or Domain without it; not through a guest key, and the hidden half only through a key that is served hidden elements). On a spine world (one where an element carries an `x_spine_` key), flag 13 reads each element with `read_spine_element` and names an off-list supertype on a listed type, every value the reader drops and a probe not in the probe form; then, on a source world, it checks that each row (an Object, Construct, Location or Law of a listed kind, the Charter too) is kept by exactly one Seat (a Title with supertype `Seat`, through its field for the row's type; any other Title neither owns nor counts), that every `x_spine_depends_on` id is in the world (not through a guest key), that a `legacy` or `provenance` row has an Event with supertype `Retirement` that names it in `x_spine_retires` and links it through its typed field where the type has one (`objects`, `constructs`, `locations`; an Event has no `laws` field, so a Law's retirement is attributed by the key alone; only through a key that sees every element, hidden ones too), that no row is still at `gone` (its retirement is unfinished), and that no two rows of one row type share a name once trimmed and folded for case (a Seat or any other element is outside that rule). Whether a probe passes and `x_spine_probed` are not checked, and the report says so. A projection (a public world built from a spine, each row naming its keeping Seat in `x_spine_owner`) is marked on its World with `x_spine_projection`, `{source, at}`: `source` the projected-from world's id as a string, a UUID that is no element's id in this world, and `at` the ISO 8601 time of the last rebuild, which must parse; each is a finding on the world otherwise. On a projection only the projection's own checks run: every row must carry `x_spine_owner` (the keeping Seat's name in the source, which need match nothing in the projection) and no element may be hidden; the source's checks do not run there, and the report names each. On an unmarked world `x_spine_owner` is a finding (the projection's third check), and a malformed mark is a finding on the world, which is then read as unmarked. Each check says how much it could compare, and one it cannot run (a folder has no change feed; nothing records whether a message was read) is listed with the reason, never counted as clean. A finding on a message or a room thing (supertype Message, Board, Work item, Spec, Heart, Vote or Sitting) is marked `"kind": "message"` and listed last, outside the count of things to look at. `--json` prints the same report for a tool, and `--packet` prints the findings as work packets (the `packet` extension profile: a Relation with supertype `Work item`, its elements with a reason each under `x_packet_elements`, a JSON array, empty when clean) for a tool that lands them in a world or a parlor. The exit code is 0 when there is nothing to look at, 1 when there is (a message finding too), 2 when nothing could be read. -On a folder, the report names first what it could not read as an element (`report.unread`, each a `file` and a `why`): a file that is not JSON, is nested more than 200 deep or holds a number that is not finite, is not an object or has no `id`, a second file of one id, a directory that is no type's. Every check ran on the rest, so an element in such a file counts as not there and a link to it reads as a link to a missing element; any unread file makes the exit code 1. A dot-prefixed file is a tool's litter and is not listed. +On a folder, the report names first what it could not read as an element (`report.unread`, each a `file` and a `why`): a file that is not JSON, is nested more than 200 deep or holds a number that is not finite, is not an object or has no `id`, a file whose extension is `.json` in another spelling (`M.JSON`), a second file of one id, a directory that is no type's (the type word in lower case). Every check ran on the rest, so an element in such a file counts as not there and a link to it reads as a link to a missing element; any unread file makes the exit code 1. A dot-prefixed file is a tool's litter and is not listed. The API door reads the key from `OW_API_KEY` and the PIN from `OW_API_PIN`, or from the toolkit's `ONLYWORLDS_API_KEY` and `ONLYWORLDS_API_PIN` when those are not set. diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 3b5229b..37d52ba 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.144.0" +__version__ = "0.145.0" diff --git a/src/onlyworlds/folder.py b/src/onlyworlds/folder.py index bfc3b32..63e56d3 100644 --- a/src/onlyworlds/folder.py +++ b/src/onlyworlds/folder.py @@ -454,6 +454,11 @@ def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder: - Every ``*.json`` in a type directory is ingested and keyed on its in-file ``id``; the filename is never parsed (§3.1). A dot-prefixed file there is a tool's litter, not an element: skipped and listed (clarified 2026-10-17). + - Names are read as written (ruled 2026-11-23): the extension is ``.json`` in lower case, so + ``M.JSON`` is skipped and listed, and a type directory is the type word in lower case, so + ``elements/Character/`` lands in ``ignored_dirs``. Two ids are the same id when they are + written the same: one UUID in capitals and in lower case is two elements. Versions before + 0.145.0 read an extension and a directory name in any case. - A file that is not JSON, not an object, or has no non-empty string ``id`` is skipped, recorded in ``skipped``, and left where it is (§4.1). - A declared ``type`` beats the directory the file sits in; an absent one is @@ -494,7 +499,8 @@ def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder: # By name in code point order (the format's one order), never by Path: a Windows path sorts # case-blind, so a duplicate id would keep a different file there than on Linux or macOS. for tdir in sorted((p for p in base.iterdir() if p.is_dir()), key=lambda p: p.name): - dir_type = tdir.name.lower() + # Names are read as written: a type folder is the type word in lower case, one of the 22. + dir_type = tdir.name if dir_type not in allowed: folder.ignored_dirs.append(tdir) continue @@ -503,6 +509,9 @@ def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder: if path.name.startswith("."): folder.skipped.append(SkippedFile(path, "a dot-prefixed file: a tool's litter, not an element")) continue + if not path.name.endswith(".json"): + folder.skipped.append(SkippedFile(path, "the extension is not .json in lower case: not read")) + continue try: body = _load_json(path) except (ValueError, UnicodeDecodeError) as exc: diff --git a/src/onlyworlds/worldfile.py b/src/onlyworlds/worldfile.py index 2cb53ad..77c5ad7 100644 --- a/src/onlyworlds/worldfile.py +++ b/src/onlyworlds/worldfile.py @@ -76,7 +76,7 @@ from ._casefold import FOLD_RUNS from ._jsonfmt import encode from ._nfc import CLASS_RUNS, DECOMPOSITIONS, EXCLUSIONS -from .folder import ELEMENTS_DIR, LEGACY_SPATIAL_DIR, WORLD_FILE, is_hidden, slugify +from .folder import ELEMENTS_DIR, LEGACY_SPATIAL_DIR, WORLD_FILE, is_hidden, read_folder, slugify __all__ = [ "MARKER_NAME", @@ -835,28 +835,33 @@ def _default_top(world: Mapping[str, Any]) -> str: return f"{slugify(name if isinstance(name, str) else None) or 'world'}-{str(world['id'])[:8]}" -class _Unread: - """An element file the writer could not read as an element.""" - - -_UNREAD = _Unread() - +def _element_files(root: Path) -> dict[str, dict[str, Any]]: + """The folder's element files, path inside the folder -> JSON object: the files this package's + folder reader serves as an element (``read_folder``), and no others. So "read as an element" is + one verdict in the package, the reader's own: a ``.json`` file directly in a type folder of + ``elements/`` or legacy ``spatial/`` that holds one JSON object with a non-empty string ``id``. + An id that two files hold is in neither: the reader serves one and skips the other, and which + of the two marks is the element's cannot be said. + + Every other file under ``elements/`` or ``spatial/`` (``_under_element_folders``) was not read as + an element: not UTF-8, not JSON (a write cut short, or text after the one JSON value), JSON the + reader refuses (nested past its depth, a number it cannot hold), not an object, without an id, + holding an id another file holds too, with another extension, deeper than a type folder or in + a folder that is no type. What such a file holds cannot be told, its hidden mark included.""" + folder = read_folder(root) + twice = {d.id for d in folder.duplicates} | set(folder.in_both_layouts) + return { + el.path.relative_to(root).as_posix(): el.body + for sink in (folder.elements, folder.legacy) + for el in sink.values() + if el.id not in twice + } -def _element_body(rel: str, src: Path) -> dict[str, Any] | _Unread | None: - """What an element file holds (a ``.json`` file directly in a type folder of ``elements/`` or legacy - ``spatial/``): its JSON object. None for a file anywhere else, which is no element file. - ``_UNREAD`` for a file there that could not be read as an element: not UTF-8, not JSON (a write cut - short), JSON this package's reader refuses (nested past its depth, a number it cannot hold), or not an - object. What such a file holds cannot be told, its hidden mark included.""" - segs = rel.split("/") - if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"): - return None - try: - body = _outside_json.loads(src.read_bytes().decode("utf-8-sig")) - except ValueError: # not UTF-8, not JSON, or JSON the reader refuses - return _UNREAD - return body if isinstance(body, dict) else _UNREAD +def _under_element_folders(rel: str) -> bool: + """Whether a path sits under ``elements/`` or legacy ``spatial/``, where a share carries only + what was read as an element.""" + return rel.split("/")[0] in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) #: Which member and which tool wrote an element (a membership id, a door): nothing to someone the @@ -864,14 +869,13 @@ def _element_body(rel: str, src: Path) -> dict[str, Any] | _Unread | None: _AUTHOR_FIELDS: tuple[str, ...] = ("created_by", "changed_by", "changed_via", "changed_client", "doors") -def _without_author_fields(rel: str, src: Path) -> bytes | None: - """An element file (``.json`` directly in a type folder of ``elements/`` or legacy ``spatial/``, - as the TypeScript writer reads one) without its author fields, in the folder's own form - (``_jsonfmt.encode``: two-space indent, a trailing newline, the other keys in their order), or - None when it holds none of them or could not be read as an element: then it travels byte for byte. - Only top-level keys go; an ``x_*`` value that holds one of the names is the extension's, and stays.""" - body = _element_body(rel, src) - if not isinstance(body, dict) or not any(k in body for k in _AUTHOR_FIELDS): +def _without_author_fields(body: dict[str, Any] | None) -> bytes | None: + """An element file's object (``_element_files``) without its author fields, in the folder's own + form (``_jsonfmt.encode``: two-space indent, a trailing newline, the other keys in their order), + or None when it holds none of them or the file was not read as an element (``body`` None): then + it travels byte for byte. Only top-level keys go; an ``x_*`` value that holds one of the names is + the extension's, and stays.""" + if body is None or not any(k in body for k in _AUTHOR_FIELDS): return None return encode({k: v for k, v in body.items() if k not in _AUTHOR_FIELDS}) @@ -907,17 +911,21 @@ def in_private(rel: str) -> bool: return len(segs) > 2 and segs[0] == "records" and _fold_name(segs[1]) in private files = {rel: src for rel, src in files.items() if not in_private(rel)} + # Read only when something is to be left out: a byte copy of everything reads no element file. + elements = {} if include_hidden and include_author_fields else _element_files(root) if not include_hidden: - # A share (§4.8): it carries an element file only when it was read as an element and no mark was - # found. A hidden element's file is left out whole, and so is one that could not be read, listed - # apart; nothing else is rewritten. + # A share (§4.8): it carries a file under elements/ or spatial/ only when it was read as an + # element and no mark was found. A hidden element's file is left out whole, and so is every + # file there that was not read as an element, listed apart; nothing else is rewritten. hidden: list[str] = [] unread: list[str] = [] for rel in sorted(files): - body = _element_body(rel, files[rel]) - if isinstance(body, _Unread): + if not _under_element_folders(rel): + continue + body = elements.get(rel) + if body is None: unread.append(rel) - elif body is not None and is_hidden(body): + elif is_hidden(body): hidden.append(rel) left = {*hidden, *unread} files = {rel: src for rel, src in files.items() if rel not in left} @@ -951,7 +959,7 @@ def in_private(rel: str) -> bool: if rel == WORLD_FILE: plan.append((rel, world_bytes)) continue - bare = None if include_author_fields else _without_author_fields(rel, files[rel]) + bare = None if include_author_fields else _without_author_fields(elements.get(rel)) plan.append((rel, files[rel] if bare is None else bare)) return top, plan @@ -1048,20 +1056,28 @@ def write_world_file( passes, receives each left-out file's path inside the folder (``elements/character/x.json``), sorted, and its length is the count. Nothing else is rewritten: a visible element that links to a hidden one keeps the id, which dangles in the file (a reader meets it as a link to an - element the world does not hold). A share carries a file in a type folder only when it - was read as an element and no mark was found: one that could not be read (not UTF-8 JSON, a - write cut short, nested more than 200 deep, a number that is not finite, not an object) is - left out too, since its mark cannot be told, and ``unread_left_out``, a second list the - caller passes, receives those paths, sorted. They are counted apart: a broken file is one a - person may want to mend. A copy carries such a file byte for byte. + element the world does not hold). A share carries a file under ``elements/`` or ``spatial/`` + only when it was read as an element and no mark was found, and "read as an element" is + the folder reader's own verdict (``read_folder``): a ``.json`` file directly in a type + folder, one JSON object with a non-empty string ``id`` that no other file holds. Every + other file there is left out too, since its mark cannot be told: one that is not UTF-8 + JSON (a write cut short, or text after the one JSON value), nested more than 200 deep, + holding a number that is not finite, not an object, without an id, holding an id another + file holds too (neither of the two travels), with another extension, deeper than a type + folder (a hidden element's file moved into ``old/`` by hand) or in a folder that is no + type. ``unread_left_out``, a second list the caller passes, receives those paths, sorted. + They are counted apart: a file a person may want to mend or move. Versions before 0.145.0 + carried a file with another extension, or one not directly in a type folder, whatever it + held, and judged the other kinds by their own mark alone. A copy carries every such file + byte for byte and never rewrites it. - Author fields are left out: ``created_by``, ``changed_by``, ``changed_via``, ``changed_client`` and ``doors`` record which member and which tool wrote each element (a membership id, a door), which means nothing to someone the world is handed to, so every - element file directly in a type folder of ``elements/`` or ``spatial/`` loses them; + element file (one the folder reader serves, as above) loses them; ``created_at`` and ``updated_at`` stay. A file holding any of them is rewritten without them in the folder's own form (two-space indent, a - trailing newline, the other keys in their order); one holding none, or that is not a JSON - object, travels byte for byte, and nothing outside the element files is touched. + trailing newline, the other keys in their order); one holding none, or that was not read + as an element, travels byte for byte, and nothing outside the element files is touched. ``include_author_fields=True`` carries every element file byte for byte, for an archive of your own folder. - ``world.json`` is carried byte for byte, ``producer``, ``source`` and diff --git a/tests/fixtures/author-fields.fixture.json b/tests/fixtures/author-fields.fixture.json index 4a0358b..a8d6f6f 100644 --- a/tests/fixtures/author-fields.fixture.json +++ b/tests/fixtures/author-fields.fixture.json @@ -32,7 +32,7 @@ "stripped": 0 }, { - "name": "only the fields present are removed, a null one too; an element left with nothing is an empty object", + "name": "only the fields present are removed, a null one too; a file with no id is not read as an element and keeps its bytes", "files": { "world.json": "{\n \"id\": \"0192a000-aaaa-7bbb-8ccc-000000000001\",\n \"name\": \"W\"\n}\n", "elements/location/hall--l1.json": "{\r\n \"id\": \"l1\",\r\n \"name\": \"Hall\",\r\n \"changed_by\": null,\r\n \"doors\": {}\r\n}\r\n", @@ -41,9 +41,9 @@ "default": { "world.json": "{\n \"id\": \"0192a000-aaaa-7bbb-8ccc-000000000001\",\n \"name\": \"W\"\n}\n", "elements/location/hall--l1.json": "{\n \"id\": \"l1\",\n \"name\": \"Hall\"\n}\n", - "elements/event/only--e2.json": "{}\n" + "elements/event/only--e2.json": "{\"created_by\":\"u\",\"doors\":{\"x\":\"2026-10-29T10:00:00Z\"}}" }, - "stripped": 2 + "stripped": 1 }, { "name": "a rewritten file is in the folder's own form: no byte order mark, strings, numbers and nesting as JSON.stringify writes them", @@ -58,7 +58,7 @@ "stripped": 1 }, { - "name": "only element files: elements// and the legacy spatial//, .json in any case; world.json, records, media and every other file byte for byte", + "name": "only element files: a .json file, the extension in lower case, directly in elements// or the legacy spatial//; world.json, records, media and every other file byte for byte", "files": { "world.json": "{\n \"id\": \"0192a000-aaaa-7bbb-8ccc-000000000001\",\n \"name\": \"W\",\n \"created_by\": \"u\"\n}\n", "spatial/pin/p--p1.json": "{\"id\":\"p1\",\"name\":\"P\",\"changed_via\":\"site\"}", @@ -74,7 +74,7 @@ "default": { "world.json": "{\n \"id\": \"0192a000-aaaa-7bbb-8ccc-000000000001\",\n \"name\": \"W\",\n \"created_by\": \"u\"\n}\n", "spatial/pin/p--p1.json": "{\n \"id\": \"p1\",\n \"name\": \"P\"\n}\n", - "elements/map/M--m1.JSON": "{\n \"id\": \"m1\",\n \"name\": \"M\"\n}\n", + "elements/map/M--m1.JSON": "{\"id\":\"m1\",\"name\":\"M\",\"changed_client\":\"atlas\"}", "elements/character/sub/s.json": "{\"id\":\"s\",\"created_by\":\"u\"}", "elements/character/notes.txt": "{\"created_by\":\"u\"}", "elements/character/list.json": "[{\"created_by\":\"u\"}]", @@ -83,7 +83,7 @@ "records/RECORDS.json": "[{\"producer\":\"lab\",\"format\":\"f\",\"version\":\"1\",\"deltas\":false,\"created_by\":\"u\"}]", "records/lab/r.json": "{\"created_by\":\"u\",\"doors\":{}}" }, - "stripped": 2 + "stripped": 1 } ] } diff --git a/tests/test_outside_json.py b/tests/test_outside_json.py index 608cfbb..4189c30 100644 --- a/tests/test_outside_json.py +++ b/tests/test_outside_json.py @@ -127,7 +127,8 @@ def calls(path: Path, module: str) -> int: assert len(files) > 40 # the search saw the package assert {p.name: calls(p, "json") for p in files if calls(p, "json")} == NAMED used = {p.name: calls(p, "_outside_json") for p in files if calls(p, "_outside_json")} - assert used == {"folder.py": 1, "kanka.py": 1, "legendkeeper.py": 2, "lint.py": 1, "worldfile.py": 3} + # worldfile.py: an archive's world.json and a folder's records manifest; folder.py's reader reads its element files. + assert used == {"folder.py": 1, "kanka.py": 1, "legendkeeper.py": 2, "lint.py": 1, "worldfile.py": 2} # --- a writer that must read a file to leave something out ------------------------------------------------ @@ -255,6 +256,26 @@ def test_the_kanka_door_skips_a_file_it_cannot_hold_with_a_note_as_one_that_is_n assert got[1] == [note.replace("(JSONDecodeError)", f"({error})") for note in broken[1]], name +def test_the_kanka_door_text_after_the_one_json_value_is_no_json(tmp_path: Path) -> None: + """Ruled 2026-11-23: a file's text is one JSON value and nothing after it but whitespace.""" + + def with_tail(name: str, tail: str) -> Path: + out = tmp_path / f"{name}.zip" + with zipfile.ZipFile(KANKA) as src, zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as dst: + for info in src.infolist(): + data = src.read(info.filename) + if info.filename == ENTITY: + data = data.decode("utf-8").rstrip().encode() + tail.encode() + dst.writestr(info.filename, data) + return out + + whole = _door(KANKA) + broken = _door(_export_with(tmp_path, "broken", None)) + for n, tail in enumerate([' {"hidden": true}', " x", "{}"]): + assert _door(with_tail(f"tail-{n}", tail)) == broken, tail + assert _door(with_tail("space", " \n\t\r\n")) == whole + + def test_the_kanka_door_writes_no_file_holding_a_number_the_export_does_not(tmp_path: Path) -> None: out = tmp_path / "world" import_kanka(_export_with(tmp_path, "inf", "1e400"), out) diff --git a/tests/test_reader.py b/tests/test_reader.py index 6b90a92..62a99ef 100644 --- a/tests/test_reader.py +++ b/tests/test_reader.py @@ -96,6 +96,9 @@ def test_reader_edges(tmp_path: Path) -> None: _w(tmp_path / "elements" / "character" / "notes.txt", "not json") _w(tmp_path / "elements" / "Species" / "s.json", '{"id": "4", "name": "cased dir"}') _w(tmp_path / "elements" / "banana" / "b.json", '{"id": "5"}') + _w(tmp_path / "elements" / "character" / "UP.JSON", '{"id": "8", "name": "cased extension"}') + _w(tmp_path / "elements" / "trait" / "a.json", '{"id": "ABCDEF00-0000-4000-8000-00000000000A"}') + _w(tmp_path / "elements" / "trait" / "b.json", '{"id": "abcdef00-0000-4000-8000-00000000000a"}') _w(tmp_path / "spatial" / "pin" / "p.json", '{"id": "6", "map_id": "m"}') _w(tmp_path / "spatial" / "pin" / "q.json", '{"id": "1", "type": "pin"}') _w(tmp_path / "spatial" / "character" / "c.json", '{"id": "7"}') @@ -104,12 +107,18 @@ def test_reader_edges(tmp_path: Path) -> None: f = read_folder(tmp_path) assert fingerprint(tmp_path) == before - assert set(f.elements) == {"1", "2", "4"} + # Names are read as written (ruled 2026-11-23): Species/ is no type folder, UP.JSON is skipped by name, + # and one UUID in two spellings is two ids. + spellings = {"ABCDEF00-0000-4000-8000-00000000000A", "abcdef00-0000-4000-8000-00000000000a"} + assert set(f.elements) == {"1", "2"} | spellings + assert "4" not in f.all_elements() and "8" not in f.all_elements() assert f.elements["1"].body["name"] == "first" assert [(d.id, d.ignored.name) for d in f.duplicates] == [("1", "b.json")] - assert f.elements["4"].type == "species" - assert {s.path.name for s in f.skipped} == {"nan.json", "list.json"} - assert {p.name for p in f.ignored_dirs} == {"banana", "character"} + assert {s.path.name for s in f.skipped} == {"nan.json", "list.json", "UP.JSON"} + assert [s.reason for s in f.skipped if s.path.name == "UP.JSON"] == [ + "the extension is not .json in lower case: not read" + ] + assert {p.name for p in f.ignored_dirs} == {"banana", "character", "Species"} assert set(f.legacy) == {"6", "1"} assert f.all_elements()["1"].layout == "elements" # elements/ wins the union assert f.server_world_id == "srv" diff --git a/tests/test_worldfile.py b/tests/test_worldfile.py index e2902df..c630ef5 100644 --- a/tests/test_worldfile.py +++ b/tests/test_worldfile.py @@ -614,29 +614,94 @@ def test_a_hidden_element_travels_byte_for_byte_unless_the_file_is_a_share(tmp_p assert written.read_bytes() == share and again == left and again_unread == unread -def test_only_a_file_directly_in_a_type_folder_is_an_element_for_the_hidden_mark(tmp_path: Path) -> None: - # elements//*.json is the layout (spec §4), as the npm SDK's writer reads it: a marked file one - # level up or deeper is no element, so a share carries it as it is. - files = { - "world.json": world_json(), - "elements/character/cy--c-2.json": encode({"id": "c-2", "name": "Cy", "hidden": True}), - "elements/stray.json": encode({"id": "c-4", "name": "Up", "hidden": True}), - "elements/character/old/cy--c-5.json": encode({"id": "c-5", "name": "Deep", "hidden": True}), - "spatial/pin/extra/p--p-2.json": encode({"id": "p-2", "name": "Deep pin", "hidden": True}), - } - src = make_folder(tmp_path / "w", files) +def _shared(folder: Path) -> tuple[set[str], list[str], list[str]]: + """A share of the folder: the paths it carries beside world.json, the hidden left out, the unread left out.""" left: list[str] = [] - entries = read_world_file(world_file_bytes(src, include_hidden=False, hidden_left_out=left)).entries - assert left == ["elements/character/cy--c-2.json"] - elsewhere = {"elements/stray.json", "elements/character/old/cy--c-5.json", "spatial/pin/extra/p--p-2.json"} - assert elsewhere <= set(entries) + unread: list[str] = [] + data = world_file_bytes(folder, include_hidden=False, hidden_left_out=left, unread_left_out=unread) + return set(read_world_file(data).entries) - {"world.json"}, left, unread + + +def test_a_share_carries_under_the_element_folders_only_what_the_reader_serves(tmp_path: Path) -> None: + """Ruled 2026-11-23: on a share nothing under elements/ or spatial/ travels except a file read as an + element with no mark, and "read as an element" is the folder reader's own verdict. A file that holds + a mark is unread too when the reader does not serve it. The npm SDK's test holds the same list.""" + marked = {"name": "H", "hidden": True, "changed_by": "m-1"} + plain = {"name": "P", "changed_by": "m-1"} + unread: dict[str, bytes] = { + # Cut short, not UTF-8, not an object. + "elements/character/broken.json": b'{"id": "x", "hidden": true', + "elements/character/latin.json": bytes([0x7B, 0x22, 0xE9, 0x22, 0x3A, 0x31, 0x7D]), + "elements/character/list.json": b'[{"hidden": true}]', + # The extension in another spelling, another extension, a swap file. + "spatial/pin/cut.JSON": b'{"id": "p"', + "elements/map/M.JSON": encode({"id": "M", **marked}), + "elements/map/N.JSON": encode({"id": "N", **plain}), + "elements/character/notes.txt": encode({"id": "t", **marked}), + "spatial/pin/notes.txt": encode({"id": "t2", **marked}), + "elements/character/x.json.crswap": encode({"id": "sw", **marked}), + # Deeper than a type folder (a hidden element's file moved into old/ by hand), directly under + # elements/, and in a folder that is no type or no legacy type. + "elements/character/old/s.json": encode({"id": "s", **marked}), + "elements/top.json": encode({"id": "top", **marked}), + "elements/widgets/w.json": encode({"id": "w", **marked}), + "elements/Relation/c.json": encode({"id": "C", **plain}), + "spatial/character/x.json": encode({"id": "sc", **plain}), + # No id: absent, empty, not a string; with a mark and without. + "elements/character/noid-h.json": encode(marked), + "elements/character/noid.json": encode(plain), + "elements/character/empty-id.json": encode({"id": "", **plain}), + "elements/character/number-id.json": encode({"id": 7, **plain}), + # Text after the one JSON value. + "elements/character/two.json": b'{"id": "c-9"} {"hidden": true}', + "elements/character/tail.json": b'{"id": "c-8"} x', + # An id two files hold travels in neither, in either order and across the two layouts. + "elements/event/t1-first.json": encode({"id": "t1", **marked}), + "elements/event/t1-second.json": encode({"id": "t1", **plain}), + "elements/event/t2-first.json": encode({"id": "t2", **plain}), + "elements/event/t2-second.json": encode({"id": "t2", **marked}), + "elements/pin/both.json": encode({"id": "b1", **marked}), + "spatial/pin/both.json": encode({"id": "b1", **plain}), + } + control = {"world.json": world_json(), "elements/character/a.json": encode({"id": "a"})} + whole = make_folder(tmp_path / "whole", {**control, **unread}) + assert _shared(whole) == ({"elements/character/a.json"}, [], sorted(unread)) + # One at a time too, so no file's verdict rests on another's (the pairs go together). + paths = list(unread) + groups = [[p] for p in paths[:20]] + [paths[20:22], paths[22:24], paths[24:26]] + assert sum(len(g) for g in groups) == len(unread) == 26 + for n, group in enumerate(groups): + alone = make_folder(tmp_path / f"alone-{n}", {"world.json": world_json(), **{p: unread[p] for p in group}}) + assert _shared(alone) == (set(), [], sorted(group)), group + # A copy carries each of them byte for byte, and so does one that leaves author fields out: a file + # not read as an element is never rewritten. + for with_authors in (True, False): + copy = read_world_file(world_file_bytes(whole, include_author_fields=with_authors)).entries + assert all(copy[p] == data for p, data in unread.items()), with_authors + assert set(copy) == {*control, *unread} + # Kept: a null mark, a nested mark, whitespace after the value, a byte order mark, hidden: true + # outside the element folders, and one UUID in two spellings, which is two ids, each judged by its own mark. + keep: dict[str, bytes] = { + "elements/character/n.json": encode({"id": "n", "hidden": None}), + "elements/character/deep.json": encode({"id": "d", "x_meta": {"hidden": True}}), + "elements/character/space.json": b'{"id": "sp"} \n\t\r\n', + "elements/character/bom.json": b"\xef\xbb\xbf" + b'{"id": "bom"}', + "elements/trait/lower.json": encode({"id": "abcdef00-0000-4000-8000-00000000000a"}), + "media/m.json": encode({"hidden": True}), + "records/lab/r.json": encode({"hidden": True}), + } + kept = make_folder(tmp_path / "kept", {"world.json": world_json(), **keep}) + assert _shared(kept) == (set(keep), [], []) + upper = "elements/trait/UPPER.json" + (kept / upper).write_bytes(encode({"id": "ABCDEF00-0000-4000-8000-00000000000A", "hidden": True})) + assert _shared(kept) == (set(keep), [upper], []), "another spelling is another id" # --- author fields: which member and which tool wrote each element, left out of a file handed on # The same bytes as the npm SDK's test/fixtures/author-fields.fixture.json (both suites hold its sha256). AUTHOR_FIXTURE = REPO / "tests" / "fixtures" / "author-fields.fixture.json" -AUTHOR_FIXTURE_SHA256 = "ed9e2a6161b0b6b276b71680750943f7ee6fe5d49fdbd932995a1b93555a1e4f" +AUTHOR_FIXTURE_SHA256 = "481db037f008ceff9989bbe44b2c27a41ba4205d7e7fd258792cbadc2365787d" AUTHOR_CASES = 5 AUTHOR_FIELDS = ["created_by", "changed_by", "changed_via", "changed_client", "doors"]