diff --git a/README.md b/README.md index 372fbae3..769f3925 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ This plugin lets you surface pads from an Etherpad instance inside Nextcloud and - Public folder/file share support for `.pad` - Periodic sync from Etherpad into `.pad` snapshots - Pad text is searchable through Nextcloud's full-text search, where that is set up -- Trash deletes on Etherpad (with deferred retry when Etherpad is temporarily unavailable) -- Restore recreates pads from `.pad` snapshot data +- A pad lives as long as its file: the trash keeps it, and it goes once the file is deleted for good +- A `.pad` file whose pad is gone gets a new one from its snapshot: at once when it comes back from the trash, and offered when it is opened ## Screenshots @@ -100,7 +100,7 @@ and configure: - Etherpad API key (OAuth is not required; Etherpad API key auth is used) - Copy content to `.pad` file interval - Which pad types users may create (see below) -- Delete-on-trash policy +- Whether a pad is deleted with its file deleted for good - External public pad policy Two settings control which pad types the app offers, both enabled by default: @@ -235,9 +235,10 @@ existing name asks for confirmation because the previous file is gone for good. ### Trash/Restore -- When a `.pad` file is moved to the Nextcloud trash, the linked Etherpad pad is deleted. -- If Etherpad is temporarily unavailable, delete is deferred and retried. -- When the `.pad` file is restored from the Nextcloud trash, a new pad is recreated and the snapshot from the `.pad` file is replayed. +- A `.pad` file moved to the Nextcloud trash keeps its pad; restored, it has the same pad back, with its history. +- Once the file is deleted for good - from the trash, past it, or with the account that owned it - a background job deletes the pad within minutes, and tries again while Etherpad is unavailable. +- A file restored without a pad - one Etherpad lost, or one trashed under 1.1.0-beta.1 - gets a new pad from the snapshot in the file. +- What each way of deleting a file does to its pad: [docs/deleting-pads.md](docs/deleting-pads.md). ## Troubleshooting @@ -293,6 +294,7 @@ existing name asks for confirmation because the previous file is gone for good. ## Documentation - Architecture: [docs/architecture.md](docs/architecture.md) +- When a pad is deleted: [docs/deleting-pads.md](docs/deleting-pads.md) - API routes: [docs/api-reference.md](docs/api-reference.md) - Etherpad integration details: [docs/etherpad-integration.md](docs/etherpad-integration.md) - `.pad` format: [docs/pad-format.md](docs/pad-format.md) diff --git a/appinfo/info.xml b/appinfo/info.xml index 9671625e..886dd084 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -18,6 +18,9 @@ + + OCA\EtherpadNextcloud\BackgroundJob\GoneFileSweepJob + OCA\EtherpadNextcloud\Migration\RegisterMimeType diff --git a/appinfo/routes.php b/appinfo/routes.php index 64359ec5..146a94ed 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -23,15 +23,12 @@ ['name' => 'padSession#initializeById', 'url' => '/api/v1/pads/initialize-by-id/{fileId}', 'verb' => 'POST'], ['name' => 'padLifecycle#syncStatusById', 'url' => '/api/v1/pads/sync-status/{fileId}', 'verb' => 'GET'], ['name' => 'padLifecycle#syncById', 'url' => '/api/v1/pads/sync/{fileId}', 'verb' => 'POST'], - ['name' => 'padLifecycle#trash', 'url' => '/api/v1/pads/trash', 'verb' => 'POST'], - ['name' => 'padLifecycle#restore', 'url' => '/api/v1/pads/restore', 'verb' => 'POST'], ['name' => 'padLifecycle#recoverByFileId', 'url' => '/api/v1/pads/recover-from-snapshot/{fileId}', 'verb' => 'POST'], ['name' => 'padLifecycle#findOriginalByFileId', 'url' => '/api/v1/pads/find-original/{fileId}', 'verb' => 'GET'], ['name' => 'admin#saveSettings', 'url' => '/api/v1/admin/settings', 'verb' => 'POST'], ['name' => 'admin#healthCheck', 'url' => '/api/v1/admin/health', 'verb' => 'POST'], ['name' => 'admin#consistencyCheck', 'url' => '/api/v1/admin/consistency-check', 'verb' => 'POST'], ['name' => 'admin#settlePending', 'url' => '/api/v1/admin/settle-pending', 'verb' => 'POST'], - ['name' => 'admin#setTestFault', 'url' => '/api/v1/admin/test-fault', 'verb' => 'POST'], ['name' => 'admin#listPadTemplates', 'url' => '/api/v1/admin/templates', 'verb' => 'GET'], ['name' => 'admin#uploadPadTemplate', 'url' => '/api/v1/admin/templates', 'verb' => 'POST'], ['name' => 'admin#deletePadTemplate', 'url' => '/api/v1/admin/templates/delete', 'verb' => 'POST'], diff --git a/docs/api-reference.md b/docs/api-reference.md index 8f43b8c5..33b5f800 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -228,7 +228,8 @@ solely by the separate external-pad policy, not by these two settings. - Controller: `PadLifecycleController::syncById` - Optional query: `force=1` - Result: snapshot sync Etherpad -> `.pad` (`updated` or `unchanged`). - - `force=1` requests an immediate upstream re-check, but unchanged snapshots are still not rewritten. + - `force=1` requests an immediate upstream re-check, but unchanged snapshots are still not rewritten. A pad behind the snapshot whose content differs is written. + - A pad Etherpad made anew in place of the file's - without a single revision, with other text than the file saved - is never written over it: `400` with `code=pad_missing`, as an open answers, and the file keeps its content for `recover-from-snapshot`. - External pads: - Sync uses public text export only (`/export/txt`) based on `pad_url`. - HTML is not imported for external pads. @@ -242,38 +243,23 @@ solely by the separate external-pad policy, not by these two settings. - `status=unavailable` for external pads without safe revision lookup - External pads return `unavailable` because the app intentionally does not keep revision state for remote servers. -- `POST /api/v1/pads/trash` - - Controller: `PadLifecycleController::trash` - - Params: `file=/path/file.pad` - - Result: - - `200` with `status=trashed` for successful trash flow. - - includes `snapshot_persisted` (`true|false`): whether the file holds the pad's current content - written now, or there already when the file's `snapshot_rev` is the pad's revision count. `false` when no fresh snapshot was written: the file was locked or could not be read, Etherpad did not answer, the pad is behind the file's snapshot (not the pad the file knew), the pad changed right after its snapshot was written, or the file's restore was still undecided, which leaves the pad alone. Also `false` when the snapshot was written but Etherpad gave no count after it: whether an edit came while it was written is not known, so the file is not taken to hold the current content. - - includes `delete_pending` (`true|false`): `true` when the pad is kept and its deletion owed, always the case when no fresh snapshot was written. The background sweep then writes the snapshot into the trashed file and deletes the pad, usually within five minutes. - - `409` with `status=skipped` + `reason` on invalid lifecycle state (for example already pending delete). - - includes transition-race guard reason `binding_state_transition_conflict` on concurrent state updates. - -- `POST /api/v1/pads/restore` - - Controller: `PadLifecycleController::restore` - - Params: `file=/path/file.pad` - - Result: - - `200` with `status=restored` for successful restore flow. - - `409` with `status=skipped` + `reason` on invalid lifecycle state. - - includes transition-race guard reason `binding_state_transition_conflict` on concurrent state updates. - - `POST /api/v1/pads/recover-from-snapshot/{fileId}` - Controller: `PadLifecycleController::recoverByFileId` - - Purpose: manual recovery entry point for `.pad` files that ended up without a binding row (WebDAV backup restore, `occ files:scan`, direct DB intervention, file copy). Reuses the same "frontmatter → fresh pad" path as `NodeRestoredEvent` but is guarded so it refuses when a binding row already exists. + - Purpose: manual recovery entry point for `.pad` files that ended up without a binding row (WebDAV backup restore, `occ files:scan`, direct DB intervention, file copy), and for a file whose active row names a pad Etherpad has lost (`pad_missing`). Reuses the paths a restore from the trash takes: "frontmatter → fresh pad" for a file without a row, the replacement of a pad that is gone for the other, which moves the row onto the new pad. Etherpad is asked again here whether the pad is lost. - Result: - `200` with `status=restored`, `old_pad_id`, `new_pad_id` on success. Always provisions a fresh pad — `pad_id` from frontmatter is never reused. + - `403` with `message` when the user may not change the file, a read-only share say: a recovery writes the file. Refused before Etherpad is asked. - `409` with `status=skipped` + `reason=external_pad` for external (`ext.*`) frontmatter; recovery doesn't apply there. - - `409` with `message` and the `PadAlreadyHasBindingException` mapping if a binding row already exists for the file. + - `409` with `status=skipped` + `reason=file_moved` or `reason=file_changed` when the file moved, or was written, while the new pad was seeded: the new pad is let go, nothing is written, and a retry starts from what the file holds then. + - `409` with `message` and the `PadAlreadyHasBindingException` mapping if the file has a row and its pad is not lost: Etherpad has it, the row waits, or it names another pad than the file. + - `503` with `retryable` when Etherpad does not answer. - `GET /api/v1/pads/find-original/{fileId}` - Controller: `PadLifecycleController::findOriginalByFileId` - Purpose: look up whether the orphan's frontmatter `pad_id` is bound to another `.pad` the requester can read. Used by the recovery UI to offer "Open the original" when a copy is detected. - Result: - `200` with `{ found: true, file_id, path, viewer_url }` when the lookup hits **and** the bound file is readable by the requester. - - `200` with `{ found: false }` for every miss path (no row, ext.* pad id, trashed/pending-delete binding, binding for a file not addressable in the requester's userspace, unparseable frontmatter, orphan itself not readable, self-loop). Payload shape and status are intentionally identical so the endpoint cannot be used to probe for binding rows that belong to other users. + - `200` with `{ found: false }` for every miss path (no row, ext.* pad id, a binding whose file was deleted for good (`pending_delete`), binding for a file not addressable in the requester's userspace, unparseable frontmatter, orphan itself not readable, self-loop). Payload shape and status are intentionally identical so the endpoint cannot be used to probe for binding rows that belong to other users. - `POST /api/v1/admin/settings` - Controller: `AdminController::saveSettings` @@ -281,7 +267,7 @@ solely by the separate external-pad policy, not by these two settings. - Stores Etherpad and security settings, including: - `etherpad_host` (public/browser base URL) - `etherpad_api_host` (optional internal API URL; fallback to `etherpad_host`) - - `delete_on_trash` (`yes|no`) + - `delete_pad_with_file` (`yes|no`) - Result includes `checks` with the single `protected_pads` line, recomputed from the saved values in the same shape the health check uses — so the settings page refreshes that verdict without a separate connection test, @@ -299,10 +285,8 @@ solely by the separate external-pad policy, not by these two settings. - `api_version` - `latency_ms` - `target` - - `pending_delete_count` — pads a trash kept, their deletion owed until - the sweep finishes it or the file is restored - - `restore_pending_count` — restored files whose pad Etherpad could not - confirm or deny + - `pending_delete_count` — files deleted for good whose pads the sweep + has yet to delete - `session_cookie_release` — the Etherpad release the open path is going by, which can differ from the one this run probed - `checks` — one entry per verified part, so a failure points at the field @@ -390,41 +374,25 @@ solely by the separate external-pad policy, not by these two settings. - `POST /api/v1/admin/consistency-check` - Controller: `AdminController::consistencyCheck` - Auth: admin only - - Purpose: optional structural integrity check across binding table and `.pad` files. - - Result includes: - - `binding_without_file_count` - - `file_without_binding_count` - - `invalid_frontmatter_count` - - `frontmatter_scanned` - - `frontmatter_skipped` - - `samples` (bounded debug sample lists per issue class) + - Purpose: optional check of the binding table against the file cache (`docs/architecture.md`, "Admin Integrity Check"). + - Result: + - `vanished_file_count`: rows whose file the file cache has nothing of, still active and never seen deleted for good, whose pads the app leaves in place; `message` says the check found issues when there are any + - `samples.vanished_files` (`file_id`, `pad_id`, `access_mode`), up to 25 + - Rows seen deleted for good are not counted: they are on their way (`pending_delete_count` in the health check). - `POST /api/v1/admin/settle-pending` - Controller: `AdminController::settlePending` - Auth: admin only - - Purpose: an immediate run of what the background jobs do for waiting rows - (`restore_pending` and `pending_delete`), within the same time budget. The - only file it writes is a trashed one, with the snapshot its trash could - not take; the only pads it deletes are those of files in a trash or - gone for good. + - Purpose: an immediate run of the sweep of files gone for good + (`docs/architecture.md`, "Files gone for good"), within the budget its + job has, and without waiting out the five minutes a file seen deleted + for good waits before its pad goes, nor the hour after Etherpad refused + to delete one. It deletes only the pads of files deleted for good, and + writes no file. With `delete_pad_with_file` off it deletes nothing, + and `message` says so. - Result: - - `checked`, `settled` - - `pending_delete_count`, `restore_pending_count`: what is left, named as in the health check - -- `POST /api/v1/admin/test-fault` - - Controller: `AdminController::setTestFault` - - Auth: admin only - - Availability: only when Nextcloud `debug` mode is enabled - - Params: - - `fault` (string, optional; empty clears active fault) - - Purpose: deterministic E2E fault injection for lifecycle error-path testing. - - Supported fault values: - - `trash_read_lock` - - `trash_write_lock` - - `trash_write_fail` - - `restore_read_lock` - - `restore_write_lock` - - `restore_write_fail` + - `checked`: rows of files deleted for good it took; `settled`: pads it deleted, with their rows + - `pending_delete_count`: what is left, named as in the health check ## Important Response Fields @@ -438,7 +406,7 @@ solely by the separate external-pad policy, not by these two settings. - `sync_status_url` (open/open-by-id): endpoint for revision-based sync status in viewer. - `code` (errors): stable identifier on selected error responses. Branch on this, never on `message` — messages are written for people and are translated, save the reason a pad on another server could not be linked or read, which comes in English. The full set: - `missing_binding` (`MissingBindingException`) — the viewer and embed swap the dead-end error for the recovery UI (`POST /api/v1/pads/recover-from-snapshot/{fileId}` + optional `GET /api/v1/pads/find-original/{fileId}` lookup). - - `waiting_binding` (`WaitingBindingException`) — `409` with `retryable: true`; the file's row still waits. An open decides such a row itself first, so there it means the open did not: the row was touched within the last minute (by the sweep, a trash, or an earlier open), someone else was deciding it, Etherpad gave no answer within a few seconds, what was left of a pad that is gone could not be removed in time, or deciding failed, the database gone say, which is logged. Try again later: once the row is settled the same request opens the pad, or answers `missing_binding` when the pad had to be let go. On open, sync, sync status and the read-only content view, signed in and public. + - `pad_missing` (`PadLostException`) — the file's row names a pad Etherpad has lost: it has none under that id (a protected pad, or a public one whose file holds saved content), or one with no revision and other text than the file saved (a public pad Etherpad made anew, with its default text, when someone visited its address). Only an open that may write asks, once per open; a sync answers it too, for a pad made anew, rather than write that pad over the file. The viewer and embed show the recovery UI without the original-file lookup; `POST /api/v1/pads/recover-from-snapshot/{fileId}` makes a new pad from the file's content and moves the row onto it. - `missing_frontmatter` (`MissingFrontmatterException`) — the file has no pad metadata yet; clients call `POST /api/v1/pads/initialize-by-id/{fileId}` once and retry the open. A file whose content is neither metadata nor a legacy shortcut cannot be initialised and is refused *without* this code. - `pad_too_large` (`EtherpadTooLargeException`) — the pad is past the 5 MiB preview ceiling; it stays editable in Etherpad. - `pad_file_changed` (`PadFileChangedException`) — the file changed while its pad was being created or initialised; try again. On create, a file may now exist under that name, and the retry says so. @@ -446,7 +414,7 @@ solely by the separate external-pad policy, not by these two settings. - `legacy_collision_no_access` (`LegacyPadCollisionException`) — see the legacy migration section. - `legacy_protected_import_disabled` (`LegacyProtectedImportDisabledException`) — `403`; the legacy `.pad` names a group pad and this instance does not import those. The file is left untouched, so the same open succeeds once an admin switches the import back on. See the legacy migration section. - The answers of a public share (`/api/v1/public/...`) carry the codes that can come up there - `waiting_binding` and `pad_too_large` - but not `missing_binding` or `missing_frontmatter`: what a client does on those needs a signed-in user. Their messages are translated, one sentence for each kind of trouble. + The answers of a public share (`/api/v1/public/...`) carry the code that can come up there - `pad_too_large` - but not `missing_binding`, `pad_missing` or `missing_frontmatter`: what a client does on those needs a signed-in user. Their messages are translated, one sentence for each kind of trouble. A response without a `code` may still be machine-readable through its HTTP status and other documented fields — a locked `.pad` answers `503` with `retryable: true`, signed in and public alike, for instance, and so does a request this instance's Etherpad could not be reached for. Every error this app answers is JSON, it never answers `502` or `504`, and every `503` of its own carries `retryable: true`; what the clients make of a 5xx that is none of these is in `docs/architecture.md` ("Errors of the API"). A file's row that another request made first (`BindingNotCreatedException`, two initialisations at once, say) answers `400` with `retryable: true` too: the next open finds that request's pad. The create endpoints answer it with their own sentence and neither field. One Etherpad answered and refused answers `400` without it: trying again gives the same answer. What is never a stable identifier is the `message` text. @@ -472,14 +440,14 @@ solely by the separate external-pad policy, not by these two settings. - prefers `POST /api/v1/pads/open-by-id` (`fileId`, requesttoken). - falls back to `POST /api/v1/pads/open` (`file`, requesttoken) only without `fileId`. - if open fails with missing frontmatter, calls `POST /api/v1/pads/initialize*` and retries open once. - - if open fails with `code=missing_binding`, renders a recovery card with an optional `GET /api/v1/pads/find-original/{fileId}` lookup and a `POST /api/v1/pads/recover-from-snapshot/{fileId}` action. + - if open fails with `code=missing_binding`, renders a recovery card with an optional `GET /api/v1/pads/find-original/{fileId}` lookup and a `POST /api/v1/pads/recover-from-snapshot/{fileId}` action; with `code=pad_missing`, the same card without the lookup. - offers "Try again" where the open may work later (`docs/architecture.md`, "Errors of the API"). - uses `POST /api/v1/pads/sync/{fileId}` periodically and on unload. - `src/embed-main.js` - powers the minimal `/embed/by-id/{fileId}` page. - uses same-origin `POST /api/v1/pads/open-by-id`. - if open fails with missing frontmatter, calls `POST /api/v1/pads/initialize-by-id/{fileId}` and retries once. - - if open fails with `code=missing_binding`, renders the same recovery flow as the inline viewer (lookup + recover). + - if open fails with `code=missing_binding` or `pad_missing`, renders the same recovery flow as the inline viewer. - offers "Try again" on its error panel where the open may work later, as the viewer does. - sets the returned `response.url` directly on the internal iframe. - uses the returned `sync_url` / `sync_interval_seconds` to trigger the same snapshot sync contract as the native viewer. @@ -503,24 +471,10 @@ solely by the separate external-pad policy, not by these two settings. ## Test Scripts - `tests/integration/e2e-pad-flow.sh` - - happy path: create -> open -> trash -> restore -> open + - happy path: create -> open -> open again - `tests/integration/e2e-sync-failure.sh` - failure path: create -> sync(force=1) must fail with non-2xx when Etherpad is down - goal: no silent best-effort success on critical sync -- `tests/integration/e2e-lifecycle-state-guards.sh` - - state guards: restore(active) and trash(pending_delete) must return `409 status=skipped` -- `tests/integration/e2e-lifecycle-trash-failure.sh` - - deferred-delete path: create -> trash remains `200` with `delete_pending=true` when Etherpad is down - - post-condition: trash-again must return `409 status=skipped` (`binding_not_active`) -- `tests/integration/e2e-lifecycle-restore-failure.sh` - - failure path: create -> trash -> restore must fail with non-2xx when Etherpad is down - - post-condition: trash-again must return `409 status=skipped` (`binding_not_active`) -- `tests/integration/e2e-lifecycle-trash-lock-tolerant.sh` - - lock path: inject `trash_write_lock`, trash must stay `200` and return `snapshot_persisted=false` - - post-condition: restore still succeeds after fault is cleared -- `tests/integration/e2e-lifecycle-restore-write-failure.sh` - - write-failure path: inject `restore_write_fail`, restore must fail non-2xx - - post-condition: restore succeeds after fault is cleared - `tests/integration/e2e-public-share-folder.sh` - folder share: viewer/open/download/reopen + DAV-style `file` parameter + route switch - `tests/integration/e2e-public-share-single-file.sh` @@ -539,10 +493,11 @@ Registered in `lib/AppInfo/Application.php`. - `OCP\Files\Template\FileCreatedFromTemplateEvent` -> `FileCreatedFromTemplateListener` - `OCA\Viewer\Event\LoadViewer` -> `LoadViewerListener` - `OCP\User\Events\UserLoggedOutEvent` -> `UserLoggedOutListener` -- `OCA\Files_Trashbin\Events\MoveToTrashEvent` -> `MoveToTrashListener` -- legacy event `OCA\Files_Trashbin::moveToTrash` -> `MoveToTrashListener` +- `OCP\User\Events\BeforeUserDeletedEvent` -> `RevokeSessionsOnAccountDeleteListener` (the account's sessions, as on a logout) - `OCA\Files_Trashbin\Events\NodeRestoredEvent` -> `RestoreFromTrashListener` - legacy hook `\OCA\Files_Trashbin\Trashbin::post_restore` -> `TrashbinHookHandler::postRestore` -> `RestoreFromTrashListener::handleLegacyHook` +- `OCP\Files\Cache\CacheEntryRemovedEvent`, `OCP\Files\Cache\CacheEntryInsertedEvent`, `OCP\Files\Cache\CacheEntriesRemovedEvent` (from 34, priority 100), `OCP\Files\Events\Node\BeforeNodeDeletedEvent`, `OCP\Files\Events\Node\NodeDeletedEvent`, `OCP\Files\Events\NodeRemovedFromCache` (what `occ files:scan` drops), the event named `\OCP\Files::postDelete` (an `OCP\EventDispatcher\GenericEvent`), `OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent`, `OCA\Files_Trashbin\Events\NodeRestoredEvent`, `OCP\User\Events\BeforeUserDeletedEvent`, `OCP\User\Events\UserDeletedEvent` -> `GoneFilesListener` (the marks of files deleted for good; `docs/architecture.md`, "Files gone for good") +- `OCP\Files\Events\Node\BeforeNodeDeletedEvent`, `OCP\Files\Events\Node\NodeDeletedEvent` -> `RevokeSessionsOnDeleteListener` (the sessions of the protected pads a delete takes along; `docs/architecture.md`, "Trash/Restore") ## App Config Keys @@ -555,7 +510,7 @@ Registered in `lib/AppInfo/Application.php`. - derived from `etherpad_host` - IP/invalid hosts -> empty domain attribute - recommendation: set explicitly for complex proxy/subdomain setups -- `delete_on_trash` (`yes|no`, default `yes`) +- `delete_pad_with_file` (`yes|no`, default `yes`) — whether the pad of a `.pad` file deleted for good is deleted (`docs/deleting-pads.md`); `delete_on_trash` before, taken over on upgrade - `sync_interval_seconds` (default `120`, clamp `5..3600`) - `allow_external_pads` (`yes|no`, default `no`) - `allow_legacy_protected_import` (`yes|no`, default `no`) — whether a legacy Ownpad `.pad` naming a group pad may bring that pad in. Turn on only where this Nextcloud is the only thing creating group pads on the Etherpad server; see the legacy migration doc. @@ -565,4 +520,3 @@ Registered in `lib/AppInfo/Application.php`. - `/embed/by-id/{fileId}` - `/embed/create-by-parent/{parentFolderId}` - when empty, no external embedding origin is added beyond `'self'` -- `test_fault` (debug-only E2E fault injection; empty by default) diff --git a/docs/architecture.md b/docs/architecture.md index 7f009b5d..46a3b496 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -11,26 +11,15 @@ Etherpad is the editing source of truth; the `.pad` file acts as binding storage - `lib/Service/BindingService.php` - Manages the central DB table `ep_pad_bindings`. - - Owns mapping `file_id <-> pad_id` and states (`active`, `pending_delete`, `restore_pending`). - - Hands a row out as a `Binding`, and a row the sweep takes as a `WaitingBinding` with its file's path; the sweep asks for deletions owed by `FileLocation`. + - Owns mapping `file_id <-> pad_id` and states (`active`, and `pending_delete` for a file deleted for good whose pad has yet to go). + - Hands a row out as a `Binding`. - Only managed internal pads are bound. External pads are represented solely by `.pad` frontmatter and snapshots. -- `lib/Service/LifecycleService.php` - - Where a `.pad` file's trash and restore arrive, from the listeners and the API; the trash is done here (see Trash/Restore). - `lib/Service/RestoreService.php` - - The restore: from the trash, in the sweep, and for a file without a row (see Trash/Restore). -- `lib/Service/TrashSnapshotWriter.php` - - The snapshot into a trashed file, at trash time and in the sweep, made by `TrashSnapshotWriters`: one file, one pad, and the reason when it does not get there (`TrashSnapshotMiss`). What a miss means for the row and the pad is its caller's. -- `lib/Service/PendingBindingService.php` - - The sweep: settles rows that wait, by where their file is now, each under its `SettleLock`, bounded per run by `RunBudget` (see Trash/Restore). It writes only into trashed files, and deletes only the pads of files in a trash or gone for good. -- `lib/Service/OwedDeletions.php` - - The deletions a trash owed, for the sweep: a trashed file's snapshot, then row and pad; for a file gone for good, pad and row. -- `lib/Service/SettleOnOpen.php` - - An open, signed in or through a public share, that finds its file's row waiting decides the row itself first, as the sweep would (see Trash/Restore). -- `lib/BackgroundJob/*PendingDeleteRetryJob.php` - - Bucketed runs of `PendingBindingService`: `restore_pending` rows aged by `updated_at`, `pending_delete` rows by `deleted_at`. Named for what they did first; the job list stores the class name. - - hot rows: every 5 minutes for the first hour - - warm rows: hourly from 1h to 24h - - cold rows: daily after 24h + - A pad from the file's own snapshot where the file has none: back from the trash without a row, or with a pad Etherpad lost (`RestoreFromTrashListener`), and the recovery an open offers (`PadLifecycleController`; see Trash/Restore). +- `lib/Listeners/GoneFilesListener.php` + - Marks the rows of files deleted for good (see "Files gone for good"). +- `lib/Service/GoneFileSweep.php`, `lib/BackgroundJob/GoneFileSweepJob.php` + - Every five minutes, deletes the pads of files deleted for good (see "Files gone for good"). - `lib/Service/EtherpadClient.php` - Adapter for Etherpad HTTP API (pad create/delete/session/read-only/export). - `lib/Service/PadFileService.php` @@ -43,10 +32,7 @@ Etherpad is the editing source of truth; the `.pad` file acts as binding storage - Guards creation only; existing pads of a disabled type keep working. - Resolves a template's access mode to an enabled one instead of failing. - `lib/Service/ConsistencyCheckService.php` - - Optional admin integrity scan: - - bindings without file - - `.pad` files without binding - - invalid/mismatching frontmatter on bound files + - Optional admin integrity scan: rows whose file is gone, and among them the vanished ones (see "Admin Integrity Check"). - `lib/Controller/ViewerController.php` - Compatibility redirect adapter: - resolves `.pad` path/id to stable Nextcloud files viewer URL. @@ -82,10 +68,10 @@ checked-in runtime assets in `js/`. - `file_id` - `pad_id` - `access_mode` - - `state` - - `deleted_at` + - `state`: `active`, or `pending_delete` once the file was seen deleted for good (see "Files gone for good") + - `deleted_at`: when the file was seen deleted for good; set only in `pending_delete` - `created_at` - - `updated_at` + - `updated_at`: the last change, and for a row in `pending_delete` the last try at its pad - stores internal managed pads only; external `ext.*` rows from earlier development versions are removed by `Version000003Date20260512230000` - `.pad` file - Frontmatter: format, binding metadata, state, export metadata. @@ -94,7 +80,7 @@ checked-in runtime assets in `js/`. - Snapshot helpers - `PadFileService::withExportSnapshot(...)` constructs updated `.pad` content for snapshot writes. - `PadFileLockRetryService::putContentWithSyncLockRetry(...)` persists that content to the Nextcloud file. - - Stored snapshots are read only by restore and by the forced-sync comparison; the read-only viewer no longer uses them at all (see `LivePadHtmlFetcher`). + - Stored snapshots are read by restore, by the forced-sync comparison, and by an open that may write and the sync to tell whether Etherpad has lost the pad (`ManagedPadLifecycle::howLost()`, `isMadeAnew()`); the read-only viewer no longer uses them at all (see `LivePadHtmlFetcher`). ## Main Flows @@ -120,6 +106,15 @@ Primary flow (native viewer): - `public`: direct/read-only URL as appropriate 4. For protected pads, response includes one Etherpad session `Set-Cookie` header. 5. Legacy app routes (`/apps/etherpad_nextcloud`, `/by-id/{fileId}`) redirect into the same native files viewer URL. +6. An open that may write asks Etherpad whether it has lost the pad (`ManagedPadLifecycle::howLost()`), before any address or session. Each question waits three seconds at most - the revision count, and for a pad at revision 0 its text - so a slow Etherpad costs an open seconds, not the client's full timeout; a public pad needed no call to Etherpad to open before: + - Lost is no pad under that id - for a protected pad, whose session would open nothing, or for a public pad whose file holds saved content: a snapshot past a pad's first revision (`snapshot_rev` above 0), or any text - a file made from a template by 1.1.0-beta.1 holds its content at `snapshot_rev: 0` - or one without a single revision while the file holds saved content, whose text is not the text the file saved: a public pad is reachable by its address, and Etherpad makes it anew when someone visits it, with its default text and the visitor as its author. A pad at revision 0 holding the saved text had its history cut short in Etherpad, and is not lost; one an admin made anew through the API with other text counts as made anew, and the recovery leaves it in place. So is a pad whose history was cut short after edits that never reached the file: it cannot be told from one made anew, so an open offers a new pad from the file and a restore makes one at once, while the pad with the newer text stays in Etherpad, its id in the log. Cutting a pad's history to revision 0 does not suit the file's revision count anyway: the sync goes by it. A public pad with nothing saved in its file, an Ownpad link to a pad nobody opened yet say, Etherpad makes on the first visit as ever. A pad merely behind the snapshot is not lost, since files a restore in 1.1.0-beta.1 left kept the old pad's revision count. Every way that seeds a new pad with content - a restore, a recovery, a pad made from a template - records the revisions seeding left as the file's `snapshot_rev` (`ManagedPadLifecycle::seed()`), so such a file counts as holding saved content from the start, before its first sync. + - Only a definite answer stops the open (`ManagedPadLifecycle::isKnownLost()`): Etherpad slow, silent or refusing the question opens the pad as before, with a line at `debug`, and whatever is wrong with Etherpad shows there; any other fault of the check itself opens it too, with a line at `warning`, since the check is then not doing its job. A public pad whose file holds nothing saved is not asked about at all: it cannot be lost. + - A lost pad answers `pad_missing` (`PadLostException`); the viewer and the embed page offer to make a new pad from the file's content (`POST /api/v1/pads/recover-from-snapshot/{fileId}`). That asks Etherpad again and takes the path a restore takes for a row whose pad is gone (`RestoreService::recoverFromSnapshot()` → `replaceLostPad()` → `restoreOntoNewPad()`): a new pad from the snapshot, the row moved onto it, the file naming it. The lost pad, or the empty one Etherpad made anew, is left alone. No other way of making a pad is added. + - A reader, who could not make a new pad, is not asked, and is shown what the pad server has. A public share that may write answers the same, without the code: only the file's owner can make the new pad. The endpoint refuses whoever may not change the file with `403`, before Etherpad is asked. + - What a replacement that fails leaves behind: "The replacement" under Trash/Restore. + - Nor does a sync write a pad Etherpad made anew over the file: one without a single revision, with other text than the file saved, is refused with `pad_missing` (see "Sync"), and the file keeps its content for the new pad. Once someone writes into the pad made anew, a viewer already open when Etherpad lost the pad syncs on leaving as ever, and writes what Etherpad then has into the file: a pad holding a revision cannot be told from one merely behind the snapshot. + - An older version of the file still names the lost pad, and opening it after the recovery is refused as a mismatch. + - Logged once a minute for each file (`ApiErrorLog`), as a refusal is. ### 2b) Open (trusted embed integration) @@ -221,7 +216,9 @@ Primary flow (native viewer): 3. `PadLifecycleController::syncById` fetches revision state from Etherpad. 4. `.pad` snapshot is updated only when the upstream snapshot actually differs. - `force=1` requests an immediate upstream re-check, but unchanged snapshots are still not rewritten. + - A forced sync writes a pad behind the snapshot too when its content differs: files a restore in 1.1.0-beta.1 left kept the old pad's revision count, and only this brings them up to date. Not a pad Etherpad made anew in place of the file's - without a single revision, with other text than the file saved (`ManagedPadLifecycle::isMadeAnew()`, the rule the open goes by): its default text written over the file would leave the saved content to the file's versions, and the open would no longer find the pad lost and offer a new pad from the file. The sync answers `pad_missing` instead, as the open does, and writes nothing. - Snapshot writes are built via `PadFileService::withExportSnapshot(...)` and persisted via `PadFileLockRetryService::putContentWithSyncLockRetry(...)`. + - Right before each write of a pad's snapshot - the ones after a wait for the file's lock too - its row is asked again (`BindingService::assertConsistentMapping()`, through `PadFileLockRetryService::putContentWithSyncLockRetry()`): a recovery may have moved it onto a new pad and written the file for it while Etherpad was asked, or while the sync waited, and the old pad's text written over that would leave file and row naming two pads. 5. External pads are synced as text only (no HTML import). - They are selected by `.pad` frontmatter, not by `ep_pad_bindings`. 6. Write-lock handling: @@ -234,53 +231,55 @@ Primary flow (native viewer): ### 5) Trash/Restore -- When the pad's step fails - an exception, the database gone, say - the file operation stops only while stopping still protects something. A trash is decided before the file moves (`MoveToTrashEvent`), so such a failure stops the delete and the file stays where it was; a pad Etherpad cannot delete is not one, its deletion is owed instead (see below). A restore is heard of after the file is back, so a failure there is logged, and the sweep or the file's own recovery takes up the pad. -- Trash: write a fresh snapshot into the file, then delete the managed Etherpad pad and the binding row. A file that already holds the pad's revision is not written again. A snapshot is never older than the file's: a pad behind the file's `snapshot_rev` (created again under its id, or back from an older backup) is not written into it, and its deletion is owed, for the sweep's rule on such a pad. After a write the pad is counted once more; if it moved on while the file was written, it is not deleted, and the sweep writes another snapshot. Etherpad cannot hold a pad still, so an edit in the moment between that count and the delete is still lost; the count keeps the write, the slowest step, out of that moment. -- A file that cannot be read, for any reason, is one more way to have no fresh snapshot: the user's delete goes through. -- No fresh snapshot, or the delete fails: the pad stays as it is and the row becomes `pending_delete`; Nextcloud's trash succeeds either way. A protected pad whose group Etherpad cannot list counts as a delete that failed, so the sweep asks once more; past the row it has taken by then, a group it still cannot list is given up and the pad goes alone. A delete through WebDAV (Files UI, clients) holds the file's lock while the trash is decided, so there it is always this path. The sweep finishes the trash on its next run, usually within five minutes: the pad's content goes into the trashed file, then row and pad go (see below). Until then a public pad stays reachable by its URL, a restore takes the pad back, and the admin page counts it as a pending delete. -- Restore without a binding row: provision a new pad from `.pad` frontmatter/snapshot. -- Restore of a waiting row (`pending_delete` or `restore_pending`), whatever `delete_on_trash` says now: read the file's `snapshot_rev`, then ask Etherpad about the row's pad. The pad id comes from the row, never from the file. - - It exists with at least that many revisions: the row becomes `active` again on that same pad, which may hold edits the snapshot missed. If the sweep took row and pad in the meantime, finishing the trash, the restore finds no row when it reads again and makes a new pad from the file, which holds the snapshot the sweep wrote first. - - Etherpad answers that it does not exist, or it has fewer revisions (created again since, or back from an older backup): a new pad from the file's snapshot, and the file records the new pad's revision count. A pad with fewer revisions is left in place and logged before anything else is tried; whoever wrote into it has only that copy. Of a pad that does not exist, what is left - an empty group - goes. - - Of two restores that race for one file only one writes it, and a restore that fails takes back what it made (`RestoreService::restoreOntoNewPad`). - - Reading the file, asking Etherpad, and seeding a new pad take a while. Through WebDAV the file stays locked meanwhile, and a delete is refused (423, measured against NC 34.0.3); without that lock - file locking switched off, or a way in that takes none - the file can be deleted again, and its trash leaves a row that waits as it is. So the row is changed, and a new pad claimed, only while the file is still where it was - also when it could not be read: moved, and the row is left to its trash (`file_moved`), and a new pad let go. - - That leaves the moment between the claim and the write, which follow each other directly. A delete of the file there holds the file's lock, so the write fails. Usually the rollback takes the row and the new pad back before the delete's trash gets to the row; the file then goes to the trash without a row, and a later restore makes a pad from its snapshot. Should the trash owe the row first, row and new pad stay with it, and the sweep holds the new pad to the file's snapshot revision - still the old pad's - as it holds any pad it deletes. A new pad with fewer revisions, the usual case, is behind: the row goes, and the pad is left in place, logged with its id. One with as many goes with the row; one with more - a file that records no revision - has its content written into the file first. Nothing is lost either way: the new pad was seeded from the file. A trash that knew the new pad for the file's own copy belongs to the repair path. - - No answer, or the file cannot be read: `restore_pending`, and neither pad nor file is touched. A row that waits again moves to the back of the queue (`updated_at`). -- A restore whose pad's step fails still restores the file, with its versions and without its trash entry; the failure goes no further than the log. A pad left unrestored shows there as one of these lines: - - `Could not restore the pad of a file back from the trash. The file itself is restored.` at `error`, once for each way in that fails, `via` naming it (`hook` or `event`). A core restore passes twice (see Event Integration), so a line from the hook can be followed by an event pass that restored the pad after all. +- A trash leaves the pad as it is: the file keeps its row, active, and its pad, until the file is deleted for good (see "Files gone for good"). Nothing is written into the file. A public pad stays reachable by its address. A file in the trash is not synced, so its snapshot is the one from before the trash; while the pad lives, the pad holds the current content, and a restore brings it back. What each way of deleting a file does to its pad: [deleting-pads.md](deleting-pads.md). +- A delete - to the trash, or past it - takes the sessions of the protected pads it takes along (`RevokeSessionsOnDeleteListener`): a file's own row, or every active protected row under a folder, found before the delete (`BeforeNodeDeletedEvent`) by walking down the file cache's `parent` index one level at a time (`ProtectedPadsOfNode`), whatever the files are called - no walk at all when the instance has no active protected pad (an index on state and access mode answers that). The walk runs in the delete's request and stops past 100 pads or at 10,000 folders, with an `info` line: more than a delete can take the sessions of. Its queries are bounded too, so a folder with a hundred thousand others in it reads no more than the walk has room for. The sessions go once the delete is done (`NodeDeletedEvent`): one that fails, a file locked by a sync say, takes none. For each group, `PadSessionRevoker::revokeForPads()` lists its sessions first - most groups hold none that live, and then nothing else is asked - and takes the live ones only when the group holds that pad alone, or nothing (`ManagedPadLifecycle::groupHoldsOnly()`, the rule a pad's deletion goes by; all of a group's pads leaving together count as that): a legacy `.pad` may name someone else's group (see "Removing a pad" in `docs/etherpad-integration.md`). Group by group: a group's sessions go before the next group is asked, so a slow Etherpad spends the budget on the first group's deletes, not on listing them all. Within two seconds, as on a logout, and 100 deletes, the newest first: every open makes a session, so a pad opened often holds more than a cookie can, and the newest are those of whoever is at it now, and the last to expire. What does not fit expires on its own, and Etherpad refuses the next change of whoever had the pad open. A restore gives nothing back: the next open makes a new session. Nothing here stops the delete. +- A restore is heard of after the file is back, so a failure of the pad's step is logged and goes no further: the file is restored all the same, with its versions and without its trash entry, and its next open offers what the restore did not do. +- Restore of a file whose row stayed active - every file whose pad the trash kept: the pad is taken back as it is, unless Etherpad has lost it while the file was away (`ManagedPadLifecycle::howLost()`, see "Open (authenticated)"). Then a new pad is made from the file at once (`RestoreService::restoreActiveRow()`, the replacement below), where an open would only offer it: coming back from the trash, the file is surely the one the pad was. Etherpad not answering, or a file that cannot be read, leave the row to the next open, which offers the new pad should the pad be lost. A folder restored does not ask for each of its files: those an open finds lost offer a new pad. +- Restore without a binding row: a new pad from the file's snapshot, whatever `delete_pad_with_file` says: the trash of an earlier version took the pad along, and nothing is left to keep. Unless another file's row names the pad the file names, and that file is still there: then the file is a copy that was never opened, its pad lives on with the original, and the restore leaves it (`copy_of_another_file`). An original whose file is gone - deleted for good, its pad about to go, or vanished - leaves the copy the content, and the copy gets a pad of its own; its open offers the original or a new pad, as any copy's does. That includes the copy a share recipient's delete leaves in the recipient's trash, while the file itself goes to its owner's: restored, it is such a copy, and the pad stays with the owner's file. A file that cannot be read - a legacy Ownpad link without metadata, or one locked now - is left to its open, quietly (`file_unreadable`), as for an active row: the open migrates it, offers its recovery or says what is wrong. +- Restore of a file whose row is `pending_delete`: seen deleted for good, yet back, so the deletion did not happen. The row is active again, and the restore goes on as for any active row. An open of such a file does the same (`BindingService::assertConsistentMapping()`). +- The replacement: a new pad from the file's snapshot, the row moved onto it, the file naming it and recording its revision count. A pad behind the file - one without a single revision, with other text than the file saved - is left in place; whoever wrote into it has only that copy. Of a pad that does not exist, what is left - an empty group - goes, and only while it holds nothing: the pad may be back by then, made anew through the API, and a group that cannot be read stays. + - Of two restores that race for one file only one writes it, and a restore that fails takes back what it made (`RestoreService::restoreOntoNewPad`). + - A replacement that fails - Etherpad gone while the new pad is seeded, the file locked for the write - leaves the active row on the lost pad: moved back onto it when the row was already claimed. The next open offers the new pad again. + - Seeding a new pad takes a while. Through WebDAV the file stays locked meanwhile, and a delete is refused (423, measured against NC 34.0.3); without that lock the file can be deleted again, or written. So the row is claimed only while the file is still where it was and still holds what the new pad was seeded from, read again right before: moved, and the new pad is let go (`file_moved`); written meanwhile - a sync of a pad made anew that someone wrote into, an upload - and it is let go too (`file_changed`), since written over, what was written would be gone. Nothing is claimed or written either way, and the next open asks again. + - Only two things can leave a row naming a pad the file does not, and opening the file then answers `Binding pad ID mismatch.`: a database that fails again in the middle of the rollback, and a sync of a pad Etherpad made anew, written into after the recovery asked about it, that writes in the moment between its last look at the row and its write, just as the recovery moves the row (see "Sync"; a sync of a pad that is gone fails before it writes, and one of a pad made anew that nobody wrote into writes nothing). Neither the open nor the recovery settles that; nothing does yet. + - A write that throws after the content landed - a hook after it failing - keeps the new pad: the file is asked which pad it names, and if it is the new one, row and file agree, and taking either back would leave them naming two pads. Logged at `warning`. + - A write that throws on a file that then cannot be read either leaves open which pad the file names. No row may be left to contradict it: the row goes, and the file's next open finds no row and offers a pad from its content, whichever pad it names. The new pad stays, named in the `warning`: a write is not atomic on every storage, and one that broke off may have cut the file short, leaving the new pad the last whole copy of what the file held. + - A row whose access mode is none the app knows gets no new pad, and stays as it is. +- A restore's pad step leaves these lines: + - `Could not restore the pad of a file back from the trash. The file itself is restored.` at `error`, once for each way in that fails, `via` naming it (`hook` or `event`). A core restore passes twice (see Event Integration), so a line from the hook can be followed by an event pass that did what the hook pass could not. - `Legacy trashbin restore hook could not start.`, or `Legacy trashbin restore hook failed.` for anything the listener let through, at `error`. - `RestoreFromTrash listener skipped a restored node.` at `warning`, with its reason, when the restored node cannot be resolved. - - A restore that leaves the pad alone on purpose says so at `debug` only, as `Lifecycle step skipped.` with its reason: `delete_on_trash` off for a file without a row, a row whose access mode is unknown, a row another flow holds. -- What the pad's restore left unfinished waits for the sweep, or the file offers its own recovery. An open that comes first decides the row itself (`SettleOnOpen`), signed in or through a public share: - - The sweep's decision for a file in Files, and no file written: a pad that is there takes the row back and the file opens; one that is behind lets the row go and the file offers its recovery. For one that is gone, what is left of it (an empty group) is removed first, and only then does the row go; a clean-up that does not finish keeps the row for a later try. - - Under the row's `SettleLock`, never waited for, and within five seconds. - - Only a row nobody has touched for a minute: a trash that has just made it a deletion owed finishes it undisturbed, and an outage costs one call to Etherpad and one log line per row and minute, however often the file is opened, anonymously through a share included. - - It reaches what the sweep cannot, or only late: a file only its owner's session can read (encrypted with the owner's key, or on a storage whose credentials live in the session), and a deletion owed that only the daily run would reach. - - A row it did not decide says the pad is still being restored (`waiting_binding`), `retryable` (see "Errors of the API"); `docs/api-reference.md` lists why. -- Only a database that fails again in the middle of the rollback can leave a row naming a pad the file does not; opening the file then answers `Binding pad ID mismatch.` A restore through the API (`POST /api/v1/pads/restore`) still answers such a failure with an error. -- `PendingBindingService` settles waiting rows in age buckets (every 5 minutes, then hourly, then daily) and from the admin page, by where the file is now: - - in Files (`restore_pending`, or `pending_delete` whose restore never came): the decision a restore takes, except that a sweep writes no file. A pad that is gone or behind releases the row, and the file offers its own recovery when it is next opened; of a pad that is gone, what is left (an empty group) goes too. - - in its owner's trash (`pending_delete`): the rest of the trash, written on the owner's own storage. A pad past the file's `snapshot_rev` goes into the file (one at it is there already), then row and pad are deleted; a restore that comes first keeps the pad. A pad that is gone: the row goes, and for a group pad what is left of it (an empty group). A pad that is behind is logged with its id and left in place, and the row goes. Either way the file keeps the snapshot it has. A pad that cannot be deleted once its row is gone is left over and logged with its id; its content is in the file. - - A file that did not get its snapshot waits for the next run, in one log line, `A trashed .pad file did not get its snapshot`, with a `reason` (`TrashSnapshotMiss`). The file's own trouble - unreadable, unparsable, a write refused, an empty file - moves the row to the back and is reported at warning level the first time only. What passes by itself - a lock, a pad that changes while it is read, a file a restore took back - is tried again where the row is, at debug level. Etherpad giving no answer is a warning each time: while the snapshot is read (`snapshot_not_fetched`), or on the count after the write (`pad_not_recounted`), when the snapshot is in the file but an edit that came meanwhile would not be. A row a trash before 1.1.0 wrote may report at debug level from the start; a row without `deleted_at` reports each time. - - An empty file waits until its trash lets it go: there is nothing to write a snapshot into, and it says nothing about the pad, which may hold the only copy. - - A restore can take the file back while the sweep is at it. The sweep asks right before the write whether the file is still where it was, and again after it, once the pad is counted again. Moved by then (`file_moved_while_written`), row and pad stay for the restore, which takes the pad back; a new file the write made in the trash where the old one was is deleted, so the trash does not list a second copy of a file that was restored. - - One such restore still gets past both questions: Nextcloud moves the file on disk first and in the file cache right after, and locks no path in a trash. A restore that moves it on disk before the write and in the cache only after the second question, with the write and a call to Etherpad in between, leaves the snapshot in the trash; if the sweep then takes the row before the restore does, the pad goes while the file back in Files holds the older one. Only a lock taken before the restore moves the file (`OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent`) would close that, at a price not paid for so narrow a moment: a restore refused for it answers 500 with an error in the log (only a class of Nextcloud's dav app would make it 423), a restored folder would have its `.pad` files looked up each time, and a lock a dying process leaves would block restoring and trashing the file until it expires. - - in a team folder's trash: nothing yet; the row waits until that trash lets the file go. On the root storage (`__groupfolders/trash/`) such rows are not fetched at all. A team folder with its own storage keeps trashed files under a bare `trash/`, found by no node, and the row moves to the back. With groupfolders' `auto` retention and no quota the trash never lets the file go, and a public pad stays reachable until it is emptied. - - gone for good, with no `filecache` row left, in either waiting state: pad deleted, then row. No restore can come for such a file, and a pad that could not be deleted keeps its row for the next run. So does one whose group could not be listed, while its deletion has been owed for less than a day, counted from the trash - a trash emptied soon after, not a file that expired from a trash or left a team folder's; after that the pad goes alone and the group is given up, so a group that can never be listed holds nothing up. - - While `delete_on_trash` is off, no pad is deleted here, even when it is switched off during a run: rows in a trash or gone for good wait, and are not fetched. - - A run takes rows of each kind in turn: restores left undecided, then deletions owed for a file gone for good, in a user's trash, and anywhere else. Each kind is asked for the whole limit and what one leaves goes to the others, so rows no run can settle yet crowd out only rows of their own kind, and a run that ends on its budget has reached every kind. Within a kind, rows are aged by `deleted_at` (`updated_at` for `restore_pending`) and taken by `updated_at`: a row that waits for its file's own trouble, or whose file no node reaches, moves to the back. - - A row is settled by one run at a time: the jobs and the admin page can run at once, and each holds the row's `SettleLock`. A run that finds the row held passes it by, also while a lock a dying process left has not expired; with file locking switched off, two runs can finish the same trash at once. - - A run lasts up to 20 s (`RunBudget`). A row Etherpad gives no answer for stays where it is, and after five of them the run stops; a file that cannot be read does not count. A pad whose row is already gone is deleted even at the end of a run, on the client's own timeouts, and so is what is left of a pad that is gone once the sweep has released its row. -- Trashing a file whose row is `restore_pending` returns the row to `pending_delete`, whatever `delete_on_trash` says, and leaves the pad alone, without a snapshot: which pad is the file's is what is undecided. If a sweep settled the row a moment earlier, the trash reads it again and trashes the file as what it is now. -- `deleted_at` is set only in `pending_delete`, when a row gets there, and kept while it stays. + - A restore that leaves the pad alone on purpose says so at `debug` only, as `Lifecycle step skipped.` with its reason: a row whose access mode is unknown, a row another flow holds, an active row whose pad is there. +- Upgrading from 1.1.0-beta.1, whose trash deleted pads (`Version000005Date20260928120000`): a trash that could not reach Etherpad left its row `pending_delete`. One whose file is still in a trash, or back in Files, becomes an active row: its pad was kept, and the trash keeps it now. One whose file is gone for good stays `pending_delete` for the sweep. The setting `delete_on_trash` becomes `delete_pad_with_file`, with the value the admin gave it - and until then the old one's word stands, should this code run before its migration; read and written through `IAppConfig` alone, so the value keeps one type. Its three retry jobs (`Hot`, `Warm`, `ColdPendingDeleteRetryJob`) are taken off the job list, rather than left to the first cron run, which drops a job whose class is gone with a warning each, and the `test_fault` key its debug instances could set goes. The index on a row's state (`ep_bind_state_idx`) gives way to one on its state and access mode (`ep_bind_state_mode_idx`), which serves every question by state alone too, from its first column. - External pads skip lifecycle side effects entirely. Trash/restore only affects the Nextcloud file; the remote Etherpad server is never mutated. +### 5b) Files gone for good + +- A pad goes once its `.pad` file is deleted for good and gone from the file cache: from a trash, past it, or with the account that owned it. What each way of deleting a file does to its pad: [deleting-pads.md](deleting-pads.md). +- `GoneFilesListener` marks the rows of files seen deleted for good: `pending_delete`, dated by `deleted_at`. The file cache says what goes: Nextcloud reports every entry it removes (`CacheEntryRemovedEvent`), each descendant of a removed folder too, on 31 to 34. Not every removal is a deletion - a scan drops what vanished outside Nextcloud - so these count: + - A removal from a trash: a user's (`files_trashbin/files/` on a home storage), a team folder's on the root storage (`__groupfolders/trash/`), or one on the folder's own storage (`trash/`, told from a folder of that name elsewhere by the storage's id). A folder of one of those names on any other storage - an external one, say - is a folder like another. That is the trash emptied, an item deleted there or expired, `occ trashbin:cleanup`, groupfolders' trash alike. + - A removal of a node Nextcloud deletes, or of anything under it, between the node's `BeforeNodeDeletedEvent` and its `NodeDeletedEvent`: a delete past the trash (a WebDAV `DELETE` with `X-NC-Skip-Trashbin`, the trash app off for the user) takes the node and all under it. Where the node is - its storage and path in the file cache - is looked up as the delete starts, one query by its id. A delete that fails, a locked file say, raises no `NodeDeletedEvent`, and its window stays open for the rest of the process, a cron run's too; it covers the node's own entries only, never what a scan drops elsewhere. A delete that goes to a trash is a move. One within a storage removes nothing from the file cache, and one to another storage that keeps the id is reported as a removal and an insert (`CacheEntryInsertedEvent`), which makes the row active again. One to a storage whose cache is wrapped - an external storage with an encoding option, say - copies the file into the trash under new ids first and then removes the old ones: so an insert into a trash while a node is being deleted closes the delete's window, and what it removes then is not deleted for good. Not `MoveToTrashEvent`: the trash app sends it before it tries, and a delete it then does not take - an app vetoing it, the move failing - goes past the trash, puts nothing there, and counts. Likewise a restore from a user's trash (`BeforeNodeRestoredEvent` to `NodeRestoredEvent`, the window closed by the source's path, as the source has no id once restored): what it removes from the trash is not deleted for good. + - A user deleted: every file on their home storage, which Nextcloud clears, file cache and all, without a single event. The files are looked up before (`BeforeUserDeletedEvent`), from the home mount (`IMountProviderCollection::getHomeMountForUser()`, as Nextcloud's own cleanup of a deleted user finds it, with no row in the mount cache needed), and marked once the user is gone (`UserDeletedEvent`). A deletion the user backend refuses raises no `UserDeletedEvent` and leaves the files unmarked. + - What counts is the file's id, never its name: a `.pad` renamed keeps its row, and its pad goes with it. + - What a scan drops never counts, in a trash or under a delete: `occ files:scan` says so (`NodeRemovedFromCache`) right before the entries go, and the listener leaves that entry and all under it, until the entry's own removal, which Nextcloud reports after all under it: a removal there later in the process counts again. The background scan and the watcher that checks for changes on access send no such word; what they drop in a trash, or under a delete whose window a failure left open, still counts. + - Versions on a home storage (`files_versions/`) and app data on the root storage (`appdata_*`, previews among them) never count; a file of such a name elsewhere does. Every other removal of the instance comes by the listener too, so each costs a look at its path; one that counts takes a place in a set, written in blocks of 500 (`UPDATE ... WHERE file_id IN`) when full, when a delete through a node is done (`NodeDeletedEvent`, and `\OCP\Files::postDelete`, which a trash's deletes send too), and at the end of the process. A team folder's trash deletes at the storage, so what it removes waits for a full block or the end of the process; a process killed before - a long-running `occ background-job:worker`, say - loses it, and those pads stay, listed as vanished. Only files the file cache has nothing of by then are marked (`BindingService::markIfGone()`), so a removal reported under an id that is not the file's never marks a file that is still there. The rows are looked up first, so a removal of a file without one costs no look into the file cache, and the listener keeps only the files whose rows it marked: a cleanup over millions of entries holds a handful. The request does not touch Etherpad. + - Nextcloud 34 reports a removed folder's descendants under the wrong ids - their places in a block of a thousand - and again with each block. That includes a whole trash emptied, which Nextcloud deletes as one folder (`files_trashbin`), and `occ trashbin:cleanup`. Fixed by nextcloud/server#63998 for 35.0.1; the backport to 34 (nextcloud/server#64497) is planned for 34.0.5 and not merged yet. It sends the block first (`CacheEntriesRemovedEvent`, from 34 on); a block holding id 0, which no file has, is such a block, and none of its removals counts, so no other file's row is marked. The listener hears the block ahead of other apps' (priority 100), so one throwing first - which Nextcloud catches before it sends the removals one by one - cannot keep it away; should the block not come, the removals under wrong ids still mark no file the file cache has, but they can mark the row of a file that vanished before. The files in a folder deleted for good there, or in a trash emptied as a whole, keep their pads and are listed as vanished. 31 to 33 report the right ids, one event each. + - The listener never stops a delete and never throws: a mark that fails is a warning, and the row counts as vanished (below). One instance hears all of a request's events, as Nextcloud's container keeps the one it made. +- A row is due five minutes after it was marked (`BindingService::GONE_GRACE_SECONDS`): a margin before a step that cannot be undone, for an order of events no one has seen yet. A row is only marked once the file is gone from the file cache, a move keeps the file's entry, and Nextcloud never gives a removed id to a file again, so nothing known needs it. +- `GoneFileSweep` runs on every tick of a five-minute cron (`GoneFileSweepJob`, declared in `appinfo/info.xml`: an add at boot, as before, ran on every request and reset the job's last run; its interval is four minutes, as Nextcloud runs a job only once more than its interval has passed, and five would run it on every other tick), within 20 s (`RunBudget`): rows in `pending_delete` that are due and whose file the file cache has nothing of, the longest untouched first, in batches of 200, ten at most a run. A file deleted past the trash takes its pad within two runs of the job. + - First, it makes the rows of files the file cache still has an hour after they were marked active again, 200 a run, with one `info` line: a deletion that did not happen after all - one rolled back, an account whose files were left. Kept waiting, such a row would take the pad of a file a scan drops later, which the app leaves. This runs with `delete_pad_with_file` off too. + - Right before a pad goes, the file cache is asked once more, and the row goes only while it still waits and names the pad. A pad Etherpad no longer has counts as deleted, and its row goes. A pad Etherpad refuses to delete keeps its row, with a warning the first time, and is tried again an hour later (`updated_at`): it neither holds the head of the queue nor warns every run. Etherpad not answering ends the run with one `info` line. An error that reads as that - an HTTP error, an answer Etherpad could not have meant - may be the pad's alone, so Etherpad is asked the question it always can (`checkToken`) first: answered, the pad waits its hour like a refused one, and the run goes on. + - A file marked but still in the file cache keeps its pad. + - The admin page's settle (`POST /api/v1/admin/settle-pending`) runs the sweep too, within its budget, and takes the rows still in their five minutes and those Etherpad refused within the hour: what the job would do within minutes, or an hour, now - after the admin fixed Etherpad, say. A run tries each row once. + - With `delete_pad_with_file` off no pad goes here, and the admin page's settle says so, but the rows keep waiting, so switching it on finds them. +- A file gone without being seen deleted is left alone, pad and row with it: one removed outside Nextcloud and dropped by a scan, a team folder deleted as a whole or a storage removed (Nextcloud clears their file cache without an event), a file cache rebuilt. The consistency check counts and lists such rows (`vanished_file_count`). A `.pad` file replaced by moving another file onto it through WebDAV goes to the trash first (measured against NC 34.0.3), so its pad goes once it leaves the trash. + ### 6) Admin Integrity Check (optional) -1. Admin runs `POST /api/v1/admin/consistency-check`. -2. Service scans DB/file metadata consistency. -3. Returns aggregate counters and bounded sample lists for diagnostics. -4. External `.pad` files without bindings are expected and are excluded from missing-binding diagnostics. +1. Admin runs `POST /api/v1/admin/consistency-check`, from the admin page or the API; nothing runs it on its own. +2. It counts the vanished rows (`vanished_file_count`): their file gone from the file cache, still active, never seen deleted for good. Those are the files gone without a deletion the app heard of - from a trash, past it, or with an account; their pads stay (see "Files gone for good"), and they are what the check reports as issues. A row seen deleted for good is on its way and not counted: `pending_delete`, which the sweep takes within minutes, or keeps while `delete_pad_with_file` is off (`pending_delete_count` in the health check). +3. It returns up to 25 of them (`samples`). The admin page lists them by pad id. Nothing removes such a row: deleting its pad in Etherpad leaves it on the list. +4. Its cost grows with the rows, or with the file cache, whichever the database reads: measured at 0.14 to 0.35 s for 500,000 rows and 2 million files (Postgres 16, warm). ## Main Frontend Modules @@ -318,7 +317,7 @@ Primary flow (native viewer): - Each error answered is logged once, by `ApiErrorLog`; the services under the mappers leave it to it, save the few lines that explain a refusal nothing else would (a name another create has locked, a file a create will not write over, a refused legacy migration): - Etherpad not reachable: `Etherpad could not be reached while answering a request.`, a warning once a minute for the instance and at debug for the rest of that minute, since an outage reaches every open viewer's sync. Refusing: `Etherpad refused a request.`, once a minute for each file, since each is a case of its own (a pad deleted in Etherpad, a group gone), and once a minute for all refusals that name none. Without a distributed cache, or with one that fails, each is a warning. - A `.pad` and its row that do not match (`BindingMismatchException`): `A .pad file and its pad binding could not be matched.`, a warning. A row that could not be written (`BindingNotCreatedException`): `Could not create pad binding.`, an error with the database's cause. - - The unforeseen: an error under the endpoint's line (`Pad restore API failed`, `Pad sync failed`, ...), or `Unhandled pad controller error` / `Unhandled public viewer error`. + - The unforeseen: an error under the endpoint's line (`Pad recovery API failed`, `Pad sync failed`, ...), or `Unhandled pad controller error` / `Unhandled public viewer error`. - Anything else - what the request got wrong, a pad on another server: `A request was refused.` at debug, with the reason the answer leaves out. - The line names the request's file (`ApiErrorLog::fileNamedBy()`): signed in by `fileId` and `file`, on a public share by `fileId` only, since a public path may be a DAV URL carrying the share token. @@ -330,9 +329,13 @@ Primary flow (native viewer): - Register the viewer handler on other pages that load Viewer. - `OCA\Files_Sharing\Event\BeforeTemplateRenderedEvent` - Register the viewer handler on public-share pages and load the one-shot opener for public single-file `.pad` shares or existing compatibility links. -- `OCA\Files_Trashbin\Events\MoveToTrashEvent`, and the legacy event `OCA\Files_Trashbin::moveToTrash` - - Trash lifecycle. +- `OCP\Files\Cache\CacheEntryRemovedEvent`, `OCP\Files\Cache\CacheEntryInsertedEvent`, `OCP\Files\Cache\CacheEntriesRemovedEvent` (from 34), `OCP\Files\Events\Node\BeforeNodeDeletedEvent`, `OCP\Files\Events\Node\NodeDeletedEvent`, `OCP\Files\Events\NodeRemovedFromCache`, the event named `\OCP\Files::postDelete`, `OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent`, `OCA\Files_Trashbin\Events\NodeRestoredEvent`, `OCP\User\Events\BeforeUserDeletedEvent`, `OCP\User\Events\UserDeletedEvent` + - Mark the rows of files deleted for good (see "Files gone for good"). +- `OCP\Files\Events\Node\BeforeNodeDeletedEvent`, `OCP\Files\Events\Node\NodeDeletedEvent` + - Take the sessions of the protected pads a delete takes along (see Trash/Restore). +- `OCP\User\Events\UserLoggedOutEvent`, `OCP\User\Events\BeforeUserDeletedEvent` + - Take the account's own sessions: on a logout, and as the account's delete starts, while Nextcloud still has its Etherpad author (see `docs/etherpad-integration.md`, "Session lifetime and revocation"). - `OCA\Files_Trashbin\Events\NodeRestoredEvent` - Restore lifecycle. - `\OCA\Files_Trashbin\Trashbin::post_restore` (legacy hook) - - Restore lifecycle for groupfolders, which fires no `NodeRestoredEvent`. Core fires both, the hook first, to the same listener: the event pass is a second try at what the hook pass left undone - after a hook pass that failed on the database, or could not read the file, say - save after a hook pass that asked Etherpad and got no answer, or an error. That one it leaves, as it would only ask again; so a restore asks an Etherpad that hangs once, not twice. Every hook pass starts afresh. + - Restore lifecycle for groupfolders, which fires no `NodeRestoredEvent`. Core fires both, the hook first, to the same listener: the event pass is a second try at what the hook pass could not do - after a hook pass that failed on the database, or could not read the file. What the hook pass decided - the pad restored, made anew, or left as it is - the event pass leaves, rather than ask Etherpad the same again; so it does after a hook pass that asked Etherpad and got no answer, or an error, so that a restore asks an Etherpad that hangs once, not twice. Every hook pass starts afresh. diff --git a/docs/deleting-pads.md b/docs/deleting-pads.md new file mode 100644 index 00000000..a3a2948e --- /dev/null +++ b/docs/deleting-pads.md @@ -0,0 +1,121 @@ +# When a Pad Is Deleted + +SPDX-License-Identifier: AGPL-3.0-or-later + +A pad lives in Etherpad; its `.pad` file lives in Nextcloud. The pad lives +as long as the file: the trash keeps it, and it is deleted once the file is +deleted for good. The technical side is in [architecture.md](architecture.md), +under "Trash/Restore" and "Files gone for good". + +What counts is the file, not its name: a `.pad` file renamed to something +else keeps its pad, and the pad goes once the file is deleted for good. + +This applies to pads this Nextcloud manages, with the admin setting +`delete_pad_with_file` on - the default; `delete_on_trash` before, +whose value it takes over. A `.pad` file that links a pad on another +Etherpad server never deletes that pad. + +## Moved to the trash + +A file goes to the trash when it is deleted through Files, a desktop or +mobile client, or a WebDAV `DELETE`, in a user's own folders as in a team +folder. So does a file replaced by moving another file onto it (WebDAV +`MOVE` with `Overwrite: T`), and every file in a folder moved to the trash. + +The pad stays as it is, and nothing is written into the file. + +- **A protected pad** loses its sessions: whoever still has it open can + write no more from their next change on, and nobody opens it until the + file is back. On a folder with many protected pads, what does not fit in + a few seconds is left to expire, within six hours. +- **A public pad** stays reachable by its link, and can be written into. + The file in the trash is not synced, so what is written there is in the + pad, not in the file's snapshot; a restore brings it back with the pad. +- **A `.pad` file that names another user's group** - a legacy Ownpad file + can - takes no sessions along: only a group that holds its pad alone + loses them. + +## Restored from the trash + +- **A `.pad` file, or a folder with `.pad` files in it:** the file has its + pad back as it was, with its history and anything written into it + meanwhile. Opening it makes a new session for a protected pad. +- **A `.pad` file whose pad Etherpad has lost meanwhile:** a new pad is made + from the snapshot in the file, at once. It holds the content, not the + pad's history. If Etherpad does not answer during the restore, the file + is restored all the same, and its next open offers the new pad. A folder + restored does not ask for each of its files: those whose pad is lost offer + a new one when they are opened. +- **A `.pad` file a share recipient deleted:** Nextcloud puts the file + itself into its owner's trash and a copy into the recipient's. The + owner's restore brings the pad back. The recipient's copy, restored, is a + copy: it holds the file's content as of its last sync - what was written + into the pad after that lives only in the pad, with the original - and + its open offers a new pad from it, while the pad stays with the file in + the owner's trash until that goes. +- **A `.pad` file trashed under an earlier version,** whose trash deleted + the pad (1.1.0-beta.1 and before): a new pad is made from the snapshot in + the file, at once. A + copy of another `.pad` file that was never opened is left as it is: its + pad was not deleted, and opening it offers that pad or a new one. + +## Deleted for good + +| How the file is deleted for good | When the pad is deleted | +|---|---| +| From the trash: the trash emptied, the item deleted there, expired, or `occ trashbin:cleanup`. A user's trash or a team folder's. | By a background job, within minutes; for a folder's files too. | +| Past the trash: a WebDAV `DELETE` with `X-NC-Skip-Trashbin: true`, the trash app switched off for the user, or a move to the trash that fails or that another app keeps from the trash. | By a background job, within minutes; for a folder's files too. | +| With the account: the account deleted. | The pads of the account's own files - those in its home and its trash, shared ones included - by a background job, within minutes. Files in team folders, and files the account put into folders others shared with it, are not the account's: they stay, and so do their pads. The account's own Etherpad sessions go as the delete starts, as on a logout. | + +"A background job" runs on every tick of a five-minute system cron; with +AJAX or webcron, only as often as those run. It deletes the pad of a file +deleted for good once five minutes have passed, so the pad goes within +about ten minutes; the admin page's "Check pending pads" does it at once. When Etherpad does not answer, the job deletes the pad once +it does; until then the admin page counts it as a pending delete. + +On Nextcloud 34, Nextcloud reports the files inside a folder deleted for +good under the wrong ids - and a trash emptied as a whole, from the Files +app or with `occ trashbin:cleanup`, is deleted as one folder. The fix +(nextcloud/server#63998) is in 35.0.1; its backport to 34 +(nextcloud/server#64497) is planned for 34.0.5 and not merged yet. The app +cannot tell which files they were, so the pads of the `.pad` files inside +such a folder, or in a trash emptied as a whole, stay, and the consistency +check lists them. A `.pad` file deleted on its own - past the trash, or +from the trash by itself or when it expires - and an account deleted, are +not affected. + +## Gone without being deleted in Nextcloud + +A file can also leave without anyone deleting it in Nextcloud. Its pad +stays: + +- files removed outside Nextcloud - on an external storage, or in the data + directory - that a scan then drops; +- a team folder deleted as a whole by an admin, and an external storage + removed. Files that were in the team folder's trash then may go as from + a trash, and take their pads along: on a team folder kept on Nextcloud's + own storage, not on one with a storage of its own. + +A pad that stays keeps its content in Etherpad, and nobody reaches it +through Nextcloud any more; a public pad stays reachable by its link. The +consistency check on the admin page counts these pads and lists up to 25 of +them by pad id (`vanished_file_count`). The app keeps their rows: deleting +such a pad in Etherpad does not take it off the list. + +## When Etherpad has lost a pad + +If Etherpad no longer has a pad - deleted there by hand, or lost with its +database - opening its file says so. Whoever may edit the file can make a +new pad from the content saved in it; from then on the file opens the new +pad. The same happens for a public pad that someone visited by its link +after it was lost, which Etherpad makes anew, empty; an editor still open on +the file does not write that empty pad into it as it closes, so the content +stays for the new pad. A copied `.pad` file, +which has no pad of its own, offers the same. A file restored from the +trash does not ask: it gets its new pad on its own. + +## With `delete_pad_with_file` off + +The app deletes no pad at all: the pads of files deleted for good stay, and +the admin page counts them as pending deletes. Switched back on, the job +deletes them. diff --git a/docs/etherpad-integration.md b/docs/etherpad-integration.md index 20319022..72377dcc 100644 --- a/docs/etherpad-integration.md +++ b/docs/etherpad-integration.md @@ -54,20 +54,18 @@ that file destroy their group, their pad and their sessions. A group that holds only the pad being deleted, or nothing at all, has nothing else to lose. -It answers true when it removed something, the pad or the empty group a -protected pad left behind, and false when Etherpad says there was nothing -left: no such pad, or no such group. A caller that has just heard the pad -is gone says so (`knownAbsent`); a public pad then costs no call, a -protected one is still asked about its group. +It is done when it removed something, the pad or the empty group a +protected pad left behind, and when Etherpad says there was nothing left: +no such pad, or no such group. A caller that has just heard the pad is +gone says so (`knownAbsent`); a public pad then costs no call, a protected +one is still asked about its group. A group Etherpad cannot list is given up by default: the pad goes alone, the half that was always safe, and the empty group stays. A caller that keeps its row and tries again says so (`retried`) and gets the failed read -instead, with nothing removed: the trash, which then owes the deletion, -and the sweep for a file gone for good while the deletion has been owed -for less than a day, counted from the trash. One that cannot try again - -the sweep once it has taken a trashed file's row, the clean-up after a -replacement or a released row - takes the default. +instead, with nothing removed: the sweep of files gone for good, which +tries again an hour later. One that cannot try again - the clean-up after +a replacement - takes the default. The shape rule itself lives in `Util\PadId` and is the same one that classifies a binding as protected. It used to be stricter here, so a pad @@ -159,9 +157,10 @@ which is how the open request can read it in the first place. open of any other protected pad happened to overwrite the cookie and cut it off; that only ever helped if the user opened another pad, and did nothing otherwise. Revoking a share does not end the Etherpad sessions - already issued for it: only expiry, a logout, or removing the group - behind the pad clears them, so the window is the session TTL either way - — it is just no longer shortened by accident. + already issued for it: only expiry, a logout, the recipient's account + being deleted, or removing the group behind the pad clears them, so the + window is the session TTL either way — it is just no longer shortened + by accident. ### Author Resolution Strategy @@ -227,8 +226,9 @@ away itself: every socket message and keeps the session id it was handed when the pad connected – read in 2.7.3, 3.0.0 and 3.3.3 – so a session that expires mid-edit rejects the next keystroke, and no later cookie reaches that - socket. Revocation fires on an explicit logout and nowhere else, and is - capped, so for most sessions the lifetime is what bounds the window. + socket. Revocation fires on an explicit logout, on the account's + deletion and on a delete of the pad's file (below), and is capped, so + for most sessions the lifetime is what bounds the window. - Expired sessions are left to the background sweep described below. Only what is expired by both clocks counts as expired: Etherpad judges `validUntil` with its own, so a session ours calls dead may still be @@ -246,9 +246,22 @@ cached id is therefore not dropped when an open fails – an emptied cache cannot be told from a user who never opened a protected pad, and a logout after a brief outage would revoke nothing. -**Only logout.** Losing a share does not revoke anything, and neither does -a permission downgrade, a deleted or disabled account, or a deleted public -link. A session issued before any of those stays valid until `validUntil`. +**A delete of the file revokes the pad's sessions** – every session of +the pad's group, whoever it was issued to, once the file goes to the +trash or past it, for a folder's protected pads too: the trash keeps the +pad, and a session would keep giving it to whoever holds one. Which +groups, and within what budget: `docs/architecture.md`, "Trash/Restore". + +**Deleting an account revokes its sessions**, as a logout does, as the +delete starts (`RevokeSessionsOnAccountDeleteListener`): Nextcloud removes +the account's settings, the cached author among them, before it reports +the account gone. A delete the user backend then refuses has lost them as +a logout would, and the next open makes new ones. + +**Otherwise, only expiry.** Losing a share does not revoke anything, and +neither does a permission downgrade, a disabled account, or a deleted +public link. A session issued before any of those stays valid until +`validUntil`. Covering them one event at a time means enumerating every way access can end, and that list has no natural end – a public link in particular opens under its own Etherpad author whose id is deliberately never cached, so diff --git a/docs/pad-format.md b/docs/pad-format.md index 62f8bbf9..cede01fe 100644 --- a/docs/pad-format.md +++ b/docs/pad-format.md @@ -104,8 +104,9 @@ Protected + external is not supported. - `trashed` / `purged` - legacy parser compatibility only; new writes do not use these states -The DB binding table uses `active`, `pending_delete` and `restore_pending`. Successful trash deletes -the binding row; restore can recreate it from the `.pad` frontmatter and snapshot. +The DB binding table uses `active`, and `pending_delete` for a file deleted for good whose pad +has yet to go. A trash keeps the binding row and the pad; a file restored without a row, or +whose pad Etherpad lost, gets a new pad from the `.pad` frontmatter and snapshot. External pads are not managed in the DB binding table, so trash/restore only moves the Nextcloud file and never creates, deletes, or restores anything on the remote Etherpad server. @@ -129,7 +130,7 @@ Snapshot write flow: - `PadFileService::withExportSnapshot(...)` builds the new `.pad` content after an Etherpad export. - `PadFileLockRetryService::putContentWithSyncLockRetry(...)` writes that content back to the Nextcloud file with bounded lock retry. -- Stored snapshots are read by `RestoreService` when restoring a pad and by the forced sync when comparing content. No viewer path reads them. +- Stored snapshots are read by `RestoreService` when restoring a pad, by the forced sync when comparing content, and by an open that may write and the sync to tell whether Etherpad has lost the pad. No viewer path shows them. - External public pad create/sync paths both use the validated, host-pinned `/export/txt` fetch internally (via `ExternalPadExportFetcher`) and store no HTML snapshot: - create uses `ExternalPadExportFetcher::normalizeAndFetchExternalPublicPadTextOrEmpty(...)`, allowing the `.pad` file to be created with an empty initial snapshot if the export is not available yet. - sync uses `ExternalPadExportFetcher::normalizeAndFetchExternalPublicPadText(...)`, keeping later export failures visible. @@ -138,6 +139,7 @@ Snapshot write flow: - Sync writes only when the upstream snapshot actually differs. - `force=1` requests an immediate upstream re-check, but unchanged snapshots are still not rewritten. +- A pad Etherpad made anew in place of the file's - without a single revision, with other text than the file saved - is not written, forced or not: the sync answers `pad_missing`, and the file keeps its content for a new pad. - On successful sync: - `snapshot_rev` is updated - body is replaced: diff --git a/docs/release-process.md b/docs/release-process.md index 4c292023..0bfbb8f7 100644 --- a/docs/release-process.md +++ b/docs/release-process.md @@ -37,7 +37,6 @@ What it does: - If Nextcloud test credentials are present, runs core E2E checks: - pad flow - protected cookie contract (session cookie attrs + no `HttpOnly` for current Etherpad runtime compatibility) - - lifecycle state guards - public folder share flow - public single-file share flow - external URL security checks @@ -92,14 +91,6 @@ RUN_FAILURE_PATHS=1 FAILURE_PATHS_PREPARED=1 NC_BASE_URL=... NC_USER=... NC_APP_ Included: - sync failure path -- trash deferred-delete failure path -- restore failure path - -Optional debug-only lifecycle fault-injection checks: - -```bash -RUN_DEBUG_FAULT_PATHS=1 NC_BASE_URL=... NC_USER=... NC_APP_PASSWORD=... ./tests/integration/release-check.sh "/release-debug-faults" -``` Notes: @@ -107,8 +98,6 @@ Notes: - `RUN_FAILURE_PATHS=1` - `FAILURE_PATHS_PREPARED=1` - This prevents false failures on healthy environments where outage conditions were not prepared. -- Requires admin credentials. -- Requires Nextcloud `debug` mode enabled. ## 3) Tagging diff --git a/js/etherpad_nextcloud-admin-settings.mjs b/js/etherpad_nextcloud-admin-settings.mjs index 63e238fb..5ac1405e 100644 --- a/js/etherpad_nextcloud-admin-settings.mjs +++ b/js/etherpad_nextcloud-admin-settings.mjs @@ -1,2 +1,2 @@ -(function(){const s=document.getElementById("etherpad-nextcloud-admin-settings"),r=document.getElementById("etherpad-nextcloud-admin-form"),f=document.getElementById("etherpad-nextcloud-admin-status"),d=document.getElementById("etherpad-nextcloud-diagnostics-status"),h=document.getElementById("etherpad-nextcloud-connection-status"),H=document.getElementById("etherpad-nextcloud-health-check"),M=document.getElementById("etherpad-nextcloud-consistency-check"),y=document.getElementById("etherpad-nextcloud-settle-pending"),B=document.getElementById("etherpad-nextcloud-pending-actions"),I=document.getElementById("etherpad-nextcloud-pending-count"),$=document.getElementById("etherpad-nextcloud-restore-pending-count"),_=r?r.querySelector('input[name="allow_external_pads"]'):null,w=r?r.querySelector('input[name="enable_protected_pads"]'):null,L=r?r.querySelector('input[name="enable_public_pads"]'):null,b=document.getElementById("pad-types-none-hint"),F=document.getElementById("external-pad-allowlist-row"),D=document.getElementById("external-pad-allowlist-hint"),v=document.getElementById("external-pad-allowlist"),E=document.getElementById("epnc-template-list"),O=document.getElementById("epnc-template-empty"),p=document.getElementById("epnc-template-file"),R=document.getElementById("epnc-template-upload"),c=document.getElementById("epnc-template-status"),x={etherpad_host:r.querySelector('[name="etherpad_host"]'),etherpad_api_host:r.querySelector('[name="etherpad_api_host"]'),etherpad_cookie_domain:r.querySelector('[name="etherpad_cookie_domain"]'),etherpad_api_key:r.querySelector('[name="etherpad_api_key"]'),sync_interval_seconds:r.querySelector('[name="sync_interval_seconds"]'),external_pad_allowlist:r.querySelector('[name="external_pad_allowlist"]'),trusted_embed_origins:r.querySelector('[name="trusted_embed_origins"]')};if(!s||!r||!f||!H)return;const N=s.getAttribute("data-save-url")||"",P=s.getAttribute("data-health-url")||"",j=s.getAttribute("data-consistency-url")||"",U=s.getAttribute("data-settle-pending-url")||"",i={saving:s.getAttribute("data-l10n-saving")||"Saving settings...",saved:s.getAttribute("data-l10n-saved")||"Settings saved.",checking:s.getAttribute("data-l10n-checking")||"Testing Etherpad connection...",consistencyRunning:s.getAttribute("data-l10n-consistency-running")||"Running consistency check...",consistencyOk:s.getAttribute("data-l10n-consistency-ok")||"Consistency check successful.",requestFailed:s.getAttribute("data-l10n-request-failed")||"Request failed.",savingFailed:s.getAttribute("data-l10n-saving-failed")||"Failed to save settings.",healthFailed:s.getAttribute("data-l10n-health-failed")||"Etherpad connection test failed.",consistencyFailed:s.getAttribute("data-l10n-consistency-failed")||"Consistency check failed.",pendingDeleteLabel:s.getAttribute("data-l10n-pending-delete-label")||"Pending Etherpad deletes",restorePendingLabel:s.getAttribute("data-l10n-restore-pending-label")||"Unresolved restores",settleFailed:s.getAttribute("data-l10n-settle-failed")||"Pending pad check failed.",templateUploading:s.getAttribute("data-l10n-template-uploading")||"Uploading template...",templateDelete:s.getAttribute("data-l10n-template-delete")||"Delete",templateTooLarge:s.getAttribute("data-l10n-template-too-large")||"Template file is too large.",templateDeleteLabel:s.getAttribute("data-l10n-template-delete-label")||"Delete template {name}",templateConfirmDelete:s.getAttribute("data-l10n-template-confirm-delete")||"Delete this template for everyone?",templateFailed:s.getAttribute("data-l10n-template-failed")||"Template request failed.",templateConfirmReplace:s.getAttribute("data-l10n-template-confirm-replace")||"Replace the existing template of that name?"},T=s.getAttribute("data-templates-url")||"",Z=s.getAttribute("data-templates-delete-url")||"";if(N===""||P===""||j===""||U==="")return;function z(){const e=!!(_&&_.checked);if(F&&(F.style.display=e?"":"none"),D&&(D.style.display=e?"":"none"),v instanceof HTMLTextAreaElement&&(v.disabled=!e,!e)){v.classList.remove("ep-input-error");const t=r.querySelector('[data-field-error="external_pad_allowlist"]');t instanceof HTMLElement&&(t.textContent="",t.classList.remove("is-visible"))}}function J(){const e=!!(w&&L)&&!w.checked&&!L.checked;if(b instanceof HTMLElement){const t=e&&b.dataset.message||"";b.textContent!==t&&(b.textContent=t)}}function K(){const e=new FormData(r);return{etherpad_host:String(e.get("etherpad_host")||"").trim(),etherpad_api_host:String(e.get("etherpad_api_host")||"").trim(),etherpad_cookie_domain:String(e.get("etherpad_cookie_domain")||"").trim(),etherpad_api_key:String(e.get("etherpad_api_key")||"").trim(),sync_interval_seconds:Number(e.get("sync_interval_seconds")||120),delete_on_trash:e.has("delete_on_trash"),enable_protected_pads:e.has("enable_protected_pads"),allow_legacy_protected_import:e.has("allow_legacy_protected_import"),enable_public_pads:e.has("enable_public_pads"),allow_external_pads:e.has("allow_external_pads"),external_pad_allowlist:String(e.get("external_pad_allowlist")||""),trusted_embed_origins:String(e.get("trusted_embed_origins")||"")}}function l(e,t,n=f){n instanceof HTMLElement&&(n.textContent=e,n.classList.remove("ep-status-success","ep-status-warning","ep-status-error"),(t==="success"||t==="warning"||t==="error")&&n.classList.add(`ep-status-${t}`))}function m(e,t=f){const n=t===c?[c]:[f,d,h];for(const a of n)a instanceof HTMLElement&&a!==t&&(a.textContent="",a.classList.remove("ep-status-success","ep-status-warning","ep-status-error"));l(e,null,t)}const V={skipped:0,ok:1,warning:2};function k(e){for(const t of document.querySelectorAll("[data-check-result]"))t.textContent="",t.className="ep-check-result",delete t.dataset.checkStatus;if(Array.isArray(e))for(const t of e){if(!t||typeof t.label!="string")continue;const n=String(t.status||"skipped"),a=typeof t.detail=="string"?t.detail:"",o=t.field?document.querySelector(`[data-check-result="${CSS.escape(String(t.field))}"]`):null;if(!(o instanceof HTMLElement))continue;const Y=o.dataset.checkStatus;Y&&(V[Y]??0)>(V[n]??0)||(o.dataset.checkStatus=n,o.className=`ep-check-result ep-check-${n}`,o.textContent=n==="ok"?t.label:a||t.label)}}function ee(e){if(!(E instanceof HTMLElement))return;E.replaceChildren();const t=Array.isArray(e)?e:[];A(t.length===0);for(const n of t)!n||typeof n.name!="string"||E.appendChild(te(n.name))}function te(e){const t=document.createElement("li");t.className="ep-template-row";const n=document.createElement("span");n.className="ep-template-name",n.textContent=e,t.appendChild(n);const a=document.createElement("button");return a.type="button",a.textContent=i.templateDelete,a.setAttribute("aria-label",i.templateDeleteLabel.replace("{name}",e)),a.addEventListener("click",()=>{window.confirm(i.templateConfirmDelete)&&ae(e)}),t.appendChild(a),t}function A(e){O instanceof HTMLElement&&(O.style.display=e?"":"none")}let G=0;async function C(){if(T===""||!(E instanceof HTMLElement))return;const e=++G,t=()=>e===G;A(!1);try{const n=await fetch(T,{credentials:"same-origin",headers:{requesttoken:String(OC.requestToken||"")}}),a=await q(n);if(!t())return;ee(a.templates)}catch(n){if(!t())return;A(!1),l(n instanceof Error?n.message:i.templateFailed,"error",c)}}const ne=2*1024*1024;async function Q(e,t=!1){if(typeof e.size=="number"&&e.size>ne){l(i.templateTooLarge,"error",c);return}m(i.templateUploading,c);try{const n=await e.text(),a=await se(T,{name:e.name,content:n,replace:t});l(String(a.message||""),"success",c),await C()}catch(n){if(!t&&n&&n.field==="template_exists"){if(window.confirm(i.templateConfirmReplace)){await Q(e,!0);return}l("",null,c);return}l(n instanceof Error?n.message:i.templateFailed,"error",c)}}async function ae(e){try{const t=await g(Z,{name:e});l(String(t.message||""),"success",c),await C()}catch(t){l(t instanceof Error?t.message:i.templateFailed,"error",c)}}function S(){Object.keys(x).forEach(e=>{const t=x[e];t instanceof HTMLElement&&t.classList.remove("ep-input-error");const n=r.querySelector(`[data-field-error="${e}"]`);n instanceof HTMLElement&&(n.textContent="",n.classList.remove("is-visible"))})}function W(e,t){if(!e||!t)return;const n=x[e];n instanceof HTMLElement&&n.classList.add("ep-input-error");const a=r.querySelector(`[data-field-error="${e}"]`);a instanceof HTMLElement&&(a.textContent=t,a.classList.add("is-visible")),n instanceof HTMLElement&&typeof n.focus=="function"&&n.focus()}const u={pendingDeletes:0,pendingRestores:0};function X(e){const t={};if(typeof e.pending_delete_count<"u"&&(t.pendingDeletes=e.pending_delete_count),typeof e.restore_pending_count<"u"&&(t.pendingRestores=e.restore_pending_count),Object.keys(t).length!==0){for(const[n,a]of Object.entries(t))u[n]=Number.isFinite(Number(a))?Number(a):0;B instanceof HTMLElement&&(B.style.display=u.pendingDeletes>0||u.pendingRestores>0?"":"none"),I instanceof HTMLElement&&(I.textContent=`${i.pendingDeleteLabel}: ${String(u.pendingDeletes)}`),$ instanceof HTMLElement&&($.textContent=`${i.restorePendingLabel}: ${String(u.pendingRestores)}`),y instanceof HTMLButtonElement&&(y.disabled=u.pendingDeletes<=0&&u.pendingRestores<=0)}}async function q(e){let t=null;const n=await e.text();try{t=n!==""?JSON.parse(n):null}catch{t=null}if(!e.ok||!t||t.ok!==!0){const a=t&&t.message?String(t.message):`${i.requestFailed} (HTTP ${e.status})`,o=new Error(a);throw o.field=t&&typeof t.field=="string"?t.field:"",o}return t}async function se(e,t){const n=await fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",requesttoken:String(OC.requestToken||"")},body:JSON.stringify(t)});return q(n)}async function g(e,t){const n=new URLSearchParams;Object.keys(t).forEach(o=>{n.set(o,String(t[o]))});const a=await fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",requesttoken:String(OC.requestToken||"")},body:n.toString()});return q(a)}r.addEventListener("submit",async e=>{e.preventDefault(),S(),k([]),m(i.saving);try{const t=await g(N,K());k(t.checks);const n=t&&t.api_version?` api=${String(t.api_version)}`:"";l(`${String(t.message||i.saved)}${n}`,"success")}catch(t){t&&typeof t.field=="string"&&t.field!==""&&W(t.field,t.message||i.savingFailed),l(t instanceof Error?t.message:i.savingFailed,"error")}}),H.addEventListener("click",async()=>{S(),k([]),m(i.checking,h);try{const e=await g(P,K());X(e),k(e.checks);const t=Array.isArray(e.checks)&&e.checks.some(n=>n&&n.status==="warning");l(String(e.message),t?"warning":"success",h)}catch(e){e&&typeof e.field=="string"&&e.field!==""&&W(e.field,e.message||i.healthFailed),l(e instanceof Error?e.message:i.healthFailed,"error",h)}}),M instanceof HTMLElement&&M.addEventListener("click",async()=>{S(),m(i.consistencyRunning,d);try{const e=await g(j,{}),t=Number(e.binding_without_file_count||0),n=`${String(e.message||i.consistencyOk)} binding_without_file=${String(t)}`;l(n,t>0?"error":"success",d)}catch(e){l(e instanceof Error?e.message:i.consistencyFailed,"error",d)}}),y instanceof HTMLElement&&y.addEventListener("click",async()=>{S(),m(i.checking,d);try{const e=await g(U,{}),t=[];for(const a of["checked","settled","restore_pending_count","pending_delete_count"])typeof e[a]<"u"&&t.push(`${a}=${String(e[a])}`);X(e);const n=t.length>0?` ${t.join(" | ")}`:"";l(`${String(e.message||"OK")}${n}`,"success",d)}catch(e){l(e instanceof Error?e.message:i.settleFailed,"error",d)}}),R instanceof HTMLElement&&p instanceof HTMLInputElement&&(R.addEventListener("click",()=>{p.click()}),p.addEventListener("change",()=>{const e=p.files&&p.files[0];e&&Q(e),p.value=""}),C()),_&&_.addEventListener("change",z),z();for(const e of[w,L])e&&e.addEventListener("change",J);J()})(); +(function(){const s=document.getElementById("etherpad-nextcloud-admin-settings"),l=document.getElementById("etherpad-nextcloud-admin-form"),g=document.getElementById("etherpad-nextcloud-admin-status"),d=document.getElementById("etherpad-nextcloud-diagnostics-status"),f=document.getElementById("etherpad-nextcloud-connection-status"),H=document.getElementById("etherpad-nextcloud-health-check"),M=document.getElementById("etherpad-nextcloud-consistency-check"),h=document.getElementById("etherpad-nextcloud-settle-pending"),B=document.getElementById("etherpad-nextcloud-pending-actions"),I=document.getElementById("etherpad-nextcloud-pending-count"),$=document.getElementById("etherpad-nextcloud-vanished"),F=document.getElementById("etherpad-nextcloud-vanished-list"),y=l?l.querySelector('input[name="allow_external_pads"]'):null,w=l?l.querySelector('input[name="enable_protected_pads"]'):null,L=l?l.querySelector('input[name="enable_public_pads"]'):null,_=document.getElementById("pad-types-none-hint"),D=document.getElementById("external-pad-allowlist-row"),O=document.getElementById("external-pad-allowlist-hint"),v=document.getElementById("external-pad-allowlist"),E=document.getElementById("epnc-template-list"),N=document.getElementById("epnc-template-empty"),u=document.getElementById("epnc-template-file"),R=document.getElementById("epnc-template-upload"),o=document.getElementById("epnc-template-status"),x={etherpad_host:l.querySelector('[name="etherpad_host"]'),etherpad_api_host:l.querySelector('[name="etherpad_api_host"]'),etherpad_cookie_domain:l.querySelector('[name="etherpad_cookie_domain"]'),etherpad_api_key:l.querySelector('[name="etherpad_api_key"]'),sync_interval_seconds:l.querySelector('[name="sync_interval_seconds"]'),external_pad_allowlist:l.querySelector('[name="external_pad_allowlist"]'),trusted_embed_origins:l.querySelector('[name="trusted_embed_origins"]')};if(!s||!l||!g||!H)return;const j=s.getAttribute("data-save-url")||"",P=s.getAttribute("data-health-url")||"",U=s.getAttribute("data-consistency-url")||"",z=s.getAttribute("data-settle-pending-url")||"",i={saving:s.getAttribute("data-l10n-saving")||"Saving settings...",saved:s.getAttribute("data-l10n-saved")||"Settings saved.",checking:s.getAttribute("data-l10n-checking")||"Testing Etherpad connection...",consistencyRunning:s.getAttribute("data-l10n-consistency-running")||"Running consistency check...",consistencyOk:s.getAttribute("data-l10n-consistency-ok")||"Consistency check successful.",requestFailed:s.getAttribute("data-l10n-request-failed")||"Request failed.",savingFailed:s.getAttribute("data-l10n-saving-failed")||"Failed to save settings.",healthFailed:s.getAttribute("data-l10n-health-failed")||"Etherpad connection test failed.",consistencyFailed:s.getAttribute("data-l10n-consistency-failed")||"Consistency check failed.",pendingDeleteLabel:s.getAttribute("data-l10n-pending-delete-label")||"Pending Etherpad deletes",settleFailed:s.getAttribute("data-l10n-settle-failed")||"Pending pad check failed.",templateUploading:s.getAttribute("data-l10n-template-uploading")||"Uploading template...",templateDelete:s.getAttribute("data-l10n-template-delete")||"Delete",templateTooLarge:s.getAttribute("data-l10n-template-too-large")||"Template file is too large.",templateDeleteLabel:s.getAttribute("data-l10n-template-delete-label")||"Delete template {name}",templateConfirmDelete:s.getAttribute("data-l10n-template-confirm-delete")||"Delete this template for everyone?",templateFailed:s.getAttribute("data-l10n-template-failed")||"Template request failed.",templateConfirmReplace:s.getAttribute("data-l10n-template-confirm-replace")||"Replace the existing template of that name?"},T=s.getAttribute("data-templates-url")||"",ee=s.getAttribute("data-templates-delete-url")||"";if(j===""||P===""||U===""||z==="")return;function J(){const e=!!(y&&y.checked);if(D&&(D.style.display=e?"":"none"),O&&(O.style.display=e?"":"none"),v instanceof HTMLTextAreaElement&&(v.disabled=!e,!e)){v.classList.remove("ep-input-error");const t=l.querySelector('[data-field-error="external_pad_allowlist"]');t instanceof HTMLElement&&(t.textContent="",t.classList.remove("is-visible"))}}function K(){const e=!!(w&&L)&&!w.checked&&!L.checked;if(_ instanceof HTMLElement){const t=e&&_.dataset.message||"";_.textContent!==t&&(_.textContent=t)}}function V(){const e=new FormData(l);return{etherpad_host:String(e.get("etherpad_host")||"").trim(),etherpad_api_host:String(e.get("etherpad_api_host")||"").trim(),etherpad_cookie_domain:String(e.get("etherpad_cookie_domain")||"").trim(),etherpad_api_key:String(e.get("etherpad_api_key")||"").trim(),sync_interval_seconds:Number(e.get("sync_interval_seconds")||120),delete_pad_with_file:e.has("delete_pad_with_file"),enable_protected_pads:e.has("enable_protected_pads"),allow_legacy_protected_import:e.has("allow_legacy_protected_import"),enable_public_pads:e.has("enable_public_pads"),allow_external_pads:e.has("allow_external_pads"),external_pad_allowlist:String(e.get("external_pad_allowlist")||""),trusted_embed_origins:String(e.get("trusted_embed_origins")||"")}}function r(e,t,n=g){n instanceof HTMLElement&&(n.textContent=e,n.classList.remove("ep-status-success","ep-status-warning","ep-status-error"),(t==="success"||t==="warning"||t==="error")&&n.classList.add(`ep-status-${t}`))}function p(e,t=g){const n=t===o?[o]:[g,d,f];for(const a of n)a instanceof HTMLElement&&a!==t&&(a.textContent="",a.classList.remove("ep-status-success","ep-status-warning","ep-status-error"));r(e,null,t)}const G={skipped:0,ok:1,warning:2};function b(e){for(const t of document.querySelectorAll("[data-check-result]"))t.textContent="",t.className="ep-check-result",delete t.dataset.checkStatus;if(Array.isArray(e))for(const t of e){if(!t||typeof t.label!="string")continue;const n=String(t.status||"skipped"),a=typeof t.detail=="string"?t.detail:"",c=t.field?document.querySelector(`[data-check-result="${CSS.escape(String(t.field))}"]`):null;if(!(c instanceof HTMLElement))continue;const Z=c.dataset.checkStatus;Z&&(G[Z]??0)>(G[n]??0)||(c.dataset.checkStatus=n,c.className=`ep-check-result ep-check-${n}`,c.textContent=n==="ok"?t.label:a||t.label)}}function te(e){if(!(E instanceof HTMLElement))return;E.replaceChildren();const t=Array.isArray(e)?e:[];A(t.length===0);for(const n of t)!n||typeof n.name!="string"||E.appendChild(ne(n.name))}function ne(e){const t=document.createElement("li");t.className="ep-template-row";const n=document.createElement("span");n.className="ep-template-name",n.textContent=e,t.appendChild(n);const a=document.createElement("button");return a.type="button",a.textContent=i.templateDelete,a.setAttribute("aria-label",i.templateDeleteLabel.replace("{name}",e)),a.addEventListener("click",()=>{window.confirm(i.templateConfirmDelete)&&se(e)}),t.appendChild(a),t}function A(e){N instanceof HTMLElement&&(N.style.display=e?"":"none")}let Q=0;async function C(){if(T===""||!(E instanceof HTMLElement))return;const e=++Q,t=()=>e===Q;A(!1);try{const n=await fetch(T,{credentials:"same-origin",headers:{requesttoken:String(OC.requestToken||"")}}),a=await q(n);if(!t())return;te(a.templates)}catch(n){if(!t())return;A(!1),r(n instanceof Error?n.message:i.templateFailed,"error",o)}}const ae=2*1024*1024;async function W(e,t=!1){if(typeof e.size=="number"&&e.size>ae){r(i.templateTooLarge,"error",o);return}p(i.templateUploading,o);try{const n=await e.text(),a=await ie(T,{name:e.name,content:n,replace:t});r(String(a.message||""),"success",o),await C()}catch(n){if(!t&&n&&n.field==="template_exists"){if(window.confirm(i.templateConfirmReplace)){await W(e,!0);return}r("",null,o);return}r(n instanceof Error?n.message:i.templateFailed,"error",o)}}async function se(e){try{const t=await m(ee,{name:e});r(String(t.message||""),"success",o),await C()}catch(t){r(t instanceof Error?t.message:i.templateFailed,"error",o)}}function k(){Object.keys(x).forEach(e=>{const t=x[e];t instanceof HTMLElement&&t.classList.remove("ep-input-error");const n=l.querySelector(`[data-field-error="${e}"]`);n instanceof HTMLElement&&(n.textContent="",n.classList.remove("is-visible"))})}function X(e,t){if(!e||!t)return;const n=x[e];n instanceof HTMLElement&&n.classList.add("ep-input-error");const a=l.querySelector(`[data-field-error="${e}"]`);a instanceof HTMLElement&&(a.textContent=t,a.classList.add("is-visible")),n instanceof HTMLElement&&typeof n.focus=="function"&&n.focus()}const S={pendingDeletes:0};function Y(e){const t={};if(typeof e.pending_delete_count<"u"&&(t.pendingDeletes=e.pending_delete_count),Object.keys(t).length!==0){for(const[n,a]of Object.entries(t))S[n]=Number.isFinite(Number(a))?Number(a):0;B instanceof HTMLElement&&(B.style.display=S.pendingDeletes>0?"":"none"),I instanceof HTMLElement&&(I.textContent=`${i.pendingDeleteLabel}: ${String(S.pendingDeletes)}`),h instanceof HTMLButtonElement&&(h.disabled=S.pendingDeletes<=0)}}async function q(e){let t=null;const n=await e.text();try{t=n!==""?JSON.parse(n):null}catch{t=null}if(!e.ok||!t||t.ok!==!0){const a=t&&t.message?String(t.message):`${i.requestFailed} (HTTP ${e.status})`,c=new Error(a);throw c.field=t&&typeof t.field=="string"?t.field:"",c}return t}async function ie(e,t){const n=await fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",requesttoken:String(OC.requestToken||"")},body:JSON.stringify(t)});return q(n)}async function m(e,t){const n=new URLSearchParams;Object.keys(t).forEach(c=>{n.set(c,String(t[c]))});const a=await fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",requesttoken:String(OC.requestToken||"")},body:n.toString()});return q(a)}l.addEventListener("submit",async e=>{e.preventDefault(),k(),b([]),p(i.saving);try{const t=await m(j,V());b(t.checks);const n=t&&t.api_version?` api=${String(t.api_version)}`:"";r(`${String(t.message||i.saved)}${n}`,"success")}catch(t){t&&typeof t.field=="string"&&t.field!==""&&X(t.field,t.message||i.savingFailed),r(t instanceof Error?t.message:i.savingFailed,"error")}}),H.addEventListener("click",async()=>{k(),b([]),p(i.checking,f);try{const e=await m(P,V());Y(e),b(e.checks);const t=Array.isArray(e.checks)&&e.checks.some(n=>n&&n.status==="warning");r(String(e.message),t?"warning":"success",f)}catch(e){e&&typeof e.field=="string"&&e.field!==""&&X(e.field,e.message||i.healthFailed),r(e instanceof Error?e.message:i.healthFailed,"error",f)}}),M instanceof HTMLElement&&M.addEventListener("click",async()=>{k(),p(i.consistencyRunning,d);try{const e=await m(U,{}),t=Number(e.vanished_file_count||0),n=`${String(e.message||i.consistencyOk)} vanished_file=${String(t)}`;r(n,t>0?"error":"success",d),le(e.samples&&e.samples.vanished_files)}catch(e){r(e instanceof Error?e.message:i.consistencyFailed,"error",d)}});function le(e){if(!($ instanceof HTMLElement)||!(F instanceof HTMLElement))return;const t=(Array.isArray(e)?e:[]).filter(n=>n&&typeof n.pad_id=="string").map(n=>{const a=document.createElement("li");return a.textContent=`${n.pad_id} (fileid ${String(n.file_id)})`,a});F.replaceChildren(...t),$.style.display=t.length>0?"":"none"}h instanceof HTMLElement&&h.addEventListener("click",async()=>{k(),p(i.checking,d);try{const e=await m(z,{}),t=[];for(const a of["checked","settled","pending_delete_count"])typeof e[a]<"u"&&t.push(`${a}=${String(e[a])}`);Y(e);const n=t.length>0?` ${t.join(" | ")}`:"";r(`${String(e.message||"OK")}${n}`,"success",d)}catch(e){r(e instanceof Error?e.message:i.settleFailed,"error",d)}}),R instanceof HTMLElement&&u instanceof HTMLInputElement&&(R.addEventListener("click",()=>{u.click()}),u.addEventListener("change",()=>{const e=u.files&&u.files[0];e&&W(e),u.value=""}),C()),y&&y.addEventListener("change",J),J();for(const e of[w,L])e&&e.addEventListener("change",K);K()})(); //# sourceMappingURL=etherpad_nextcloud-admin-settings.mjs.map diff --git a/js/etherpad_nextcloud-admin-settings.mjs.map b/js/etherpad_nextcloud-admin-settings.mjs.map index 6a97aa56..2730ff0c 100644 --- a/js/etherpad_nextcloud-admin-settings.mjs.map +++ b/js/etherpad_nextcloud-admin-settings.mjs.map @@ -1 +1 @@ -{"version":3,"file":"etherpad_nextcloud-admin-settings.mjs","sources":["../src/admin-settings.js"],"sourcesContent":["(function () {\n\t'use strict'\n\n\tconst root = document.getElementById('etherpad-nextcloud-admin-settings')\n\tconst form = document.getElementById('etherpad-nextcloud-admin-form')\n\tconst statusNode = document.getElementById('etherpad-nextcloud-admin-status')\n\tconst diagnosticsTarget = document.getElementById('etherpad-nextcloud-diagnostics-status')\n\tconst connectionTarget = document.getElementById('etherpad-nextcloud-connection-status')\n\tconst healthButton = document.getElementById('etherpad-nextcloud-health-check')\n\tconst consistencyButton = document.getElementById('etherpad-nextcloud-consistency-check')\n\tconst settlePendingButton = document.getElementById('etherpad-nextcloud-settle-pending')\n\tconst pendingActions = document.getElementById('etherpad-nextcloud-pending-actions')\n\tconst pendingCountNode = document.getElementById('etherpad-nextcloud-pending-count')\n\tconst restorePendingCountNode = document.getElementById('etherpad-nextcloud-restore-pending-count')\n\tconst allowExternalCheckbox = form ? form.querySelector('input[name=\"allow_external_pads\"]') : null\n\tconst protectedPadsCheckbox = form ? form.querySelector('input[name=\"enable_protected_pads\"]') : null\n\tconst publicPadsCheckbox = form ? form.querySelector('input[name=\"enable_public_pads\"]') : null\n\tconst padTypesNoneHint = document.getElementById('pad-types-none-hint')\n\tconst allowlistRow = document.getElementById('external-pad-allowlist-row')\n\tconst allowlistHint = document.getElementById('external-pad-allowlist-hint')\n\tconst allowlistTextarea = document.getElementById('external-pad-allowlist')\n\tconst templateListNode = document.getElementById('epnc-template-list')\n\tconst templateEmptyNode = document.getElementById('epnc-template-empty')\n\tconst templateFileInput = document.getElementById('epnc-template-file')\n\tconst templateUploadButton = document.getElementById('epnc-template-upload')\n\tconst templateStatusNode = document.getElementById('epnc-template-status')\n\tconst fieldNodes = {\n\t\tetherpad_host: form.querySelector('[name=\"etherpad_host\"]'),\n\t\tetherpad_api_host: form.querySelector('[name=\"etherpad_api_host\"]'),\n\t\tetherpad_cookie_domain: form.querySelector('[name=\"etherpad_cookie_domain\"]'),\n\t\tetherpad_api_key: form.querySelector('[name=\"etherpad_api_key\"]'),\n\t\tsync_interval_seconds: form.querySelector('[name=\"sync_interval_seconds\"]'),\n\t\texternal_pad_allowlist: form.querySelector('[name=\"external_pad_allowlist\"]'),\n\t\ttrusted_embed_origins: form.querySelector('[name=\"trusted_embed_origins\"]'),\n\t}\n\n\tif (!root || !form || !statusNode || !healthButton) {\n\t\treturn\n\t}\n\n\tconst saveUrl = root.getAttribute('data-save-url') || ''\n\tconst healthUrl = root.getAttribute('data-health-url') || ''\n\tconst consistencyUrl = root.getAttribute('data-consistency-url') || ''\n\tconst settlePendingUrl = root.getAttribute('data-settle-pending-url') || ''\n\tconst l10n = {\n\t\tsaving: root.getAttribute('data-l10n-saving') || 'Saving settings...',\n\t\tsaved: root.getAttribute('data-l10n-saved') || 'Settings saved.',\n\t\tchecking: root.getAttribute('data-l10n-checking') || 'Testing Etherpad connection...',\n\t\tconsistencyRunning: root.getAttribute('data-l10n-consistency-running') || 'Running consistency check...',\n\t\tconsistencyOk: root.getAttribute('data-l10n-consistency-ok') || 'Consistency check successful.',\n\t\trequestFailed: root.getAttribute('data-l10n-request-failed') || 'Request failed.',\n\t\tsavingFailed: root.getAttribute('data-l10n-saving-failed') || 'Failed to save settings.',\n\t\thealthFailed: root.getAttribute('data-l10n-health-failed') || 'Etherpad connection test failed.',\n\t\tconsistencyFailed: root.getAttribute('data-l10n-consistency-failed') || 'Consistency check failed.',\n\t\tpendingDeleteLabel: root.getAttribute('data-l10n-pending-delete-label') || 'Pending Etherpad deletes',\n\t\trestorePendingLabel: root.getAttribute('data-l10n-restore-pending-label') || 'Unresolved restores',\n\t\tsettleFailed: root.getAttribute('data-l10n-settle-failed') || 'Pending pad check failed.',\n\t\ttemplateUploading: root.getAttribute('data-l10n-template-uploading') || 'Uploading template...',\n\t\ttemplateDelete: root.getAttribute('data-l10n-template-delete') || 'Delete',\n\t\ttemplateTooLarge: root.getAttribute('data-l10n-template-too-large') || 'Template file is too large.',\n\t\ttemplateDeleteLabel: root.getAttribute('data-l10n-template-delete-label') || 'Delete template {name}',\n\t\ttemplateConfirmDelete: root.getAttribute('data-l10n-template-confirm-delete') || 'Delete this template for everyone?',\n\t\ttemplateFailed: root.getAttribute('data-l10n-template-failed') || 'Template request failed.',\n\t\ttemplateConfirmReplace: root.getAttribute('data-l10n-template-confirm-replace') || 'Replace the existing template of that name?',\n\t}\n\tconst templatesUrl = root.getAttribute('data-templates-url') || ''\n\tconst templatesDeleteUrl = root.getAttribute('data-templates-delete-url') || ''\n\n\tif (saveUrl === '' || healthUrl === '' || consistencyUrl === '' || settlePendingUrl === '') {\n\t\treturn\n\t}\n\n\tfunction updateExternalSettingsVisibility() {\n\t\tconst enabled = !!(allowExternalCheckbox && allowExternalCheckbox.checked)\n\t\tif (allowlistRow) {\n\t\t\tallowlistRow.style.display = enabled ? '' : 'none'\n\t\t}\n\t\tif (allowlistHint) {\n\t\t\tallowlistHint.style.display = enabled ? '' : 'none'\n\t\t}\n\t\tif (allowlistTextarea instanceof HTMLTextAreaElement) {\n\t\t\tallowlistTextarea.disabled = !enabled\n\t\t\tif (!enabled) {\n\t\t\t\tallowlistTextarea.classList.remove('ep-input-error')\n\t\t\t\tconst errorNode = form.querySelector('[data-field-error=\"external_pad_allowlist\"]')\n\t\t\t\tif (errorNode instanceof HTMLElement) {\n\t\t\t\t\terrorNode.textContent = ''\n\t\t\t\t\terrorNode.classList.remove('is-visible')\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction updatePadTypesHint() {\n\t\tconst noneEnabled = !!(protectedPadsCheckbox && publicPadsCheckbox)\n\t\t\t&& !protectedPadsCheckbox.checked\n\t\t\t&& !publicPadsCheckbox.checked\n\t\tif (padTypesNoneHint instanceof HTMLElement) {\n\t\t\t// Write the text instead of toggling visibility: a live region only\n\t\t\t// announces content changes, and an element returning from\n\t\t\t// `display: none` reads as initial content. `.ep-field-hint:empty`\n\t\t\t// collapses the empty paragraph, so it looks the same.\n\t\t\tconst message = noneEnabled ? (padTypesNoneHint.dataset.message || '') : ''\n\t\t\t// Rewriting the same text would announce it again on load.\n\t\t\tif (padTypesNoneHint.textContent !== message) {\n\t\t\t\tpadTypesNoneHint.textContent = message\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction getPayload() {\n\t\tconst data = new FormData(form)\n\t\treturn {\n\t\t\tetherpad_host: String(data.get('etherpad_host') || '').trim(),\n\t\t\tetherpad_api_host: String(data.get('etherpad_api_host') || '').trim(),\n\t\t\tetherpad_cookie_domain: String(data.get('etherpad_cookie_domain') || '').trim(),\n\t\t\tetherpad_api_key: String(data.get('etherpad_api_key') || '').trim(),\n\t\t\tsync_interval_seconds: Number(data.get('sync_interval_seconds') || 120),\n\t\t\tdelete_on_trash: data.has('delete_on_trash'),\n\t\t\tenable_protected_pads: data.has('enable_protected_pads'),\n\t\t\tallow_legacy_protected_import: data.has('allow_legacy_protected_import'),\n\t\t\tenable_public_pads: data.has('enable_public_pads'),\n\t\t\tallow_external_pads: data.has('allow_external_pads'),\n\t\t\texternal_pad_allowlist: String(data.get('external_pad_allowlist') || ''),\n\t\t\ttrusted_embed_origins: String(data.get('trusted_embed_origins') || ''),\n\t\t}\n\t}\n\n\t// Writing a status touches only its own area, so a late response cannot\n\t// wipe out the other action's result.\n\tfunction setStatus(message, state, node = statusNode) {\n\t\tif (!(node instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tnode.textContent = message\n\t\tnode.classList.remove('ep-status-success', 'ep-status-warning', 'ep-status-error')\n\t\tif (state === 'success' || state === 'warning' || state === 'error') {\n\t\t\tnode.classList.add(`ep-status-${state}`)\n\t\t}\n\t}\n\n\t// Starting one does clear the other: its result predates this action and\n\t// would be read as belonging to it. The template status is its own group —\n\t// uploading a template makes neither a connection test nor a save result\n\t// stale, and vice versa.\n\tfunction beginStatus(message, node = statusNode) {\n\t\tconst group = node === templateStatusNode\n\t\t\t? [templateStatusNode]\n\t\t\t: [statusNode, diagnosticsTarget, connectionTarget]\n\t\tfor (const other of group) {\n\t\t\tif (other instanceof HTMLElement && other !== node) {\n\t\t\t\tother.textContent = ''\n\t\t\t\tother.classList.remove('ep-status-success', 'ep-status-warning', 'ep-status-error')\n\t\t\t}\n\t\t}\n\t\tsetStatus(message, null, node)\n\t}\n\n\t// Higher wins when two checks land on the same field, so a problem is\n\t// never hidden by a passing verdict that happened to come later.\n\tconst CHECK_SEVERITY = { skipped: 0, ok: 1, warning: 2 }\n\n\t// Each result is shown at the field it came from: a green tick where\n\t// things are fine, the message itself where they are not.\n\tfunction renderConnectionChecks(checks) {\n\t\tfor (const slot of document.querySelectorAll('[data-check-result]')) {\n\t\t\tslot.textContent = ''\n\t\t\tslot.className = 'ep-check-result'\n\t\t\tdelete slot.dataset.checkStatus\n\t\t}\n\t\tif (!Array.isArray(checks)) {\n\t\t\treturn\n\t\t}\n\t\tfor (const check of checks) {\n\t\t\tif (!check || typeof check.label !== 'string') {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst status = String(check.status || 'skipped')\n\t\t\tconst detail = typeof check.detail === 'string' ? check.detail : ''\n\t\t\tconst slot = check.field\n\t\t\t\t? document.querySelector(`[data-check-result=\"${CSS.escape(String(check.field))}\"]`)\n\t\t\t\t: null\n\t\t\tif (!(slot instanceof HTMLElement)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst shown = slot.dataset.checkStatus\n\t\t\tif (shown && (CHECK_SEVERITY[shown] ?? 0) > (CHECK_SEVERITY[status] ?? 0)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tslot.dataset.checkStatus = status\n\t\t\tslot.className = `ep-check-result ep-check-${status}`\n\t\t\t// A passing field needs no prose — the tick and the label say it.\n\t\t\t// A failing one needs the reason right there.\n\t\t\tslot.textContent = status === 'ok' ? check.label : (detail || check.label)\n\t\t}\n\t}\n\n\t// Shared templates: an admin uploads .pad files that everyone then sees as\n\t// tiles in Nextcloud's picker.\n\tfunction renderTemplates(templates) {\n\t\tif (!(templateListNode instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\ttemplateListNode.replaceChildren()\n\t\tconst list = Array.isArray(templates) ? templates : []\n\t\tshowTemplateEmptyState(list.length === 0)\n\t\tfor (const template of list) {\n\t\t\tif (!template || typeof template.name !== 'string') {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttemplateListNode.appendChild(buildTemplateRow(template.name))\n\t\t}\n\t}\n\n\tfunction buildTemplateRow(name) {\n\t\tconst row = document.createElement('li')\n\t\trow.className = 'ep-template-row'\n\n\t\tconst label = document.createElement('span')\n\t\tlabel.className = 'ep-template-name'\n\t\tlabel.textContent = name\n\t\trow.appendChild(label)\n\n\t\tconst remove = document.createElement('button')\n\t\tremove.type = 'button'\n\t\tremove.textContent = l10n.templateDelete\n\t\t// The visible label repeats on every row, so the accessible name has to\n\t\t// carry the name of the template this one removes.\n\t\tremove.setAttribute('aria-label', l10n.templateDeleteLabel.replace('{name}', name))\n\t\tremove.addEventListener('click', () => {\n\t\t\tif (!window.confirm(l10n.templateConfirmDelete)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvoid deleteTemplate(name)\n\t\t})\n\t\trow.appendChild(remove)\n\t\treturn row\n\t}\n\n\tfunction showTemplateEmptyState(visible) {\n\t\tif (templateEmptyNode instanceof HTMLElement) {\n\t\t\ttemplateEmptyNode.style.display = visible ? '' : 'none'\n\t\t}\n\t}\n\n\t// Every upload and delete starts another listing while the first may still\n\t// be in flight. Without this the slower answer wins whenever it happens to\n\t// arrive last, putting a deleted template back on the page or replacing a\n\t// fresh result with an old error.\n\tlet templateListGeneration = 0\n\n\tasync function loadTemplates() {\n\t\tif (templatesUrl === '' || !(templateListNode instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tconst generation = ++templateListGeneration\n\t\tconst isCurrent = () => generation === templateListGeneration\n\n\t\t// \"No shared templates yet\" is an answer, and we do not have one until\n\t\t// the request comes back — showing it next to an error would claim the\n\t\t// list is empty when we simply could not read it.\n\t\tshowTemplateEmptyState(false)\n\t\ttry {\n\t\t\tconst response = await fetch(templatesUrl, {\n\t\t\t\tcredentials: 'same-origin',\n\t\t\t\theaders: { requesttoken: String(OC.requestToken || '') },\n\t\t\t})\n\t\t\tconst data = await readJsonResponse(response)\n\t\t\tif (!isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trenderTemplates(data.templates)\n\t\t} catch (error) {\n\t\t\tif (!isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshowTemplateEmptyState(false)\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.templateFailed, 'error', templateStatusNode)\n\t\t}\n\t}\n\n\t// The same limit the server enforces. Without it a mis-picked large file is\n\t// read into memory and posted, only to hit post_max_size or the memory\n\t// limit — a failure that says nothing, instead of the sentence below.\n\tconst MAX_TEMPLATE_BYTES = 2 * 1024 * 1024\n\n\tasync function uploadTemplate(file, replace = false) {\n\t\tif (typeof file.size === 'number' && file.size > MAX_TEMPLATE_BYTES) {\n\t\t\tsetStatus(l10n.templateTooLarge, 'error', templateStatusNode)\n\t\t\treturn\n\t\t}\n\t\tbeginStatus(l10n.templateUploading, templateStatusNode)\n\t\ttry {\n\t\t\tconst content = await file.text()\n\t\t\tconst data = await postJsonBody(templatesUrl, { name: file.name, content, replace })\n\t\t\tsetStatus(String(data.message || ''), 'success', templateStatusNode)\n\t\t\tawait loadTemplates()\n\t\t} catch (error) {\n\t\t\t// The server refuses to overwrite unless asked, so a name that is\n\t\t\t// already taken comes back as a question rather than a failure.\n\t\t\tif (!replace && error && error.field === 'template_exists') {\n\t\t\t\tif (window.confirm(l10n.templateConfirmReplace)) {\n\t\t\t\t\tawait uploadTemplate(file, true)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsetStatus('', null, templateStatusNode)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.templateFailed, 'error', templateStatusNode)\n\t\t}\n\t}\n\n\tasync function deleteTemplate(name) {\n\t\ttry {\n\t\t\tconst data = await postJson(templatesDeleteUrl, { name })\n\t\t\tsetStatus(String(data.message || ''), 'success', templateStatusNode)\n\t\t\tawait loadTemplates()\n\t\t} catch (error) {\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.templateFailed, 'error', templateStatusNode)\n\t\t}\n\t}\n\n\tfunction clearFieldErrors() {\n\t\tObject.keys(fieldNodes).forEach((field) => {\n\t\t\tconst input = fieldNodes[field]\n\t\t\tif (input instanceof HTMLElement) {\n\t\t\t\tinput.classList.remove('ep-input-error')\n\t\t\t}\n\t\t\tconst errorNode = form.querySelector(`[data-field-error=\"${field}\"]`)\n\t\t\tif (errorNode instanceof HTMLElement) {\n\t\t\t\terrorNode.textContent = ''\n\t\t\t\terrorNode.classList.remove('is-visible')\n\t\t\t}\n\t\t})\n\t}\n\n\tfunction showFieldError(field, message) {\n\t\tif (!field || !message) {\n\t\t\treturn\n\t\t}\n\t\tconst input = fieldNodes[field]\n\t\tif (input instanceof HTMLElement) {\n\t\t\tinput.classList.add('ep-input-error')\n\t\t}\n\t\tconst errorNode = form.querySelector(`[data-field-error=\"${field}\"]`)\n\t\tif (errorNode instanceof HTMLElement) {\n\t\t\terrorNode.textContent = message\n\t\t\terrorNode.classList.add('is-visible')\n\t\t}\n\t\tif (input instanceof HTMLElement && typeof input.focus === 'function') {\n\t\t\tinput.focus()\n\t\t}\n\t}\n\n\tconst bindingCounts = { pendingDeletes: 0, pendingRestores: 0 }\n\n\t// Only the counts a response carries; one that carries none leaves the\n\t// panel as it was rather than repainting it from what this page assumed.\n\t// The health check and the pending pad check name them the same.\n\tfunction updateBindingCounts(data) {\n\t\tconst counts = {}\n\t\tif (typeof data.pending_delete_count !== 'undefined') {\n\t\t\tcounts.pendingDeletes = data.pending_delete_count\n\t\t}\n\t\tif (typeof data.restore_pending_count !== 'undefined') {\n\t\t\tcounts.pendingRestores = data.restore_pending_count\n\t\t}\n\t\tif (Object.keys(counts).length === 0) {\n\t\t\treturn\n\t\t}\n\t\tfor (const [key, value] of Object.entries(counts)) {\n\t\t\tbindingCounts[key] = Number.isFinite(Number(value)) ? Number(value) : 0\n\t\t}\n\t\tif (pendingActions instanceof HTMLElement) {\n\t\t\tpendingActions.style.display = bindingCounts.pendingDeletes > 0 || bindingCounts.pendingRestores > 0 ? '' : 'none'\n\t\t}\n\t\tif (pendingCountNode instanceof HTMLElement) {\n\t\t\tpendingCountNode.textContent = `${l10n.pendingDeleteLabel}: ${String(bindingCounts.pendingDeletes)}`\n\t\t}\n\t\tif (restorePendingCountNode instanceof HTMLElement) {\n\t\t\trestorePendingCountNode.textContent = `${l10n.restorePendingLabel}: ${String(bindingCounts.pendingRestores)}`\n\t\t}\n\t\t// The check deletes a pad only once its file is gone for good, and\n\t\t// nothing here is more than a nudge to the job that does the same.\n\t\tif (settlePendingButton instanceof HTMLButtonElement) {\n\t\t\tsettlePendingButton.disabled = bindingCounts.pendingDeletes <= 0 && bindingCounts.pendingRestores <= 0\n\t\t}\n\t}\n\n\t// One place decides what a response means, so a caller cannot forget to\n\t// look at the status or at `ok` in the body.\n\tasync function readJsonResponse(response) {\n\t\tlet data = null\n\t\tconst responseText = await response.text()\n\t\ttry {\n\t\t\tdata = responseText !== '' ? JSON.parse(responseText) : null\n\t\t} catch (error) {\n\t\t\tdata = null\n\t\t}\n\n\t\tif (!response.ok || !data || data.ok !== true) {\n\t\t\t// Only our own JSON is quoted: another body came from something\n\t\t\t// between the browser and the app, and showing its markup reads\n\t\t\t// as an app failure. The status says more than the markup does.\n\t\t\tconst message = (data && data.message)\n\t\t\t\t? String(data.message)\n\t\t\t\t: `${l10n.requestFailed} (HTTP ${response.status})`\n\t\t\tconst err = new Error(message)\n\t\t\terr.field = (data && typeof data.field === 'string') ? data.field : ''\n\t\t\tthrow err\n\t\t}\n\n\t\treturn data\n\t}\n\n\t/**\n\t * POST a JSON body. Used for the template upload, where URL-encoding a\n\t * whole file would inflate it several times over.\n\t */\n\tasync function postJsonBody(url, payload) {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\tcredentials: 'same-origin',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\trequesttoken: String(OC.requestToken || ''),\n\t\t\t},\n\t\t\tbody: JSON.stringify(payload),\n\t\t})\n\t\treturn readJsonResponse(response)\n\t}\n\n\tasync function postJson(url, payload) {\n\t\tconst body = new URLSearchParams()\n\t\tObject.keys(payload).forEach((key) => {\n\t\t\tbody.set(key, String(payload[key]))\n\t\t})\n\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\tcredentials: 'same-origin',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t\t\trequesttoken: String(OC.requestToken || ''),\n\t\t\t},\n\t\t\tbody: body.toString(),\n\t\t})\n\n\t\treturn readJsonResponse(response)\n\t}\n\n\tform.addEventListener('submit', async (event) => {\n\t\tevent.preventDefault()\n\t\tclearFieldErrors()\n\t\t// Verdicts describe the values of the previous run: keeping them up\n\t\t// while this one is in flight puts a green tick next to a field that\n\t\t// is being changed, and a failed save would leave them there.\n\t\trenderConnectionChecks([])\n\t\tbeginStatus(l10n.saving)\n\t\ttry {\n\t\t\tconst data = await postJson(saveUrl, getPayload())\n\t\t\t// Saving answers with the cookie verdict alone; rendering it clears\n\t\t\t// the other fields' results, which the save just invalidated.\n\t\t\trenderConnectionChecks(data.checks)\n\t\t\tconst versionSuffix = data && data.api_version ? ` api=${String(data.api_version)}` : ''\n\t\t\tsetStatus(`${String(data.message || l10n.saved)}${versionSuffix}`, 'success')\n\t\t} catch (error) {\n\t\t\tif (error && typeof error.field === 'string' && error.field !== '') {\n\t\t\t\tshowFieldError(error.field, error.message || l10n.savingFailed)\n\t\t\t}\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.savingFailed, 'error')\n\t\t}\n\t})\n\n\thealthButton.addEventListener('click', async () => {\n\t\tclearFieldErrors()\n\t\trenderConnectionChecks([])\n\t\tbeginStatus(l10n.checking, connectionTarget)\n\t\ttry {\n\t\t\tconst data = await postJson(healthUrl, getPayload())\n\t\t\tupdateBindingCounts(data)\n\t\t\t// The per-field results carry the target and latency and the\n\t\t\t// protected-pads verdict, so the summary stays a summary.\n\t\t\trenderConnectionChecks(data.checks)\n\t\t\tconst needsAttention = Array.isArray(data.checks)\n\t\t\t\t&& data.checks.some((check) => check && check.status === 'warning')\n\t\t\tsetStatus(String(data.message), needsAttention ? 'warning' : 'success', connectionTarget)\n\t\t} catch (error) {\n\t\t\tif (error && typeof error.field === 'string' && error.field !== '') {\n\t\t\t\tshowFieldError(error.field, error.message || l10n.healthFailed)\n\t\t\t}\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.healthFailed, 'error', connectionTarget)\n\t\t}\n\t})\n\n\tif (consistencyButton instanceof HTMLElement) {\n\t\tconsistencyButton.addEventListener('click', async () => {\n\t\t\tclearFieldErrors()\n\t\t\tbeginStatus(l10n.consistencyRunning, diagnosticsTarget)\n\t\t\ttry {\n\t\t\t\tconst data = await postJson(consistencyUrl, {})\n\t\t\t\tconst bindingWithoutFile = Number(data.binding_without_file_count || 0)\n\t\t\t\tconst message = `${String(data.message || l10n.consistencyOk)} binding_without_file=${String(bindingWithoutFile)}`\n\t\t\t\tsetStatus(message, bindingWithoutFile > 0 ? 'error' : 'success', diagnosticsTarget)\n\t\t\t} catch (error) {\n\t\t\t\tsetStatus(error instanceof Error ? error.message : l10n.consistencyFailed, 'error', diagnosticsTarget)\n\t\t\t}\n\t\t})\n\t}\n\n\tif (settlePendingButton instanceof HTMLElement) {\n\t\tsettlePendingButton.addEventListener('click', async () => {\n\t\t\tclearFieldErrors()\n\t\t\tbeginStatus(l10n.checking, diagnosticsTarget)\n\t\t\ttry {\n\t\t\t\tconst data = await postJson(settlePendingUrl, {})\n\t\t\t\tconst details = []\n\t\t\t\tfor (const key of ['checked', 'settled', 'restore_pending_count', 'pending_delete_count']) {\n\t\t\t\t\tif (typeof data[key] !== 'undefined') {\n\t\t\t\t\t\tdetails.push(`${key}=${String(data[key])}`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tupdateBindingCounts(data)\n\t\t\t\tconst suffix = details.length > 0 ? ` ${details.join(' | ')}` : ''\n\t\t\t\tsetStatus(`${String(data.message || 'OK')}${suffix}`, 'success', diagnosticsTarget)\n\t\t\t} catch (error) {\n\t\t\t\tsetStatus(error instanceof Error ? error.message : l10n.settleFailed, 'error', diagnosticsTarget)\n\t\t\t}\n\t\t})\n\t}\n\n\tif (templateUploadButton instanceof HTMLElement && templateFileInput instanceof HTMLInputElement) {\n\t\ttemplateUploadButton.addEventListener('click', () => {\n\t\t\ttemplateFileInput.click()\n\t\t})\n\t\ttemplateFileInput.addEventListener('change', () => {\n\t\t\tconst file = templateFileInput.files && templateFileInput.files[0]\n\t\t\tif (file) {\n\t\t\t\tvoid uploadTemplate(file)\n\t\t\t}\n\t\t\t// Reset so picking the same file twice fires again.\n\t\t\ttemplateFileInput.value = ''\n\t\t})\n\t\tvoid loadTemplates()\n\t}\n\n\tif (allowExternalCheckbox) {\n\t\tallowExternalCheckbox.addEventListener('change', updateExternalSettingsVisibility)\n\t}\n\tupdateExternalSettingsVisibility()\n\n\tfor (const checkbox of [protectedPadsCheckbox, publicPadsCheckbox]) {\n\t\tif (checkbox) {\n\t\t\tcheckbox.addEventListener('change', updatePadTypesHint)\n\t\t}\n\t}\n\tupdatePadTypesHint()\n})()\n"],"names":["root","form","statusNode","diagnosticsTarget","connectionTarget","healthButton","consistencyButton","settlePendingButton","pendingActions","pendingCountNode","restorePendingCountNode","allowExternalCheckbox","protectedPadsCheckbox","publicPadsCheckbox","padTypesNoneHint","allowlistRow","allowlistHint","allowlistTextarea","templateListNode","templateEmptyNode","templateFileInput","templateUploadButton","templateStatusNode","fieldNodes","saveUrl","healthUrl","consistencyUrl","settlePendingUrl","l10n","templatesUrl","templatesDeleteUrl","updateExternalSettingsVisibility","enabled","errorNode","updatePadTypesHint","noneEnabled","message","getPayload","data","setStatus","state","node","beginStatus","group","other","CHECK_SEVERITY","renderConnectionChecks","checks","slot","check","status","detail","shown","renderTemplates","templates","list","showTemplateEmptyState","template","buildTemplateRow","name","row","label","remove","deleteTemplate","visible","templateListGeneration","loadTemplates","generation","isCurrent","response","readJsonResponse","error","MAX_TEMPLATE_BYTES","uploadTemplate","file","replace","content","postJsonBody","postJson","clearFieldErrors","field","input","showFieldError","bindingCounts","updateBindingCounts","counts","key","value","responseText","err","url","payload","body","event","versionSuffix","needsAttention","bindingWithoutFile","details","suffix","checkbox"],"mappings":"CAAC,UAAY,CAGZ,MAAMA,EAAO,SAAS,eAAe,mCAAmC,EAClEC,EAAO,SAAS,eAAe,+BAA+B,EAC9DC,EAAa,SAAS,eAAe,iCAAiC,EACtEC,EAAoB,SAAS,eAAe,uCAAuC,EACnFC,EAAmB,SAAS,eAAe,sCAAsC,EACjFC,EAAe,SAAS,eAAe,iCAAiC,EACxEC,EAAoB,SAAS,eAAe,sCAAsC,EAClFC,EAAsB,SAAS,eAAe,mCAAmC,EACjFC,EAAiB,SAAS,eAAe,oCAAoC,EAC7EC,EAAmB,SAAS,eAAe,kCAAkC,EAC7EC,EAA0B,SAAS,eAAe,0CAA0C,EAC5FC,EAAwBV,EAAOA,EAAK,cAAc,mCAAmC,EAAI,KACzFW,EAAwBX,EAAOA,EAAK,cAAc,qCAAqC,EAAI,KAC3FY,EAAqBZ,EAAOA,EAAK,cAAc,kCAAkC,EAAI,KACrFa,EAAmB,SAAS,eAAe,qBAAqB,EAChEC,EAAe,SAAS,eAAe,4BAA4B,EACnEC,EAAgB,SAAS,eAAe,6BAA6B,EACrEC,EAAoB,SAAS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B,EAChBrC,EAAYd,EAAK,SAAUzB,CAAiB,EAC5C,GAAI,CACH,MAAMmC,EAAO,MAAMwC,EAASnD,EAAkB,CAAA,CAAE,EAC1CsE,EAAU,CAAA,EAChB,UAAWX,IAAO,CAAC,UAAW,UAAW,wBAAyB,sBAAsB,EACnF,OAAOhD,EAAKgD,CAAG,EAAM,KACxBW,EAAQ,KAAK,GAAGX,CAAG,IAAI,OAAOhD,EAAKgD,CAAG,CAAC,CAAC,EAAE,EAG5CF,EAAoB9C,CAAI,EACxB,MAAM4D,EAASD,EAAQ,OAAS,EAAI,IAAIA,EAAQ,KAAK,KAAK,CAAC,GAAK,GAChE1D,EAAU,GAAG,OAAOD,EAAK,SAAW,IAAI,CAAC,GAAG4D,CAAM,GAAI,UAAW/F,CAAiB,CACnF,OAASoE,EAAO,CACfhC,EAAUgC,aAAiB,MAAQA,EAAM,QAAU3C,EAAK,aAAc,QAASzB,CAAiB,CACjG,CACD,CAAC,EAGEkB,aAAgC,aAAeD,aAA6B,mBAC/EC,EAAqB,iBAAiB,QAAS,IAAM,CACpDD,EAAkB,MAAK,CACxB,CAAC,EACDA,EAAkB,iBAAiB,SAAU,IAAM,CAClD,MAAMsD,EAAOtD,EAAkB,OAASA,EAAkB,MAAM,CAAC,EAC7DsD,GACED,EAAeC,CAAI,EAGzBtD,EAAkB,MAAQ,EAC3B,CAAC,EACI8C,EAAa,GAGfvD,GACHA,EAAsB,iBAAiB,SAAUoB,CAAgC,EAElFA,EAAgC,EAEhC,UAAWoE,IAAY,CAACvF,EAAuBC,CAAkB,EAC5DsF,GACHA,EAAS,iBAAiB,SAAUjE,CAAkB,EAGxDA,EAAkB,CACnB,GAAC"} \ No newline at end of file +{"version":3,"file":"etherpad_nextcloud-admin-settings.mjs","sources":["../src/admin-settings.js"],"sourcesContent":["(function () {\n\t'use strict'\n\n\tconst root = document.getElementById('etherpad-nextcloud-admin-settings')\n\tconst form = document.getElementById('etherpad-nextcloud-admin-form')\n\tconst statusNode = document.getElementById('etherpad-nextcloud-admin-status')\n\tconst diagnosticsTarget = document.getElementById('etherpad-nextcloud-diagnostics-status')\n\tconst connectionTarget = document.getElementById('etherpad-nextcloud-connection-status')\n\tconst healthButton = document.getElementById('etherpad-nextcloud-health-check')\n\tconst consistencyButton = document.getElementById('etherpad-nextcloud-consistency-check')\n\tconst settlePendingButton = document.getElementById('etherpad-nextcloud-settle-pending')\n\tconst pendingActions = document.getElementById('etherpad-nextcloud-pending-actions')\n\tconst pendingCountNode = document.getElementById('etherpad-nextcloud-pending-count')\n\tconst vanishedNode = document.getElementById('etherpad-nextcloud-vanished')\n\tconst vanishedList = document.getElementById('etherpad-nextcloud-vanished-list')\n\tconst allowExternalCheckbox = form ? form.querySelector('input[name=\"allow_external_pads\"]') : null\n\tconst protectedPadsCheckbox = form ? form.querySelector('input[name=\"enable_protected_pads\"]') : null\n\tconst publicPadsCheckbox = form ? form.querySelector('input[name=\"enable_public_pads\"]') : null\n\tconst padTypesNoneHint = document.getElementById('pad-types-none-hint')\n\tconst allowlistRow = document.getElementById('external-pad-allowlist-row')\n\tconst allowlistHint = document.getElementById('external-pad-allowlist-hint')\n\tconst allowlistTextarea = document.getElementById('external-pad-allowlist')\n\tconst templateListNode = document.getElementById('epnc-template-list')\n\tconst templateEmptyNode = document.getElementById('epnc-template-empty')\n\tconst templateFileInput = document.getElementById('epnc-template-file')\n\tconst templateUploadButton = document.getElementById('epnc-template-upload')\n\tconst templateStatusNode = document.getElementById('epnc-template-status')\n\tconst fieldNodes = {\n\t\tetherpad_host: form.querySelector('[name=\"etherpad_host\"]'),\n\t\tetherpad_api_host: form.querySelector('[name=\"etherpad_api_host\"]'),\n\t\tetherpad_cookie_domain: form.querySelector('[name=\"etherpad_cookie_domain\"]'),\n\t\tetherpad_api_key: form.querySelector('[name=\"etherpad_api_key\"]'),\n\t\tsync_interval_seconds: form.querySelector('[name=\"sync_interval_seconds\"]'),\n\t\texternal_pad_allowlist: form.querySelector('[name=\"external_pad_allowlist\"]'),\n\t\ttrusted_embed_origins: form.querySelector('[name=\"trusted_embed_origins\"]'),\n\t}\n\n\tif (!root || !form || !statusNode || !healthButton) {\n\t\treturn\n\t}\n\n\tconst saveUrl = root.getAttribute('data-save-url') || ''\n\tconst healthUrl = root.getAttribute('data-health-url') || ''\n\tconst consistencyUrl = root.getAttribute('data-consistency-url') || ''\n\tconst settlePendingUrl = root.getAttribute('data-settle-pending-url') || ''\n\tconst l10n = {\n\t\tsaving: root.getAttribute('data-l10n-saving') || 'Saving settings...',\n\t\tsaved: root.getAttribute('data-l10n-saved') || 'Settings saved.',\n\t\tchecking: root.getAttribute('data-l10n-checking') || 'Testing Etherpad connection...',\n\t\tconsistencyRunning: root.getAttribute('data-l10n-consistency-running') || 'Running consistency check...',\n\t\tconsistencyOk: root.getAttribute('data-l10n-consistency-ok') || 'Consistency check successful.',\n\t\trequestFailed: root.getAttribute('data-l10n-request-failed') || 'Request failed.',\n\t\tsavingFailed: root.getAttribute('data-l10n-saving-failed') || 'Failed to save settings.',\n\t\thealthFailed: root.getAttribute('data-l10n-health-failed') || 'Etherpad connection test failed.',\n\t\tconsistencyFailed: root.getAttribute('data-l10n-consistency-failed') || 'Consistency check failed.',\n\t\tpendingDeleteLabel: root.getAttribute('data-l10n-pending-delete-label') || 'Pending Etherpad deletes',\n\t\tsettleFailed: root.getAttribute('data-l10n-settle-failed') || 'Pending pad check failed.',\n\t\ttemplateUploading: root.getAttribute('data-l10n-template-uploading') || 'Uploading template...',\n\t\ttemplateDelete: root.getAttribute('data-l10n-template-delete') || 'Delete',\n\t\ttemplateTooLarge: root.getAttribute('data-l10n-template-too-large') || 'Template file is too large.',\n\t\ttemplateDeleteLabel: root.getAttribute('data-l10n-template-delete-label') || 'Delete template {name}',\n\t\ttemplateConfirmDelete: root.getAttribute('data-l10n-template-confirm-delete') || 'Delete this template for everyone?',\n\t\ttemplateFailed: root.getAttribute('data-l10n-template-failed') || 'Template request failed.',\n\t\ttemplateConfirmReplace: root.getAttribute('data-l10n-template-confirm-replace') || 'Replace the existing template of that name?',\n\t}\n\tconst templatesUrl = root.getAttribute('data-templates-url') || ''\n\tconst templatesDeleteUrl = root.getAttribute('data-templates-delete-url') || ''\n\n\tif (saveUrl === '' || healthUrl === '' || consistencyUrl === '' || settlePendingUrl === '') {\n\t\treturn\n\t}\n\n\tfunction updateExternalSettingsVisibility() {\n\t\tconst enabled = !!(allowExternalCheckbox && allowExternalCheckbox.checked)\n\t\tif (allowlistRow) {\n\t\t\tallowlistRow.style.display = enabled ? '' : 'none'\n\t\t}\n\t\tif (allowlistHint) {\n\t\t\tallowlistHint.style.display = enabled ? '' : 'none'\n\t\t}\n\t\tif (allowlistTextarea instanceof HTMLTextAreaElement) {\n\t\t\tallowlistTextarea.disabled = !enabled\n\t\t\tif (!enabled) {\n\t\t\t\tallowlistTextarea.classList.remove('ep-input-error')\n\t\t\t\tconst errorNode = form.querySelector('[data-field-error=\"external_pad_allowlist\"]')\n\t\t\t\tif (errorNode instanceof HTMLElement) {\n\t\t\t\t\terrorNode.textContent = ''\n\t\t\t\t\terrorNode.classList.remove('is-visible')\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction updatePadTypesHint() {\n\t\tconst noneEnabled = !!(protectedPadsCheckbox && publicPadsCheckbox)\n\t\t\t&& !protectedPadsCheckbox.checked\n\t\t\t&& !publicPadsCheckbox.checked\n\t\tif (padTypesNoneHint instanceof HTMLElement) {\n\t\t\t// Write the text instead of toggling visibility: a live region only\n\t\t\t// announces content changes, and an element returning from\n\t\t\t// `display: none` reads as initial content. `.ep-field-hint:empty`\n\t\t\t// collapses the empty paragraph, so it looks the same.\n\t\t\tconst message = noneEnabled ? (padTypesNoneHint.dataset.message || '') : ''\n\t\t\t// Rewriting the same text would announce it again on load.\n\t\t\tif (padTypesNoneHint.textContent !== message) {\n\t\t\t\tpadTypesNoneHint.textContent = message\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction getPayload() {\n\t\tconst data = new FormData(form)\n\t\treturn {\n\t\t\tetherpad_host: String(data.get('etherpad_host') || '').trim(),\n\t\t\tetherpad_api_host: String(data.get('etherpad_api_host') || '').trim(),\n\t\t\tetherpad_cookie_domain: String(data.get('etherpad_cookie_domain') || '').trim(),\n\t\t\tetherpad_api_key: String(data.get('etherpad_api_key') || '').trim(),\n\t\t\tsync_interval_seconds: Number(data.get('sync_interval_seconds') || 120),\n\t\t\tdelete_pad_with_file: data.has('delete_pad_with_file'),\n\t\t\tenable_protected_pads: data.has('enable_protected_pads'),\n\t\t\tallow_legacy_protected_import: data.has('allow_legacy_protected_import'),\n\t\t\tenable_public_pads: data.has('enable_public_pads'),\n\t\t\tallow_external_pads: data.has('allow_external_pads'),\n\t\t\texternal_pad_allowlist: String(data.get('external_pad_allowlist') || ''),\n\t\t\ttrusted_embed_origins: String(data.get('trusted_embed_origins') || ''),\n\t\t}\n\t}\n\n\t// Writing a status touches only its own area, so a late response cannot\n\t// wipe out the other action's result.\n\tfunction setStatus(message, state, node = statusNode) {\n\t\tif (!(node instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tnode.textContent = message\n\t\tnode.classList.remove('ep-status-success', 'ep-status-warning', 'ep-status-error')\n\t\tif (state === 'success' || state === 'warning' || state === 'error') {\n\t\t\tnode.classList.add(`ep-status-${state}`)\n\t\t}\n\t}\n\n\t// Starting one does clear the other: its result predates this action and\n\t// would be read as belonging to it. The template status is its own group —\n\t// uploading a template makes neither a connection test nor a save result\n\t// stale, and vice versa.\n\tfunction beginStatus(message, node = statusNode) {\n\t\tconst group = node === templateStatusNode\n\t\t\t? [templateStatusNode]\n\t\t\t: [statusNode, diagnosticsTarget, connectionTarget]\n\t\tfor (const other of group) {\n\t\t\tif (other instanceof HTMLElement && other !== node) {\n\t\t\t\tother.textContent = ''\n\t\t\t\tother.classList.remove('ep-status-success', 'ep-status-warning', 'ep-status-error')\n\t\t\t}\n\t\t}\n\t\tsetStatus(message, null, node)\n\t}\n\n\t// Higher wins when two checks land on the same field, so a problem is\n\t// never hidden by a passing verdict that happened to come later.\n\tconst CHECK_SEVERITY = { skipped: 0, ok: 1, warning: 2 }\n\n\t// Each result is shown at the field it came from: a green tick where\n\t// things are fine, the message itself where they are not.\n\tfunction renderConnectionChecks(checks) {\n\t\tfor (const slot of document.querySelectorAll('[data-check-result]')) {\n\t\t\tslot.textContent = ''\n\t\t\tslot.className = 'ep-check-result'\n\t\t\tdelete slot.dataset.checkStatus\n\t\t}\n\t\tif (!Array.isArray(checks)) {\n\t\t\treturn\n\t\t}\n\t\tfor (const check of checks) {\n\t\t\tif (!check || typeof check.label !== 'string') {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst status = String(check.status || 'skipped')\n\t\t\tconst detail = typeof check.detail === 'string' ? check.detail : ''\n\t\t\tconst slot = check.field\n\t\t\t\t? document.querySelector(`[data-check-result=\"${CSS.escape(String(check.field))}\"]`)\n\t\t\t\t: null\n\t\t\tif (!(slot instanceof HTMLElement)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst shown = slot.dataset.checkStatus\n\t\t\tif (shown && (CHECK_SEVERITY[shown] ?? 0) > (CHECK_SEVERITY[status] ?? 0)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tslot.dataset.checkStatus = status\n\t\t\tslot.className = `ep-check-result ep-check-${status}`\n\t\t\t// A passing field needs no prose — the tick and the label say it.\n\t\t\t// A failing one needs the reason right there.\n\t\t\tslot.textContent = status === 'ok' ? check.label : (detail || check.label)\n\t\t}\n\t}\n\n\t// Shared templates: an admin uploads .pad files that everyone then sees as\n\t// tiles in Nextcloud's picker.\n\tfunction renderTemplates(templates) {\n\t\tif (!(templateListNode instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\ttemplateListNode.replaceChildren()\n\t\tconst list = Array.isArray(templates) ? templates : []\n\t\tshowTemplateEmptyState(list.length === 0)\n\t\tfor (const template of list) {\n\t\t\tif (!template || typeof template.name !== 'string') {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttemplateListNode.appendChild(buildTemplateRow(template.name))\n\t\t}\n\t}\n\n\tfunction buildTemplateRow(name) {\n\t\tconst row = document.createElement('li')\n\t\trow.className = 'ep-template-row'\n\n\t\tconst label = document.createElement('span')\n\t\tlabel.className = 'ep-template-name'\n\t\tlabel.textContent = name\n\t\trow.appendChild(label)\n\n\t\tconst remove = document.createElement('button')\n\t\tremove.type = 'button'\n\t\tremove.textContent = l10n.templateDelete\n\t\t// The visible label repeats on every row, so the accessible name has to\n\t\t// carry the name of the template this one removes.\n\t\tremove.setAttribute('aria-label', l10n.templateDeleteLabel.replace('{name}', name))\n\t\tremove.addEventListener('click', () => {\n\t\t\tif (!window.confirm(l10n.templateConfirmDelete)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvoid deleteTemplate(name)\n\t\t})\n\t\trow.appendChild(remove)\n\t\treturn row\n\t}\n\n\tfunction showTemplateEmptyState(visible) {\n\t\tif (templateEmptyNode instanceof HTMLElement) {\n\t\t\ttemplateEmptyNode.style.display = visible ? '' : 'none'\n\t\t}\n\t}\n\n\t// Every upload and delete starts another listing while the first may still\n\t// be in flight. Without this the slower answer wins whenever it happens to\n\t// arrive last, putting a deleted template back on the page or replacing a\n\t// fresh result with an old error.\n\tlet templateListGeneration = 0\n\n\tasync function loadTemplates() {\n\t\tif (templatesUrl === '' || !(templateListNode instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tconst generation = ++templateListGeneration\n\t\tconst isCurrent = () => generation === templateListGeneration\n\n\t\t// \"No shared templates yet\" is an answer, and we do not have one until\n\t\t// the request comes back — showing it next to an error would claim the\n\t\t// list is empty when we simply could not read it.\n\t\tshowTemplateEmptyState(false)\n\t\ttry {\n\t\t\tconst response = await fetch(templatesUrl, {\n\t\t\t\tcredentials: 'same-origin',\n\t\t\t\theaders: { requesttoken: String(OC.requestToken || '') },\n\t\t\t})\n\t\t\tconst data = await readJsonResponse(response)\n\t\t\tif (!isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trenderTemplates(data.templates)\n\t\t} catch (error) {\n\t\t\tif (!isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshowTemplateEmptyState(false)\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.templateFailed, 'error', templateStatusNode)\n\t\t}\n\t}\n\n\t// The same limit the server enforces. Without it a mis-picked large file is\n\t// read into memory and posted, only to hit post_max_size or the memory\n\t// limit — a failure that says nothing, instead of the sentence below.\n\tconst MAX_TEMPLATE_BYTES = 2 * 1024 * 1024\n\n\tasync function uploadTemplate(file, replace = false) {\n\t\tif (typeof file.size === 'number' && file.size > MAX_TEMPLATE_BYTES) {\n\t\t\tsetStatus(l10n.templateTooLarge, 'error', templateStatusNode)\n\t\t\treturn\n\t\t}\n\t\tbeginStatus(l10n.templateUploading, templateStatusNode)\n\t\ttry {\n\t\t\tconst content = await file.text()\n\t\t\tconst data = await postJsonBody(templatesUrl, { name: file.name, content, replace })\n\t\t\tsetStatus(String(data.message || ''), 'success', templateStatusNode)\n\t\t\tawait loadTemplates()\n\t\t} catch (error) {\n\t\t\t// The server refuses to overwrite unless asked, so a name that is\n\t\t\t// already taken comes back as a question rather than a failure.\n\t\t\tif (!replace && error && error.field === 'template_exists') {\n\t\t\t\tif (window.confirm(l10n.templateConfirmReplace)) {\n\t\t\t\t\tawait uploadTemplate(file, true)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsetStatus('', null, templateStatusNode)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.templateFailed, 'error', templateStatusNode)\n\t\t}\n\t}\n\n\tasync function deleteTemplate(name) {\n\t\ttry {\n\t\t\tconst data = await postJson(templatesDeleteUrl, { name })\n\t\t\tsetStatus(String(data.message || ''), 'success', templateStatusNode)\n\t\t\tawait loadTemplates()\n\t\t} catch (error) {\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.templateFailed, 'error', templateStatusNode)\n\t\t}\n\t}\n\n\tfunction clearFieldErrors() {\n\t\tObject.keys(fieldNodes).forEach((field) => {\n\t\t\tconst input = fieldNodes[field]\n\t\t\tif (input instanceof HTMLElement) {\n\t\t\t\tinput.classList.remove('ep-input-error')\n\t\t\t}\n\t\t\tconst errorNode = form.querySelector(`[data-field-error=\"${field}\"]`)\n\t\t\tif (errorNode instanceof HTMLElement) {\n\t\t\t\terrorNode.textContent = ''\n\t\t\t\terrorNode.classList.remove('is-visible')\n\t\t\t}\n\t\t})\n\t}\n\n\tfunction showFieldError(field, message) {\n\t\tif (!field || !message) {\n\t\t\treturn\n\t\t}\n\t\tconst input = fieldNodes[field]\n\t\tif (input instanceof HTMLElement) {\n\t\t\tinput.classList.add('ep-input-error')\n\t\t}\n\t\tconst errorNode = form.querySelector(`[data-field-error=\"${field}\"]`)\n\t\tif (errorNode instanceof HTMLElement) {\n\t\t\terrorNode.textContent = message\n\t\t\terrorNode.classList.add('is-visible')\n\t\t}\n\t\tif (input instanceof HTMLElement && typeof input.focus === 'function') {\n\t\t\tinput.focus()\n\t\t}\n\t}\n\n\tconst bindingCounts = { pendingDeletes: 0 }\n\n\t// Only the counts a response carries; one that carries none leaves the\n\t// panel as it was rather than repainting it from what this page assumed.\n\t// The health check and the pending pad check name them the same.\n\tfunction updateBindingCounts(data) {\n\t\tconst counts = {}\n\t\tif (typeof data.pending_delete_count !== 'undefined') {\n\t\t\tcounts.pendingDeletes = data.pending_delete_count\n\t\t}\n\t\tif (Object.keys(counts).length === 0) {\n\t\t\treturn\n\t\t}\n\t\tfor (const [key, value] of Object.entries(counts)) {\n\t\t\tbindingCounts[key] = Number.isFinite(Number(value)) ? Number(value) : 0\n\t\t}\n\t\tif (pendingActions instanceof HTMLElement) {\n\t\t\tpendingActions.style.display = bindingCounts.pendingDeletes > 0 ? '' : 'none'\n\t\t}\n\t\tif (pendingCountNode instanceof HTMLElement) {\n\t\t\tpendingCountNode.textContent = `${l10n.pendingDeleteLabel}: ${String(bindingCounts.pendingDeletes)}`\n\t\t}\n\t\t// The check deletes a pad only once its file is gone for good, and\n\t\t// nothing here is more than a nudge to the job that does the same.\n\t\tif (settlePendingButton instanceof HTMLButtonElement) {\n\t\t\tsettlePendingButton.disabled = bindingCounts.pendingDeletes <= 0\n\t\t}\n\t}\n\n\t// One place decides what a response means, so a caller cannot forget to\n\t// look at the status or at `ok` in the body.\n\tasync function readJsonResponse(response) {\n\t\tlet data = null\n\t\tconst responseText = await response.text()\n\t\ttry {\n\t\t\tdata = responseText !== '' ? JSON.parse(responseText) : null\n\t\t} catch (error) {\n\t\t\tdata = null\n\t\t}\n\n\t\tif (!response.ok || !data || data.ok !== true) {\n\t\t\t// Only our own JSON is quoted: another body came from something\n\t\t\t// between the browser and the app, and showing its markup reads\n\t\t\t// as an app failure. The status says more than the markup does.\n\t\t\tconst message = (data && data.message)\n\t\t\t\t? String(data.message)\n\t\t\t\t: `${l10n.requestFailed} (HTTP ${response.status})`\n\t\t\tconst err = new Error(message)\n\t\t\terr.field = (data && typeof data.field === 'string') ? data.field : ''\n\t\t\tthrow err\n\t\t}\n\n\t\treturn data\n\t}\n\n\t/**\n\t * POST a JSON body. Used for the template upload, where URL-encoding a\n\t * whole file would inflate it several times over.\n\t */\n\tasync function postJsonBody(url, payload) {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\tcredentials: 'same-origin',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\trequesttoken: String(OC.requestToken || ''),\n\t\t\t},\n\t\t\tbody: JSON.stringify(payload),\n\t\t})\n\t\treturn readJsonResponse(response)\n\t}\n\n\tasync function postJson(url, payload) {\n\t\tconst body = new URLSearchParams()\n\t\tObject.keys(payload).forEach((key) => {\n\t\t\tbody.set(key, String(payload[key]))\n\t\t})\n\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\tcredentials: 'same-origin',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t\t\trequesttoken: String(OC.requestToken || ''),\n\t\t\t},\n\t\t\tbody: body.toString(),\n\t\t})\n\n\t\treturn readJsonResponse(response)\n\t}\n\n\tform.addEventListener('submit', async (event) => {\n\t\tevent.preventDefault()\n\t\tclearFieldErrors()\n\t\t// Verdicts describe the values of the previous run: keeping them up\n\t\t// while this one is in flight puts a green tick next to a field that\n\t\t// is being changed, and a failed save would leave them there.\n\t\trenderConnectionChecks([])\n\t\tbeginStatus(l10n.saving)\n\t\ttry {\n\t\t\tconst data = await postJson(saveUrl, getPayload())\n\t\t\t// Saving answers with the cookie verdict alone; rendering it clears\n\t\t\t// the other fields' results, which the save just invalidated.\n\t\t\trenderConnectionChecks(data.checks)\n\t\t\tconst versionSuffix = data && data.api_version ? ` api=${String(data.api_version)}` : ''\n\t\t\tsetStatus(`${String(data.message || l10n.saved)}${versionSuffix}`, 'success')\n\t\t} catch (error) {\n\t\t\tif (error && typeof error.field === 'string' && error.field !== '') {\n\t\t\t\tshowFieldError(error.field, error.message || l10n.savingFailed)\n\t\t\t}\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.savingFailed, 'error')\n\t\t}\n\t})\n\n\thealthButton.addEventListener('click', async () => {\n\t\tclearFieldErrors()\n\t\trenderConnectionChecks([])\n\t\tbeginStatus(l10n.checking, connectionTarget)\n\t\ttry {\n\t\t\tconst data = await postJson(healthUrl, getPayload())\n\t\t\tupdateBindingCounts(data)\n\t\t\t// The per-field results carry the target and latency and the\n\t\t\t// protected-pads verdict, so the summary stays a summary.\n\t\t\trenderConnectionChecks(data.checks)\n\t\t\tconst needsAttention = Array.isArray(data.checks)\n\t\t\t\t&& data.checks.some((check) => check && check.status === 'warning')\n\t\t\tsetStatus(String(data.message), needsAttention ? 'warning' : 'success', connectionTarget)\n\t\t} catch (error) {\n\t\t\tif (error && typeof error.field === 'string' && error.field !== '') {\n\t\t\t\tshowFieldError(error.field, error.message || l10n.healthFailed)\n\t\t\t}\n\t\t\tsetStatus(error instanceof Error ? error.message : l10n.healthFailed, 'error', connectionTarget)\n\t\t}\n\t})\n\n\tif (consistencyButton instanceof HTMLElement) {\n\t\tconsistencyButton.addEventListener('click', async () => {\n\t\t\tclearFieldErrors()\n\t\t\tbeginStatus(l10n.consistencyRunning, diagnosticsTarget)\n\t\t\ttry {\n\t\t\t\tconst data = await postJson(consistencyUrl, {})\n\t\t\t\tconst vanishedFile = Number(data.vanished_file_count || 0)\n\t\t\t\tconst message = `${String(data.message || l10n.consistencyOk)} vanished_file=${String(vanishedFile)}`\n\t\t\t\tsetStatus(message, vanishedFile > 0 ? 'error' : 'success', diagnosticsTarget)\n\t\t\t\tshowVanished(data.samples && data.samples.vanished_files)\n\t\t\t} catch (error) {\n\t\t\t\tsetStatus(error instanceof Error ? error.message : l10n.consistencyFailed, 'error', diagnosticsTarget)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * The pads of files gone without passing a trash, which the app leaves\n\t * in place: listed, so an admin can delete them in Etherpad.\n\t */\n\tfunction showVanished(rows) {\n\t\tif (!(vanishedNode instanceof HTMLElement) || !(vanishedList instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tconst items = (Array.isArray(rows) ? rows : [])\n\t\t\t.filter((row) => row && typeof row.pad_id === 'string')\n\t\t\t.map((row) => {\n\t\t\t\tconst item = document.createElement('li')\n\t\t\t\titem.textContent = `${row.pad_id} (fileid ${String(row.file_id)})`\n\t\t\t\treturn item\n\t\t\t})\n\t\tvanishedList.replaceChildren(...items)\n\t\tvanishedNode.style.display = items.length > 0 ? '' : 'none'\n\t}\n\n\tif (settlePendingButton instanceof HTMLElement) {\n\t\tsettlePendingButton.addEventListener('click', async () => {\n\t\t\tclearFieldErrors()\n\t\t\tbeginStatus(l10n.checking, diagnosticsTarget)\n\t\t\ttry {\n\t\t\t\tconst data = await postJson(settlePendingUrl, {})\n\t\t\t\tconst details = []\n\t\t\t\tfor (const key of ['checked', 'settled', 'pending_delete_count']) {\n\t\t\t\t\tif (typeof data[key] !== 'undefined') {\n\t\t\t\t\t\tdetails.push(`${key}=${String(data[key])}`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tupdateBindingCounts(data)\n\t\t\t\tconst suffix = details.length > 0 ? ` ${details.join(' | ')}` : ''\n\t\t\t\tsetStatus(`${String(data.message || 'OK')}${suffix}`, 'success', diagnosticsTarget)\n\t\t\t} catch (error) {\n\t\t\t\tsetStatus(error instanceof Error ? error.message : l10n.settleFailed, 'error', diagnosticsTarget)\n\t\t\t}\n\t\t})\n\t}\n\n\tif (templateUploadButton instanceof HTMLElement && templateFileInput instanceof HTMLInputElement) {\n\t\ttemplateUploadButton.addEventListener('click', () => {\n\t\t\ttemplateFileInput.click()\n\t\t})\n\t\ttemplateFileInput.addEventListener('change', () => {\n\t\t\tconst file = templateFileInput.files && templateFileInput.files[0]\n\t\t\tif (file) {\n\t\t\t\tvoid uploadTemplate(file)\n\t\t\t}\n\t\t\t// Reset so picking the same file twice fires again.\n\t\t\ttemplateFileInput.value = ''\n\t\t})\n\t\tvoid loadTemplates()\n\t}\n\n\tif (allowExternalCheckbox) {\n\t\tallowExternalCheckbox.addEventListener('change', updateExternalSettingsVisibility)\n\t}\n\tupdateExternalSettingsVisibility()\n\n\tfor (const checkbox of [protectedPadsCheckbox, publicPadsCheckbox]) {\n\t\tif (checkbox) {\n\t\t\tcheckbox.addEventListener('change', updatePadTypesHint)\n\t\t}\n\t}\n\tupdatePadTypesHint()\n})()\n"],"names":["root","form","statusNode","diagnosticsTarget","connectionTarget","healthButton","consistencyButton","settlePendingButton","pendingActions","pendingCountNode","vanishedNode","vanishedList","allowExternalCheckbox","protectedPadsCheckbox","publicPadsCheckbox","padTypesNoneHint","allowlistRow","allowlistHint","allowlistTextarea","templateListNode","templateEmptyNode","templateFileInput","templateUploadButton","templateStatusNode","fieldNodes","saveUrl","healthUrl","consistencyUrl","settlePendingUrl","l10n","templatesUrl","templatesDeleteUrl","updateExternalSettingsVisibility","enabled","errorNode","updatePadTypesHint","noneEnabled","message","getPayload","data","setStatus","state","node","beginStatus","group","other","CHECK_SEVERITY","renderConnectionChecks","checks","slot","check","status","detail","shown","renderTemplates","templates","list","showTemplateEmptyState","template","buildTemplateRow","name","row","label","remove","deleteTemplate","visible","templateListGeneration","loadTemplates","generation","isCurrent","response","readJsonResponse","error","MAX_TEMPLATE_BYTES","uploadTemplate","file","replace","content","postJsonBody","postJson","clearFieldErrors","field","input","showFieldError","bindingCounts","updateBindingCounts","counts","key","value","responseText","err","url","payload","body","event","versionSuffix","needsAttention","vanishedFile","showVanished","rows","items","item","details","suffix","checkbox"],"mappings":"CAAC,UAAY,CAGZ,MAAMA,EAAO,SAAS,eAAe,mCAAmC,EAClEC,EAAO,SAAS,eAAe,+BAA+B,EAC9DC,EAAa,SAAS,eAAe,iCAAiC,EACtEC,EAAoB,SAAS,eAAe,uCAAuC,EACnFC,EAAmB,SAAS,eAAe,sCAAsC,EACjFC,EAAe,SAAS,eAAe,iCAAiC,EACxEC,EAAoB,SAAS,eAAe,sCAAsC,EAClFC,EAAsB,SAAS,eAAe,mCAAmC,EACjFC,EAAiB,SAAS,eAAe,oCAAoC,EAC7EC,EAAmB,SAAS,eAAe,kCAAkC,EAC7EC,EAAe,SAAS,eAAe,6BAA6B,EACpEC,EAAe,SAAS,eAAe,kCAAkC,EACzEC,EAAwBX,EAAOA,EAAK,cAAc,mCAAmC,EAAI,KACzFY,EAAwBZ,EAAOA,EAAK,cAAc,qCAAqC,EAAI,KAC3Fa,EAAqBb,EAAOA,EAAK,cAAc,kCAAkC,EAAI,KACrFc,EAAmB,SAAS,eAAe,qBAAqB,EAChEC,EAAe,SAAS,eAAe,4BAA4B,EACnEC,EAAgB,SAAS,eAAe,6BAA6B,EACrEC,EAAoB,SAAS,eAAe,wBAAwB,EACpEC,EAAmB,SAAS,eAAe,oBAAoB,EAC/DC,EAAoB,SAAS,eAAe,qBAAqB,EACjEC,EAAoB,SAAS,eAAe,oBAAoB,EAChEC,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..0ba0b8b9 100644 --- a/js/etherpad_nextcloud-embed-main.mjs +++ b/js/etherpad_nextcloud-embed-main.mjs @@ -1,2 +1,2 @@ -import{o as Ee,f as x,r as Le,a as _e}from"./fetch-helpers-BUxbvlK6.chunk.mjs";import{o as Ce,s as Se,c as Te,a as Me,p as xe,i as ve,b as He,d as we,e as Ae,l as Ne,h as qe}from"./pad-open-flow-By_FzSKk.chunk.mjs";(function(){const F="epnc-embed__recovery-button",v=F+" epnc-embed__recovery-button--primary",a=document.getElementById("etherpad-nextcloud-embed");if(!(a instanceof HTMLElement))return;const g=Number(a.getAttribute("data-file-id")||""),U=String(a.getAttribute("data-open-by-id-url")||"").trim(),O=String(a.getAttribute("data-initialize-by-id-url-template")||"").trim(),P=String(a.getAttribute("data-recover-url-template")||"").trim(),B=String(a.getAttribute("data-find-original-url-template")||"").trim(),K=String(a.getAttribute("data-request-token")||"").trim(),Q=String(a.getAttribute("data-trusted-origins")||"").split(/\s+/).map(e=>e.trim()).filter(Boolean),s=a.querySelector("[data-epnc-embed-loading]"),L=a.querySelector("[data-epnc-embed-error]"),H=a.querySelector("[data-epnc-embed-error-message]"),_=a.querySelector("[data-epnc-embed-error-actions]"),p=a.querySelector("[data-epnc-embed-recovery]"),l=a.querySelector("[data-epnc-embed-recovery-message]"),b=a.querySelector("[data-epnc-embed-recovery-body]"),m=a.querySelector("[data-epnc-embed-recovery-actions]"),u=a.querySelector("[data-epnc-embed-iframe]"),X=String(a.getAttribute("data-l10n-content-empty")||"This pad is still empty.").trim(),j=String(a.getAttribute("data-l10n-content-loading")||"Loading pad content...").trim(),w=String(a.getAttribute("data-l10n-content-error")||"Could not load the pad content.").trim(),Y=String(a.getAttribute("data-l10n-content-no-url")||"The server did not say where to load this pad from.").trim(),D=String(a.getAttribute("data-l10n-content-retry")||"Try again").trim(),z=String(a.getAttribute("data-l10n-content-refresh")||"Refresh").trim(),Z=String(a.getAttribute("data-l10n-content-refreshing")||"Refreshing...").trim(),$=String(a.getAttribute("data-l10n-external-link")||"Open original pad").trim(),ee=String(a.getAttribute("data-l10n-recovery-checking")||"Checking for the original pad...").trim(),te=String(a.getAttribute("data-l10n-recovery-copy-body")||"").trim(),ne=String(a.getAttribute("data-l10n-recovery-orphan-body")||"").trim(),re=String(a.getAttribute("data-l10n-recovery-open-original")||"Open the original .pad file").trim(),G=String(a.getAttribute("data-l10n-recovery-create-new")||"Create new pad from this file").trim(),ae=String(a.getAttribute("data-l10n-recovery-creating")||"Creating new pad...").trim(),oe=String(a.getAttribute("data-l10n-unanswered")||"Nextcloud did not answer. Check your connection and try again.").trim();let A=null;const h=()=>Ee(K),f=Ae({requestToken:h}),C=(e,t)=>Le(e,oe,t),N=(e,t)=>qe(e,t,{preventScroll:!0}),S=(e,t,r=F)=>{const n=document.createElement("button");return n.type="button",n.className=r,n.textContent=e,n.addEventListener("click",t),n},y=(e,t=!1,r=!1)=>{E(),H instanceof HTMLElement&&(H.textContent=String(e||"Unknown error.")),_ instanceof HTMLElement&&(_.replaceChildren(),t&&_.appendChild(S(D,()=>{T(!0)},v))),L instanceof HTMLElement&&(L.hidden=!1),r&&N(_,H)},ie=()=>{E(),s instanceof HTMLElement&&(s.classList.remove("epnc-embed__loading--pad-doc"),s.hidden=!1)},ce=e=>{if(!(s instanceof HTMLElement))return null;s.classList.add("epnc-embed__loading--pad-doc"),s.textContent="";const t=document.createElement("div");t.className="epnc-pad-doc";const r=document.createElement("div");r.className="epnc-pad-doc__inner";const n=document.createElement("div");n.className="epnc-pad-doc__toolbar";const o=document.createElement("span");o.className="epnc-pad-doc__toolbar-error",o.hidden=!0,n.appendChild(o);const c=document.createElement("button");if(c.type="button",c.className="button epnc-pad-doc__refresh",c.textContent=z,n.appendChild(c),String(e||"").trim()!==""){const d=document.createElement("a");d.className="button epnc-pad-doc__link",d.href=e,d.target="_blank",d.rel="noopener noreferrer",d.textContent=$,n.appendChild(d)}const i=document.createElement("div");return i.className="epnc-pad-doc__text",i.textContent=j,r.appendChild(n),r.appendChild(i),t.appendChild(r),s.appendChild(t),{body:i,refresh:c,toolbarError:o,loaded:!1}};let q=0;const k=async(e,t)=>{if(!e||!(e.body instanceof HTMLElement))return;const{body:r,refresh:n,toolbarError:o}=e;q+=1;const c=q,i=()=>c===q;e.loaded||(r.className="epnc-pad-doc__text",r.textContent=j),o instanceof HTMLElement&&(o.hidden=!0),n instanceof HTMLButtonElement&&(n.disabled=!0,n.textContent=Z);try{if(t===""){V(e,t,Y,!1);return}const d=await Ne(t);if(!i())return;if(e.loaded=!0,d.isEmpty){r.className="epnc-pad-doc__text",r.textContent=X;return}r.className="epnc-pad-doc__text epnc-pad-doc__text--html",r.innerHTML=d.html}catch(d){if(!i())return;V(e,t,C(d,w))}finally{i()&&n instanceof HTMLButtonElement&&(n.disabled=!1,n.textContent=z)}},V=(e,t,r,n=!0)=>{const{body:o,toolbarError:c}=e;if(e.loaded&&c instanceof HTMLElement){c.textContent=r||w,c.hidden=!1;return}o.className="epnc-pad-doc__text",o.textContent="";const i=document.createElement("p");i.textContent=r||w,o.appendChild(i),n&&o.appendChild(S(D,()=>{k(e,t)},"button primary"))},de=e=>{if(!(u instanceof HTMLIFrameElement)){y("Embed iframe is not available.");return}const t=()=>{u.removeEventListener("load",t),window.setTimeout(()=>{s instanceof HTMLElement&&(s.hidden=!0),u.hidden=!1},100)};u.addEventListener("load",t,{once:!0}),u.src=e},I=(e,t,r,n={})=>{!e||typeof e.postMessage!="function"||e.postMessage(Object.assign({type:r,fileId:g},n),t)},se=e=>!e||e==="null"?!1:e===window.location.origin?!0:Q.includes(e),le=()=>{A||(A=e=>{const t=String(e.origin||"");if(!se(t))return;const r=e.data,n=typeof r=="string"?r:r&&typeof r=="object"&&typeof r.type=="string"?r.type:"";if(n){if(n==="epnc:host-visible"){f.start();return}if(n==="epnc:host-hidden"){f.fireAndForget(!0,!0),f.stop();return}if(n==="epnc:host-before-close"||n==="epnc:host-sync-now"){const o=n!=="epnc:host-sync-now",c=n==="epnc:host-before-close"?"before-close":"sync-now";I(e.source,t,"epnc:sync-flush-started",{reason:c}),f.sync(!0,o).then(i=>{I(e.source,t,"epnc:sync-flush-finished",{reason:c,result:i&&typeof i=="object"?i:{}})}).catch(i=>{I(e.source,t,"epnc:sync-flush-failed",{reason:c,message:i instanceof Error?i.message:"Sync failed."})}),o&&f.stop()}}},window.addEventListener("message",A))},me=async()=>{const e=new URLSearchParams;e.set("fileId",String(g));const t=await x(U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",requesttoken:h()},body:e.toString()});return we(t)},pe=async()=>{const e=O.replace("__FILE_ID__",encodeURIComponent(String(g))),t=await x(e,{method:"POST",headers:{requesttoken:h()}},{timeoutMs:null});t&&t.status==="migrated_from_legacy"&&console.info("Legacy Ownpad .pad migrated to managed format on first open.")},E=()=>{s instanceof HTMLElement&&(s.hidden=!0),L instanceof HTMLElement&&(L.hidden=!0),p instanceof HTMLElement&&(p.hidden=!0),u instanceof HTMLIFrameElement&&(u.hidden=!0,u.removeAttribute("src"))},ue=()=>{p instanceof HTMLElement&&(E(),p.hidden=!1,l instanceof HTMLElement&&(l.textContent=ee),b instanceof HTMLElement&&(b.textContent=""),m instanceof HTMLElement&&m.replaceChildren())},fe=(e,t)=>{if(p instanceof HTMLElement&&(E(),p.hidden=!1,l instanceof HTMLElement&&(l.textContent=t),b instanceof HTMLElement&&(b.textContent=te),m instanceof HTMLElement)){const r=document.createElement("a");r.className=v,r.href=e,r.textContent=re,m.replaceChildren(r,S(G,()=>{J()}))}},ge=e=>{p instanceof HTMLElement&&(E(),p.hidden=!1,l instanceof HTMLElement&&(l.textContent=e),b instanceof HTMLElement&&(b.textContent=ne),m instanceof HTMLElement&&m.replaceChildren(S(G,()=>{J()},v)))},W=e=>{m instanceof HTMLElement&&m.querySelectorAll("button").forEach(t=>{t.disabled=e,e?(t.dataset.originalLabel=t.dataset.originalLabel||t.textContent||"",t.textContent=ae):t.dataset.originalLabel&&(t.textContent=t.dataset.originalLabel,delete t.dataset.originalLabel)})},J=async()=>{if(P===""){y("Recovery is not available in this embed.");return}W(!0);const e=P.replace("__FILE_ID__",encodeURIComponent(String(g)));try{await x(e,{method:"POST",headers:{requesttoken:h()}},{timeoutMs:null}),T(!0)}catch(t){if(_e(t)){T(!0);return}W(!1),l instanceof HTMLElement&&(l.textContent=C(t,"Recovery failed.")),N(m,l)}},be=async()=>{if(B==="")return"";const e=B.replace("__FILE_ID__",encodeURIComponent(String(g)));try{const t=await x(e,{method:"GET"});if(t&&t.found===!0&&typeof t.embed_url=="string")return t.embed_url}catch{}return""},he=async(e,t,r)=>{const n=C(e,"Pad open failed.");ue();const o=await be();r()&&(o!==""?fe(o,n):ge(n),t&&N(m,l))};let R=0;const T=async(e=!1)=>{R+=1;const t=R,r=()=>t===R;if(ie(),!Number.isFinite(g)||g<=0||U===""||O===""){y("Embed configuration is incomplete.");return}if(h()===""){y("CSRF request token is missing.");return}try{const n=await Ce({open:me,initialize:pe,stillWanted:r});if(n===null||!r())return;const{syncUrl:o,intervalMs:c}=Se(n);f.configure({syncUrl:o,intervalMs:c}),f.installLifecycleHandlers(),le(),o!==""&&f.start();const i=Te(n),{isContentView:d,externalUrl:ye}=Me(n);if(d){const M=ce(ye);M!==null&&M.refresh.addEventListener("click",()=>{k(M,i)}),k(M,i);return}de(xe(n))}catch(n){if(!r())return;if(ve(n)){he(n,e,r);return}y(C(n,"Pad open failed."),He(n),e)}};T()})(); +import{o as Ee,f as v,r as Le,a as _e}from"./fetch-helpers-BUxbvlK6.chunk.mjs";import{o as Ce,s as Se,c as Te,a as Me,p as xe,i as ve,b as He,d as we,e as Ae,f as qe,l as Ne,h as ke}from"./pad-open-flow-_qELVjOV.chunk.mjs";(function(){const F="epnc-embed__recovery-button",H=F+" epnc-embed__recovery-button--primary",a=document.getElementById("etherpad-nextcloud-embed");if(!(a instanceof HTMLElement))return;const g=Number(a.getAttribute("data-file-id")||""),U=String(a.getAttribute("data-open-by-id-url")||"").trim(),O=String(a.getAttribute("data-initialize-by-id-url-template")||"").trim(),P=String(a.getAttribute("data-recover-url-template")||"").trim(),B=String(a.getAttribute("data-find-original-url-template")||"").trim(),Q=String(a.getAttribute("data-request-token")||"").trim(),X=String(a.getAttribute("data-trusted-origins")||"").split(/\s+/).map(e=>e.trim()).filter(Boolean),s=a.querySelector("[data-epnc-embed-loading]"),_=a.querySelector("[data-epnc-embed-error]"),w=a.querySelector("[data-epnc-embed-error-message]"),C=a.querySelector("[data-epnc-embed-error-actions]"),p=a.querySelector("[data-epnc-embed-recovery]"),l=a.querySelector("[data-epnc-embed-recovery-message]"),b=a.querySelector("[data-epnc-embed-recovery-body]"),m=a.querySelector("[data-epnc-embed-recovery-actions]"),u=a.querySelector("[data-epnc-embed-iframe]"),Y=String(a.getAttribute("data-l10n-content-empty")||"This pad is still empty.").trim(),j=String(a.getAttribute("data-l10n-content-loading")||"Loading pad content...").trim(),A=String(a.getAttribute("data-l10n-content-error")||"Could not load the pad content.").trim(),Z=String(a.getAttribute("data-l10n-content-no-url")||"The server did not say where to load this pad from.").trim(),D=String(a.getAttribute("data-l10n-content-retry")||"Try again").trim(),z=String(a.getAttribute("data-l10n-content-refresh")||"Refresh").trim(),$=String(a.getAttribute("data-l10n-content-refreshing")||"Refreshing...").trim(),ee=String(a.getAttribute("data-l10n-external-link")||"Open original pad").trim(),te=String(a.getAttribute("data-l10n-recovery-checking")||"Checking for the original pad...").trim(),ne=String(a.getAttribute("data-l10n-recovery-copy-body")||"").trim(),re=String(a.getAttribute("data-l10n-recovery-orphan-body")||"").trim(),ae=String(a.getAttribute("data-l10n-recovery-open-original")||"Open the original .pad file").trim(),G=String(a.getAttribute("data-l10n-recovery-create-new")||"Create new pad from this file").trim(),oe=String(a.getAttribute("data-l10n-recovery-creating")||"Creating new pad...").trim(),ie=String(a.getAttribute("data-l10n-unanswered")||"Nextcloud did not answer. Check your connection and try again.").trim();let q=null;const h=()=>Ee(Q),f=qe({requestToken:h}),y=(e,t)=>Le(e,ie,t),S=(e,t)=>ke(e,t,{preventScroll:!0}),T=(e,t,r=F)=>{const n=document.createElement("button");return n.type="button",n.className=r,n.textContent=e,n.addEventListener("click",t),n},E=(e,t=!1,r=!1)=>{L(),w instanceof HTMLElement&&(w.textContent=String(e||"Unknown error.")),C instanceof HTMLElement&&(C.replaceChildren(),t&&C.appendChild(T(D,()=>{M(!0)},H))),_ instanceof HTMLElement&&(_.hidden=!1),r&&S(C,w)},ce=()=>{L(),s instanceof HTMLElement&&(s.classList.remove("epnc-embed__loading--pad-doc"),s.hidden=!1)},de=e=>{if(!(s instanceof HTMLElement))return null;s.classList.add("epnc-embed__loading--pad-doc"),s.textContent="";const t=document.createElement("div");t.className="epnc-pad-doc";const r=document.createElement("div");r.className="epnc-pad-doc__inner";const n=document.createElement("div");n.className="epnc-pad-doc__toolbar";const o=document.createElement("span");o.className="epnc-pad-doc__toolbar-error",o.hidden=!0,n.appendChild(o);const c=document.createElement("button");if(c.type="button",c.className="button epnc-pad-doc__refresh",c.textContent=z,n.appendChild(c),String(e||"").trim()!==""){const d=document.createElement("a");d.className="button epnc-pad-doc__link",d.href=e,d.target="_blank",d.rel="noopener noreferrer",d.textContent=ee,n.appendChild(d)}const i=document.createElement("div");return i.className="epnc-pad-doc__text",i.textContent=j,r.appendChild(n),r.appendChild(i),t.appendChild(r),s.appendChild(t),{body:i,refresh:c,toolbarError:o,loaded:!1}};let N=0;const k=async(e,t)=>{if(!e||!(e.body instanceof HTMLElement))return;const{body:r,refresh:n,toolbarError:o}=e;N+=1;const c=N,i=()=>c===N;e.loaded||(r.className="epnc-pad-doc__text",r.textContent=j),o instanceof HTMLElement&&(o.hidden=!0),n instanceof HTMLButtonElement&&(n.disabled=!0,n.textContent=$);try{if(t===""){V(e,t,Z,!1);return}const d=await Ne(t);if(!i())return;if(e.loaded=!0,d.isEmpty){r.className="epnc-pad-doc__text",r.textContent=Y;return}r.className="epnc-pad-doc__text epnc-pad-doc__text--html",r.innerHTML=d.html}catch(d){if(!i())return;V(e,t,y(d,A))}finally{i()&&n instanceof HTMLButtonElement&&(n.disabled=!1,n.textContent=z)}},V=(e,t,r,n=!0)=>{const{body:o,toolbarError:c}=e;if(e.loaded&&c instanceof HTMLElement){c.textContent=r||A,c.hidden=!1;return}o.className="epnc-pad-doc__text",o.textContent="";const i=document.createElement("p");i.textContent=r||A,o.appendChild(i),n&&o.appendChild(T(D,()=>{k(e,t)},"button primary"))},se=e=>{if(!(u instanceof HTMLIFrameElement)){E("Embed iframe is not available.");return}const t=()=>{u.removeEventListener("load",t),window.setTimeout(()=>{s instanceof HTMLElement&&(s.hidden=!0),u.hidden=!1},100)};u.addEventListener("load",t,{once:!0}),u.src=e},I=(e,t,r,n={})=>{!e||typeof e.postMessage!="function"||e.postMessage(Object.assign({type:r,fileId:g},n),t)},le=e=>!e||e==="null"?!1:e===window.location.origin?!0:X.includes(e),me=()=>{q||(q=e=>{const t=String(e.origin||"");if(!le(t))return;const r=e.data,n=typeof r=="string"?r:r&&typeof r=="object"&&typeof r.type=="string"?r.type:"";if(n){if(n==="epnc:host-visible"){f.start();return}if(n==="epnc:host-hidden"){f.fireAndForget(!0,!0),f.stop();return}if(n==="epnc:host-before-close"||n==="epnc:host-sync-now"){const o=n!=="epnc:host-sync-now",c=n==="epnc:host-before-close"?"before-close":"sync-now";I(e.source,t,"epnc:sync-flush-started",{reason:c}),f.sync(!0,o).then(i=>{I(e.source,t,"epnc:sync-flush-finished",{reason:c,result:i&&typeof i=="object"?i:{}})}).catch(i=>{I(e.source,t,"epnc:sync-flush-failed",{reason:c,message:i instanceof Error?i.message:"Sync failed."})}),o&&f.stop()}}},window.addEventListener("message",q))},pe=async()=>{const e=new URLSearchParams;e.set("fileId",String(g));const t=await v(U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",requesttoken:h()},body:e.toString()});return Ae(t)},ue=async()=>{const e=O.replace("__FILE_ID__",encodeURIComponent(String(g))),t=await v(e,{method:"POST",headers:{requesttoken:h()}},{timeoutMs:null});t&&t.status==="migrated_from_legacy"&&console.info("Legacy Ownpad .pad migrated to managed format on first open.")},L=()=>{s instanceof HTMLElement&&(s.hidden=!0),_ instanceof HTMLElement&&(_.hidden=!0),p instanceof HTMLElement&&(p.hidden=!0),u instanceof HTMLIFrameElement&&(u.hidden=!0,u.removeAttribute("src"))},fe=()=>{p instanceof HTMLElement&&(L(),p.hidden=!1,l instanceof HTMLElement&&(l.textContent=te),b instanceof HTMLElement&&(b.textContent=""),m instanceof HTMLElement&&m.replaceChildren())},ge=(e,t)=>{if(p instanceof HTMLElement&&(L(),p.hidden=!1,l instanceof HTMLElement&&(l.textContent=t),b instanceof HTMLElement&&(b.textContent=ne),m instanceof HTMLElement)){const r=document.createElement("a");r.className=H,r.href=e,r.textContent=ae,m.replaceChildren(r,T(G,()=>{K()}))}},W=(e,t=re)=>{p instanceof HTMLElement&&(L(),p.hidden=!1,l instanceof HTMLElement&&(l.textContent=e),b instanceof HTMLElement&&(b.textContent=t),m instanceof HTMLElement&&m.replaceChildren(T(G,()=>{K()},H)))},J=e=>{m instanceof HTMLElement&&m.querySelectorAll("button").forEach(t=>{t.disabled=e,e?(t.dataset.originalLabel=t.dataset.originalLabel||t.textContent||"",t.textContent=oe):t.dataset.originalLabel&&(t.textContent=t.dataset.originalLabel,delete t.dataset.originalLabel)})},K=async()=>{if(P===""){E("Recovery is not available in this embed.");return}J(!0);const e=P.replace("__FILE_ID__",encodeURIComponent(String(g)));try{await v(e,{method:"POST",headers:{requesttoken:h()}},{timeoutMs:null}),M(!0)}catch(t){if(_e(t)){M(!0);return}J(!1),l instanceof HTMLElement&&(l.textContent=y(t,"Recovery failed.")),S(m,l)}},be=async()=>{if(B==="")return"";const e=B.replace("__FILE_ID__",encodeURIComponent(String(g)));try{const t=await v(e,{method:"GET"});if(t&&t.found===!0&&typeof t.embed_url=="string")return t.embed_url}catch{}return""},he=async(e,t,r)=>{const n=y(e,"Pad open failed.");fe();const o=await be();r()&&(o!==""?ge(o,n):W(n),t&&S(m,l))};let R=0;const M=async(e=!1)=>{R+=1;const t=R,r=()=>t===R;if(ce(),!Number.isFinite(g)||g<=0||U===""||O===""){E("Embed configuration is incomplete.");return}if(h()===""){E("CSRF request token is missing.");return}try{const n=await Ce({open:pe,initialize:ue,stillWanted:r});if(n===null||!r())return;const{syncUrl:o,intervalMs:c}=Se(n);f.configure({syncUrl:o,intervalMs:c}),f.installLifecycleHandlers(),me(),o!==""&&f.start();const i=Te(n),{isContentView:d,externalUrl:ye}=Me(n);if(d){const x=de(ye);x!==null&&x.refresh.addEventListener("click",()=>{k(x,i)}),k(x,i);return}se(xe(n))}catch(n){if(!r())return;if(ve(n)){he(n,e,r);return}if(He(n)){W(y(n,"Pad open failed."),""),e&&S(m,l);return}E(y(n,"Pad open failed."),we(n),e)}};M()})(); //# sourceMappingURL=etherpad_nextcloud-embed-main.mjs.map diff --git a/js/etherpad_nextcloud-embed-main.mjs.map b/js/etherpad_nextcloud-embed-main.mjs.map index 3b9afae7..d83724c6 100644 --- a/js/etherpad_nextcloud-embed-main.mjs.map +++ b/js/etherpad_nextcloud-embed-main.mjs.map @@ -1 +1 @@ -{"version":3,"file":"etherpad_nextcloud-embed-main.mjs","sources":["../src/embed-main.js"],"sourcesContent":["/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\nimport { ocRequestToken } from './lib/oc-compat.js'\nimport { createPadSync } from './lib/pad-sync.js'\nimport { fetchJsonWithTimeout as fetchJson, isUnanswered, requestErrorMessage } from './lib/fetch-helpers.js'\nimport { handFocusTo } from './lib/hand-focus.js'\nimport { loadPadContent } from './lib/pad-content.js'\nimport { assertOpenPayload, contentUrlFrom, contentViewFrom, isMissingBindingError, isRetryableOpenError, openWithFrontmatterRecovery, padUrlFrom, syncSettingsFrom } from './lib/pad-open-flow.js'\n\n(function () {\n\tconst IFRAME_REVEAL_DELAY_MS = 100\n\tconst BUTTON_CLASS = 'epnc-embed__recovery-button'\n\tconst PRIMARY_BUTTON_CLASS = BUTTON_CLASS + ' epnc-embed__recovery-button--primary'\n\n\tconst root = document.getElementById('etherpad-nextcloud-embed')\n\tif (!(root instanceof HTMLElement)) {\n\t\treturn\n\t}\n\n\tconst fileId = Number(root.getAttribute('data-file-id') || '')\n\tconst openByIdUrl = String(root.getAttribute('data-open-by-id-url') || '').trim()\n\tconst initializeByIdUrlTemplate = String(root.getAttribute('data-initialize-by-id-url-template') || '').trim()\n\tconst recoverUrlTemplate = String(root.getAttribute('data-recover-url-template') || '').trim()\n\tconst findOriginalUrlTemplate = String(root.getAttribute('data-find-original-url-template') || '').trim()\n\tconst templateRequestToken = String(root.getAttribute('data-request-token') || '').trim()\n\tconst trustedOrigins = String(root.getAttribute('data-trusted-origins') || '')\n\t\t.split(/\\s+/)\n\t\t.map((value) => value.trim())\n\t\t.filter(Boolean)\n\tconst loadingNode = root.querySelector('[data-epnc-embed-loading]')\n\tconst errorNode = root.querySelector('[data-epnc-embed-error]')\n\tconst errorMessageNode = root.querySelector('[data-epnc-embed-error-message]')\n\tconst errorActionsNode = root.querySelector('[data-epnc-embed-error-actions]')\n\tconst recoveryNode = root.querySelector('[data-epnc-embed-recovery]')\n\tconst recoveryMessageNode = root.querySelector('[data-epnc-embed-recovery-message]')\n\tconst recoveryBodyNode = root.querySelector('[data-epnc-embed-recovery-body]')\n\tconst recoveryActionsNode = root.querySelector('[data-epnc-embed-recovery-actions]')\n\tconst iframe = root.querySelector('[data-epnc-embed-iframe]')\n\tconst contentEmptyText = String(root.getAttribute('data-l10n-content-empty') || 'This pad is still empty.').trim()\n\tconst contentLoadingText = String(root.getAttribute('data-l10n-content-loading') || 'Loading pad content...').trim()\n\tconst contentErrorText = String(root.getAttribute('data-l10n-content-error') || 'Could not load the pad content.').trim()\n\tconst contentNoUrlText = String(root.getAttribute('data-l10n-content-no-url') || 'The server did not say where to load this pad from.').trim()\n\tconst contentRetryText = String(root.getAttribute('data-l10n-content-retry') || 'Try again').trim()\n\tconst contentRefreshText = String(root.getAttribute('data-l10n-content-refresh') || 'Refresh').trim()\n\tconst contentRefreshingText = String(root.getAttribute('data-l10n-content-refreshing') || 'Refreshing...').trim()\n\tconst externalLinkText = String(root.getAttribute('data-l10n-external-link') || 'Open original pad').trim()\n\tconst recoveryCheckingText = String(root.getAttribute('data-l10n-recovery-checking') || 'Checking for the original pad...').trim()\n\tconst recoveryCopyBodyText = String(root.getAttribute('data-l10n-recovery-copy-body') || '').trim()\n\tconst recoveryOrphanBodyText = String(root.getAttribute('data-l10n-recovery-orphan-body') || '').trim()\n\tconst recoveryOpenOriginalText = String(root.getAttribute('data-l10n-recovery-open-original') || 'Open the original .pad file').trim()\n\tconst recoveryCreateNewText = String(root.getAttribute('data-l10n-recovery-create-new') || 'Create new pad from this file').trim()\n\tconst recoveryCreatingText = String(root.getAttribute('data-l10n-recovery-creating') || 'Creating new pad...').trim()\n\tconst unansweredText = String(root.getAttribute('data-l10n-unanswered') || 'Nextcloud did not answer. Check your connection and try again.').trim()\n\tlet messageHandler = null\n\n\tconst requestToken = () => ocRequestToken(templateRequestToken)\n\tconst padSync = createPadSync({ requestToken })\n\n\tconst messageOf = (error, fallback) => requestErrorMessage(error, unansweredText, fallback)\n\t// The page sits in another one, which must not scroll to it.\n\tconst handFocusToCard = (actionsNode, messageNode) => handFocusTo(actionsNode, messageNode, { preventScroll: true })\n\n\t/** Every button of this page: the content's retry, the error panel's, the recovery card's. */\n\tconst buildButton = (label, onClick, className = BUTTON_CLASS) => {\n\t\tconst button = document.createElement('button')\n\t\tbutton.type = 'button'\n\t\tbutton.className = className\n\t\tbutton.textContent = label\n\t\tbutton.addEventListener('click', onClick)\n\t\treturn button\n\t}\n\n\t/**\n\t * $canRetry: the open may work later (`isRetryableOpenError`), so the\n\t * panel offers to run it again rather than a dead end. $afterClick: see\n\t * handFocusTo().\n\t */\n\tconst showError = (message, canRetry = false, afterClick = false) => {\n\t\thideAllPanels()\n\t\tif (errorMessageNode instanceof HTMLElement) {\n\t\t\terrorMessageNode.textContent = String(message || 'Unknown error.')\n\t\t}\n\t\tif (errorActionsNode instanceof HTMLElement) {\n\t\t\terrorActionsNode.replaceChildren()\n\t\t\tif (canRetry) {\n\t\t\t\terrorActionsNode.appendChild(buildButton(contentRetryText, () => { void run(true) }, PRIMARY_BUTTON_CLASS))\n\t\t\t}\n\t\t}\n\t\tif (errorNode instanceof HTMLElement) {\n\t\t\terrorNode.hidden = false\n\t\t}\n\t\tif (afterClick) {\n\t\t\thandFocusToCard(errorActionsNode, errorMessageNode)\n\t\t}\n\t}\n\n\t/** Every panel away and the loading state up: where every open starts. */\n\tconst showLoading = () => {\n\t\thideAllPanels()\n\t\tif (loadingNode instanceof HTMLElement) {\n\t\t\tloadingNode.classList.remove('epnc-embed__loading--pad-doc')\n\t\t\tloadingNode.hidden = false\n\t\t}\n\t}\n\n\t/**\n\t * The read-only surface: a small toolbar and a document area that\n\t * `loadContent` fills. Returns the parts the loader redraws, so the\n\t * frame and its button survive a refresh.\n\t */\n\tconst showPadContentView = (url) => {\n\t\tif (!(loadingNode instanceof HTMLElement)) {\n\t\t\treturn null\n\t\t}\n\t\tloadingNode.classList.add('epnc-embed__loading--pad-doc')\n\t\tloadingNode.textContent = ''\n\n\t\tconst surface = document.createElement('div')\n\t\tsurface.className = 'epnc-pad-doc'\n\n\t\tconst inner = document.createElement('div')\n\t\tinner.className = 'epnc-pad-doc__inner'\n\n\t\tconst toolbar = document.createElement('div')\n\t\ttoolbar.className = 'epnc-pad-doc__toolbar'\n\n\t\t// A failed refresh is reported here rather than in place of the pad.\n\t\tconst toolbarError = document.createElement('span')\n\t\ttoolbarError.className = 'epnc-pad-doc__toolbar-error'\n\t\ttoolbarError.hidden = true\n\t\ttoolbar.appendChild(toolbarError)\n\n\t\tconst refresh = document.createElement('button')\n\t\trefresh.type = 'button'\n\t\trefresh.className = 'button epnc-pad-doc__refresh'\n\t\trefresh.textContent = contentRefreshText\n\t\ttoolbar.appendChild(refresh)\n\n\t\t// A read-only share has nothing to link to: the pad it would point\n\t\t// at is the one being withheld.\n\t\tif (String(url || '').trim() !== '') {\n\t\t\tconst link = document.createElement('a')\n\t\t\tlink.className = 'button epnc-pad-doc__link'\n\t\t\tlink.href = url\n\t\t\tlink.target = '_blank'\n\t\t\tlink.rel = 'noopener noreferrer'\n\t\t\tlink.textContent = externalLinkText\n\t\t\ttoolbar.appendChild(link)\n\t\t}\n\n\t\tconst body = document.createElement('div')\n\t\tbody.className = 'epnc-pad-doc__text'\n\t\tbody.textContent = contentLoadingText\n\n\t\tinner.appendChild(toolbar)\n\t\tinner.appendChild(body)\n\t\tsurface.appendChild(inner)\n\t\tloadingNode.appendChild(surface)\n\n\t\t// `loaded`: \"busy\" and \"nothing yet\" are two states, and only the\n\t\t// second may blank the view.\n\t\treturn { body, refresh, toolbarError, loaded: false }\n\t}\n\n\t// So a slower earlier answer cannot land on top of a newer one.\n\tlet contentGeneration = 0\n\n\t/** Each call re-checks access on the server. */\n\tconst loadContent = async (view, contentUrl) => {\n\t\tif (!view || !(view.body instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tconst { body, refresh, toolbarError } = view\n\t\tcontentGeneration += 1\n\t\tconst generation = contentGeneration\n\t\tconst isCurrent = () => generation === contentGeneration\n\n\t\t// Only before the first answer; after that the button carries it.\n\t\tif (!view.loaded) {\n\t\t\tbody.className = 'epnc-pad-doc__text'\n\t\t\tbody.textContent = contentLoadingText\n\t\t}\n\t\tif (toolbarError instanceof HTMLElement) {\n\t\t\ttoolbarError.hidden = true\n\t\t}\n\t\tif (refresh instanceof HTMLButtonElement) {\n\t\t\trefresh.disabled = true\n\t\t\trefresh.textContent = contentRefreshingText\n\t\t}\n\n\t\ttry {\n\t\t\tif (contentUrl === '') {\n\t\t\t\t// Retrying cannot help, so the message says what is actually\n\t\t\t\t// wrong instead of inviting another press.\n\t\t\t\trenderContentError(view, contentUrl, contentNoUrlText, false)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst content = await loadPadContent(contentUrl)\n\t\t\tif (!isCurrent()) return\n\t\t\tview.loaded = true\n\t\t\tif (content.isEmpty) {\n\t\t\t\t// Left blank this would read as a failure nobody reported.\n\t\t\t\tbody.className = 'epnc-pad-doc__text'\n\t\t\t\tbody.textContent = contentEmptyText\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbody.className = 'epnc-pad-doc__text epnc-pad-doc__text--html'\n\t\t\tbody.innerHTML = content.html\n\t\t} catch (error) {\n\t\t\tif (!isCurrent()) return\n\t\t\trenderContentError(view, contentUrl, messageOf(error, contentErrorText))\n\t\t} finally {\n\t\t\tif (isCurrent() && refresh instanceof HTMLButtonElement) {\n\t\t\t\trefresh.disabled = false\n\t\t\t\trefresh.textContent = contentRefreshText\n\t\t\t}\n\t\t}\n\t}\n\n\tconst renderContentError = (view, contentUrl, message, canRetry = true) => {\n\t\tconst { body, toolbarError } = view\n\t\t// Something is on screen: keep it, and say the attempt failed.\n\t\tif (view.loaded && toolbarError instanceof HTMLElement) {\n\t\t\ttoolbarError.textContent = message || contentErrorText\n\t\t\ttoolbarError.hidden = false\n\t\t\treturn\n\t\t}\n\t\tbody.className = 'epnc-pad-doc__text'\n\t\tbody.textContent = ''\n\n\t\tconst text = document.createElement('p')\n\t\ttext.textContent = message || contentErrorText\n\n\t\tbody.appendChild(text)\n\t\tif (canRetry) {\n\t\t\tbody.appendChild(buildButton(contentRetryText, () => { void loadContent(view, contentUrl) }, 'button primary'))\n\t\t}\n\t}\n\n\tconst showIframe = (url) => {\n\t\tif (!(iframe instanceof HTMLIFrameElement)) {\n\t\t\tshowError('Embed iframe is not available.')\n\t\t\treturn\n\t\t}\n\t\t// The loading state the open started from stays up until the pad has loaded.\n\t\tconst revealIframe = () => {\n\t\t\tiframe.removeEventListener('load', revealIframe)\n\t\t\twindow.setTimeout(() => {\n\t\t\t\tif (loadingNode instanceof HTMLElement) {\n\t\t\t\t\tloadingNode.hidden = true\n\t\t\t\t}\n\t\t\t\tiframe.hidden = false\n\t\t\t}, IFRAME_REVEAL_DELAY_MS)\n\t\t}\n\t\tiframe.addEventListener('load', revealIframe, { once: true })\n\t\tiframe.src = url\n\t}\n\n\tconst postHostMessage = (source, origin, type, payload = {}) => {\n\t\t// Replies are only sent from the already origin-validated message handler.\n\t\tif (!source || typeof source.postMessage !== 'function') {\n\t\t\treturn\n\t\t}\n\t\tsource.postMessage(Object.assign({\n\t\t\ttype,\n\t\t\tfileId,\n\t\t}, payload), origin)\n\t}\n\n\tconst isAllowedMessageOrigin = (origin) => {\n\t\tif (!origin || origin === 'null') {\n\t\t\treturn false\n\t\t}\n\t\tif (origin === window.location.origin) {\n\t\t\treturn true\n\t\t}\n\t\treturn trustedOrigins.includes(origin)\n\t}\n\n\tconst installHostMessageHandler = () => {\n\t\tif (messageHandler) {\n\t\t\treturn\n\t\t}\n\t\tmessageHandler = (event) => {\n\t\t\tconst origin = String(event.origin || '')\n\t\t\tif (!isAllowedMessageOrigin(origin)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst payload = event.data\n\t\t\tconst type = typeof payload === 'string'\n\t\t\t\t? payload\n\t\t\t\t: (payload && typeof payload === 'object' && typeof payload.type === 'string' ? payload.type : '')\n\t\t\tif (!type) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (type === 'epnc:host-visible') {\n\t\t\t\tpadSync.start()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (type === 'epnc:host-hidden') {\n\t\t\t\tpadSync.fireAndForget(true, true)\n\t\t\t\tpadSync.stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (type === 'epnc:host-before-close' || type === 'epnc:host-sync-now') {\n\t\t\t\tconst keepalive = type !== 'epnc:host-sync-now'\n\t\t\t\tconst reason = type === 'epnc:host-before-close' ? 'before-close' : 'sync-now'\n\t\t\t\tpostHostMessage(event.source, origin, 'epnc:sync-flush-started', {\n\t\t\t\t\treason,\n\t\t\t\t})\n\t\t\t\tvoid padSync.sync(true, keepalive)\n\t\t\t\t\t.then((result) => {\n\t\t\t\t\t\tpostHostMessage(event.source, origin, 'epnc:sync-flush-finished', {\n\t\t\t\t\t\t\treason,\n\t\t\t\t\t\t\tresult: result && typeof result === 'object' ? result : {},\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\tpostHostMessage(event.source, origin, 'epnc:sync-flush-failed', {\n\t\t\t\t\t\t\treason,\n\t\t\t\t\t\t\tmessage: error instanceof Error ? error.message : 'Sync failed.',\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\tif (keepalive) {\n\t\t\t\t\tpadSync.stop()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twindow.addEventListener('message', messageHandler)\n\t}\n\n\tconst openPad = async () => {\n\t\tconst body = new URLSearchParams()\n\t\tbody.set('fileId', String(fileId))\n\t\tconst data = await fetchJson(openByIdUrl, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n\t\t\t\trequesttoken: requestToken(),\n\t\t\t},\n\t\t\tbody: body.toString(),\n\t\t})\n\t\treturn assertOpenPayload(data)\n\t}\n\n\tconst initializePad = async () => {\n\t\tconst url = initializeByIdUrlTemplate.replace('__FILE_ID__', encodeURIComponent(String(fileId)))\n\t\t// A write: see fetchJsonWithTimeout() for why it gets no timeout.\n\t\tconst data = await fetchJson(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\trequesttoken: requestToken(),\n\t\t\t},\n\t\t}, { timeoutMs: null })\n\t\tif (data && data.status === 'migrated_from_legacy') {\n\t\t\t// Mirror the backend audit-log entry to the browser console; no\n\t\t\t// toast surface is wired up in this app yet.\n\t\t\tconsole.info('Legacy Ownpad .pad migrated to managed format on first open.')\n\t\t}\n\t}\n\n\tconst hideAllPanels = () => {\n\t\tif (loadingNode instanceof HTMLElement) loadingNode.hidden = true\n\t\tif (errorNode instanceof HTMLElement) errorNode.hidden = true\n\t\tif (recoveryNode instanceof HTMLElement) recoveryNode.hidden = true\n\t\tif (iframe instanceof HTMLIFrameElement) {\n\t\t\tiframe.hidden = true\n\t\t\tiframe.removeAttribute('src')\n\t\t}\n\t}\n\n\tconst showRecoveryChecking = () => {\n\t\tif (!(recoveryNode instanceof HTMLElement)) return\n\t\thideAllPanels()\n\t\trecoveryNode.hidden = false\n\t\tif (recoveryMessageNode instanceof HTMLElement) recoveryMessageNode.textContent = recoveryCheckingText\n\t\tif (recoveryBodyNode instanceof HTMLElement) recoveryBodyNode.textContent = ''\n\t\tif (recoveryActionsNode instanceof HTMLElement) recoveryActionsNode.replaceChildren()\n\t}\n\n\tconst showRecoveryWithOriginal = (originalEmbedUrl, errorMessage) => {\n\t\tif (!(recoveryNode instanceof HTMLElement)) return\n\t\thideAllPanels()\n\t\trecoveryNode.hidden = false\n\t\tif (recoveryMessageNode instanceof HTMLElement) recoveryMessageNode.textContent = errorMessage\n\t\tif (recoveryBodyNode instanceof HTMLElement) recoveryBodyNode.textContent = recoveryCopyBodyText\n\t\tif (recoveryActionsNode instanceof HTMLElement) {\n\t\t\tconst openLink = document.createElement('a')\n\t\t\topenLink.className = PRIMARY_BUTTON_CLASS\n\t\t\t// Stay in embed mode: load the original's embed page in the same\n\t\t\t// frame so a host iframe doesn't need to deal with a new tab.\n\t\t\topenLink.href = originalEmbedUrl\n\t\t\topenLink.textContent = recoveryOpenOriginalText\n\t\t\trecoveryActionsNode.replaceChildren(\n\t\t\t\topenLink,\n\t\t\t\tbuildButton(recoveryCreateNewText, () => { void triggerRecovery() }),\n\t\t\t)\n\t\t}\n\t}\n\n\tconst showRecoveryWithoutOriginal = (errorMessage) => {\n\t\tif (!(recoveryNode instanceof HTMLElement)) return\n\t\thideAllPanels()\n\t\trecoveryNode.hidden = false\n\t\tif (recoveryMessageNode instanceof HTMLElement) recoveryMessageNode.textContent = errorMessage\n\t\tif (recoveryBodyNode instanceof HTMLElement) recoveryBodyNode.textContent = recoveryOrphanBodyText\n\t\tif (recoveryActionsNode instanceof HTMLElement) {\n\t\t\trecoveryActionsNode.replaceChildren(\n\t\t\t\tbuildButton(recoveryCreateNewText, () => { void triggerRecovery() }, PRIMARY_BUTTON_CLASS),\n\t\t\t)\n\t\t}\n\t}\n\n\tconst setRecoveryActionsBusy = (busy) => {\n\t\tif (!(recoveryActionsNode instanceof HTMLElement)) return\n\t\tconst buttons = recoveryActionsNode.querySelectorAll('button')\n\t\tbuttons.forEach((node) => {\n\t\t\tnode.disabled = busy\n\t\t\tif (busy) {\n\t\t\t\tnode.dataset.originalLabel = node.dataset.originalLabel || node.textContent || ''\n\t\t\t\tnode.textContent = recoveryCreatingText\n\t\t\t} else if (node.dataset.originalLabel) {\n\t\t\t\tnode.textContent = node.dataset.originalLabel\n\t\t\t\tdelete node.dataset.originalLabel\n\t\t\t}\n\t\t})\n\t}\n\n\tconst triggerRecovery = async () => {\n\t\tif (recoverUrlTemplate === '') {\n\t\t\tshowError('Recovery is not available in this embed.')\n\t\t\treturn\n\t\t}\n\t\tsetRecoveryActionsBusy(true)\n\t\tconst url = recoverUrlTemplate.replace('__FILE_ID__', encodeURIComponent(String(fileId)))\n\t\ttry {\n\t\t\t// A write, like initializePad().\n\t\t\tawait fetchJson(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { requesttoken: requestToken() },\n\t\t\t}, { timeoutMs: null })\n\t\t\t// Open again now that the binding exists.\n\t\t\tvoid run(true)\n\t\t} catch (error) {\n\t\t\t// No answer: the pad may be set up by now, and another recovery\n\t\t\t// would meet it. Opening tells, and is safe to repeat.\n\t\t\tif (isUnanswered(error)) {\n\t\t\t\tvoid run(true)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsetRecoveryActionsBusy(false)\n\t\t\tif (recoveryMessageNode instanceof HTMLElement) {\n\t\t\t\trecoveryMessageNode.textContent = messageOf(error, 'Recovery failed.')\n\t\t\t}\n\t\t\t// The clicked button lost the focus while it was disabled.\n\t\t\thandFocusToCard(recoveryActionsNode, recoveryMessageNode)\n\t\t}\n\t}\n\n\t/** The original's embed page, or '' when there is none or no answer. */\n\tconst findOriginalEmbedUrl = async () => {\n\t\tif (findOriginalUrlTemplate === '') {\n\t\t\treturn ''\n\t\t}\n\t\tconst lookupUrl = findOriginalUrlTemplate.replace('__FILE_ID__', encodeURIComponent(String(fileId)))\n\t\ttry {\n\t\t\tconst hint = await fetchJson(lookupUrl, { method: 'GET' })\n\t\t\tif (hint && hint.found === true && typeof hint.embed_url === 'string') {\n\t\t\t\treturn hint.embed_url\n\t\t\t}\n\t\t} catch {\n\t\t\t// Silent: the card then offers a new pad only.\n\t\t}\n\t\treturn ''\n\t}\n\n\tconst enterRecoveryFlow = async (initialError, afterClick, isCurrent) => {\n\t\tconst errorMessage = messageOf(initialError, 'Pad open failed.')\n\t\tshowRecoveryChecking()\n\t\tconst originalEmbedUrl = await findOriginalEmbedUrl()\n\t\tif (!isCurrent()) {\n\t\t\treturn\n\t\t}\n\t\tif (originalEmbedUrl !== '') {\n\t\t\tshowRecoveryWithOriginal(originalEmbedUrl, errorMessage)\n\t\t} else {\n\t\t\tshowRecoveryWithoutOriginal(errorMessage)\n\t\t}\n\t\tif (afterClick) {\n\t\t\thandFocusToCard(recoveryActionsNode, recoveryMessageNode)\n\t\t}\n\t}\n\n\t// So an open that answers late cannot undo a newer one.\n\tlet openGeneration = 0\n\n\t/** $afterClick: a second try or a recovery started it; see handFocusTo(). */\n\tconst run = async (afterClick = false) => {\n\t\topenGeneration += 1\n\t\tconst generation = openGeneration\n\t\tconst isCurrent = () => generation === openGeneration\n\t\tshowLoading()\n\t\tif (!Number.isFinite(fileId) || fileId <= 0 || openByIdUrl === '' || initializeByIdUrlTemplate === '') {\n\t\t\tshowError('Embed configuration is incomplete.')\n\t\t\treturn\n\t\t}\n\t\tif (requestToken() === '') {\n\t\t\tshowError('CSRF request token is missing.')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tconst data = await openWithFrontmatterRecovery({ open: openPad, initialize: initializePad, stillWanted: isCurrent })\n\t\t\tif (data === null || !isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { syncUrl, intervalMs } = syncSettingsFrom(data)\n\t\t\tpadSync.configure({ syncUrl, intervalMs })\n\t\t\tpadSync.installLifecycleHandlers()\n\t\t\tinstallHostMessageHandler()\n\t\t\t// No syncing for a viewer: it writes the pad back into the .pad\n\t\t\t// file, which is exactly what a read-only share may not do.\n\t\t\tif (syncUrl !== '') {\n\t\t\t\tpadSync.start()\n\t\t\t}\n\t\t\tconst contentUrl = contentUrlFrom(data)\n\t\t\tconst { isContentView, externalUrl } = contentViewFrom(data)\n\t\t\tif (isContentView) {\n\t\t\t\tconst view = showPadContentView(externalUrl)\n\t\t\t\tif (view !== null) {\n\t\t\t\t\tview.refresh.addEventListener('click', () => { void loadContent(view, contentUrl) })\n\t\t\t\t}\n\t\t\t\tvoid loadContent(view, contentUrl)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshowIframe(padUrlFrom(data))\n\t\t} catch (error) {\n\t\t\tif (!isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (isMissingBindingError(error)) {\n\t\t\t\tvoid enterRecoveryFlow(error, afterClick, isCurrent)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshowError(messageOf(error, 'Pad open failed.'), isRetryableOpenError(error), afterClick)\n\t\t}\n\t}\n\n\tvoid run()\n})()\n"],"names":["BUTTON_CLASS","PRIMARY_BUTTON_CLASS","root","fileId","openByIdUrl","initializeByIdUrlTemplate","recoverUrlTemplate","findOriginalUrlTemplate","templateRequestToken","trustedOrigins","value","loadingNode","errorNode","errorMessageNode","errorActionsNode","recoveryNode","recoveryMessageNode","recoveryBodyNode","recoveryActionsNode","iframe","contentEmptyText","contentLoadingText","contentErrorText","contentNoUrlText","contentRetryText","contentRefreshText","contentRefreshingText","externalLinkText","recoveryCheckingText","recoveryCopyBodyText","recoveryOrphanBodyText","recoveryOpenOriginalText","recoveryCreateNewText","recoveryCreatingText","unansweredText","messageHandler","requestToken","ocRequestToken","padSync","createPadSync","messageOf","error","fallback","requestErrorMessage","handFocusToCard","actionsNode","messageNode","handFocusTo","buildButton","label","onClick","className","button","showError","message","canRetry","afterClick","hideAllPanels","run","showLoading","showPadContentView","url","surface","inner","toolbar","toolbarError","refresh","link","body","contentGeneration","loadContent","view","contentUrl","generation","isCurrent","renderContentError","content","loadPadContent","text","showIframe","revealIframe","postHostMessage","source","origin","type","payload","isAllowedMessageOrigin","installHostMessageHandler","event","keepalive","reason","result","openPad","data","fetchJson","assertOpenPayload","initializePad","showRecoveryChecking","showRecoveryWithOriginal","originalEmbedUrl","errorMessage","openLink","triggerRecovery","showRecoveryWithoutOriginal","setRecoveryActionsBusy","busy","node","isUnanswered","findOriginalEmbedUrl","lookupUrl","hint","enterRecoveryFlow","initialError","openGeneration","openWithFrontmatterRecovery","syncUrl","intervalMs","syncSettingsFrom","contentUrlFrom","isContentView","externalUrl","contentViewFrom","padUrlFrom","isMissingBindingError","isRetryableOpenError"],"mappings":"wNAWC,UAAY,CAEZ,MAAMA,EAAe,8BACfC,EAAuBD,EAAe,wCAEtCE,EAAO,SAAS,eAAe,0BAA0B,EAC/D,GAAI,EAAEA,aAAgB,aACrB,OAGD,MAAMC,EAAS,OAAOD,EAAK,aAAa,cAAc,GAAK,EAAE,EACvDE,EAAc,OAAOF,EAAK,aAAa,qBAAqB,GAAK,EAAE,EAAE,KAAI,EACzEG,EAA4B,OAAOH,EAAK,aAAa,oCAAoC,GAAK,EAAE,EAAE,KAAI,EACtGI,EAAqB,OAAOJ,EAAK,aAAa,2BAA2B,GAAK,EAAE,EAAE,KAAI,EACtFK,EAA0B,OAAOL,EAAK,aAAa,iCAAiC,GAAK,EAAE,EAAE,KAAI,EACjGM,EAAuB,OAAON,EAAK,aAAa,oBAAoB,GAAK,EAAE,EAAE,KAAI,EACjFO,EAAiB,OAAOP,EAAK,aAAa,sBAAsB,GAAK,EAAE,EAC3E,MAAM,KAAK,EACX,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AAYI,GAAe,YAAatB,CAAS,CAAE,EACnH,GAAImB,IAAS,MAAQ,CAACnB,IACrB,OAED,KAAM,CAAE,QAAAyC,EAAS,WAAAC,CAAU,EAAKC,GAAiBxB,CAAI,EACrDvD,EAAQ,UAAU,CAAE,QAAA6E,EAAS,WAAAC,CAAU,CAAE,EACzC9E,EAAQ,yBAAwB,EAChCiD,GAAyB,EAGrB4B,IAAY,IACf7E,EAAQ,MAAK,EAEd,MAAMkC,EAAa8C,GAAezB,CAAI,EAChC,CAAE,cAAA0B,EAAe,YAAAC,EAAW,EAAKC,GAAgB5B,CAAI,EAC3D,GAAI0B,EAAe,CAClB,MAAMhD,EAAOX,GAAmB4D,EAAW,EACvCjD,IAAS,MACZA,EAAK,QAAQ,iBAAiB,QAAS,IAAM,CAAOD,EAAYC,EAAMC,CAAU,CAAE,CAAC,EAE/EF,EAAYC,EAAMC,CAAU,EACjC,MACD,CACAO,GAAW2C,GAAW7B,CAAI,CAAC,CAC5B,OAASpD,EAAO,CACf,GAAI,CAACiC,EAAS,EACb,OAED,GAAIiD,GAAsBlF,CAAK,EAAG,CAC5BsE,GAAkBtE,EAAOe,EAAYkB,CAAS,EACnD,MACD,CACArB,EAAUb,EAAUC,EAAO,kBAAkB,EAAGmF,GAAqBnF,CAAK,EAAGe,CAAU,CACxF,CACD,EAEKE,EAAG,CACT,GAAC"} \ No newline at end of file +{"version":3,"file":"etherpad_nextcloud-embed-main.mjs","sources":["../src/embed-main.js"],"sourcesContent":["/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\nimport { ocRequestToken } from './lib/oc-compat.js'\nimport { createPadSync } from './lib/pad-sync.js'\nimport { fetchJsonWithTimeout as fetchJson, isUnanswered, requestErrorMessage } from './lib/fetch-helpers.js'\nimport { handFocusTo } from './lib/hand-focus.js'\nimport { loadPadContent } from './lib/pad-content.js'\nimport { assertOpenPayload, contentUrlFrom, contentViewFrom, isMissingBindingError, isPadMissingError, isRetryableOpenError, openWithFrontmatterRecovery, padUrlFrom, syncSettingsFrom } from './lib/pad-open-flow.js'\n\n(function () {\n\tconst IFRAME_REVEAL_DELAY_MS = 100\n\tconst BUTTON_CLASS = 'epnc-embed__recovery-button'\n\tconst PRIMARY_BUTTON_CLASS = BUTTON_CLASS + ' epnc-embed__recovery-button--primary'\n\n\tconst root = document.getElementById('etherpad-nextcloud-embed')\n\tif (!(root instanceof HTMLElement)) {\n\t\treturn\n\t}\n\n\tconst fileId = Number(root.getAttribute('data-file-id') || '')\n\tconst openByIdUrl = String(root.getAttribute('data-open-by-id-url') || '').trim()\n\tconst initializeByIdUrlTemplate = String(root.getAttribute('data-initialize-by-id-url-template') || '').trim()\n\tconst recoverUrlTemplate = String(root.getAttribute('data-recover-url-template') || '').trim()\n\tconst findOriginalUrlTemplate = String(root.getAttribute('data-find-original-url-template') || '').trim()\n\tconst templateRequestToken = String(root.getAttribute('data-request-token') || '').trim()\n\tconst trustedOrigins = String(root.getAttribute('data-trusted-origins') || '')\n\t\t.split(/\\s+/)\n\t\t.map((value) => value.trim())\n\t\t.filter(Boolean)\n\tconst loadingNode = root.querySelector('[data-epnc-embed-loading]')\n\tconst errorNode = root.querySelector('[data-epnc-embed-error]')\n\tconst errorMessageNode = root.querySelector('[data-epnc-embed-error-message]')\n\tconst errorActionsNode = root.querySelector('[data-epnc-embed-error-actions]')\n\tconst recoveryNode = root.querySelector('[data-epnc-embed-recovery]')\n\tconst recoveryMessageNode = root.querySelector('[data-epnc-embed-recovery-message]')\n\tconst recoveryBodyNode = root.querySelector('[data-epnc-embed-recovery-body]')\n\tconst recoveryActionsNode = root.querySelector('[data-epnc-embed-recovery-actions]')\n\tconst iframe = root.querySelector('[data-epnc-embed-iframe]')\n\tconst contentEmptyText = String(root.getAttribute('data-l10n-content-empty') || 'This pad is still empty.').trim()\n\tconst contentLoadingText = String(root.getAttribute('data-l10n-content-loading') || 'Loading pad content...').trim()\n\tconst contentErrorText = String(root.getAttribute('data-l10n-content-error') || 'Could not load the pad content.').trim()\n\tconst contentNoUrlText = String(root.getAttribute('data-l10n-content-no-url') || 'The server did not say where to load this pad from.').trim()\n\tconst contentRetryText = String(root.getAttribute('data-l10n-content-retry') || 'Try again').trim()\n\tconst contentRefreshText = String(root.getAttribute('data-l10n-content-refresh') || 'Refresh').trim()\n\tconst contentRefreshingText = String(root.getAttribute('data-l10n-content-refreshing') || 'Refreshing...').trim()\n\tconst externalLinkText = String(root.getAttribute('data-l10n-external-link') || 'Open original pad').trim()\n\tconst recoveryCheckingText = String(root.getAttribute('data-l10n-recovery-checking') || 'Checking for the original pad...').trim()\n\tconst recoveryCopyBodyText = String(root.getAttribute('data-l10n-recovery-copy-body') || '').trim()\n\tconst recoveryOrphanBodyText = String(root.getAttribute('data-l10n-recovery-orphan-body') || '').trim()\n\tconst recoveryOpenOriginalText = String(root.getAttribute('data-l10n-recovery-open-original') || 'Open the original .pad file').trim()\n\tconst recoveryCreateNewText = String(root.getAttribute('data-l10n-recovery-create-new') || 'Create new pad from this file').trim()\n\tconst recoveryCreatingText = String(root.getAttribute('data-l10n-recovery-creating') || 'Creating new pad...').trim()\n\tconst unansweredText = String(root.getAttribute('data-l10n-unanswered') || 'Nextcloud did not answer. Check your connection and try again.').trim()\n\tlet messageHandler = null\n\n\tconst requestToken = () => ocRequestToken(templateRequestToken)\n\tconst padSync = createPadSync({ requestToken })\n\n\tconst messageOf = (error, fallback) => requestErrorMessage(error, unansweredText, fallback)\n\t// The page sits in another one, which must not scroll to it.\n\tconst handFocusToCard = (actionsNode, messageNode) => handFocusTo(actionsNode, messageNode, { preventScroll: true })\n\n\t/** Every button of this page: the content's retry, the error panel's, the recovery card's. */\n\tconst buildButton = (label, onClick, className = BUTTON_CLASS) => {\n\t\tconst button = document.createElement('button')\n\t\tbutton.type = 'button'\n\t\tbutton.className = className\n\t\tbutton.textContent = label\n\t\tbutton.addEventListener('click', onClick)\n\t\treturn button\n\t}\n\n\t/**\n\t * $canRetry: the open may work later (`isRetryableOpenError`), so the\n\t * panel offers to run it again rather than a dead end. $afterClick: see\n\t * handFocusTo().\n\t */\n\tconst showError = (message, canRetry = false, afterClick = false) => {\n\t\thideAllPanels()\n\t\tif (errorMessageNode instanceof HTMLElement) {\n\t\t\terrorMessageNode.textContent = String(message || 'Unknown error.')\n\t\t}\n\t\tif (errorActionsNode instanceof HTMLElement) {\n\t\t\terrorActionsNode.replaceChildren()\n\t\t\tif (canRetry) {\n\t\t\t\terrorActionsNode.appendChild(buildButton(contentRetryText, () => { void run(true) }, PRIMARY_BUTTON_CLASS))\n\t\t\t}\n\t\t}\n\t\tif (errorNode instanceof HTMLElement) {\n\t\t\terrorNode.hidden = false\n\t\t}\n\t\tif (afterClick) {\n\t\t\thandFocusToCard(errorActionsNode, errorMessageNode)\n\t\t}\n\t}\n\n\t/** Every panel away and the loading state up: where every open starts. */\n\tconst showLoading = () => {\n\t\thideAllPanels()\n\t\tif (loadingNode instanceof HTMLElement) {\n\t\t\tloadingNode.classList.remove('epnc-embed__loading--pad-doc')\n\t\t\tloadingNode.hidden = false\n\t\t}\n\t}\n\n\t/**\n\t * The read-only surface: a small toolbar and a document area that\n\t * `loadContent` fills. Returns the parts the loader redraws, so the\n\t * frame and its button survive a refresh.\n\t */\n\tconst showPadContentView = (url) => {\n\t\tif (!(loadingNode instanceof HTMLElement)) {\n\t\t\treturn null\n\t\t}\n\t\tloadingNode.classList.add('epnc-embed__loading--pad-doc')\n\t\tloadingNode.textContent = ''\n\n\t\tconst surface = document.createElement('div')\n\t\tsurface.className = 'epnc-pad-doc'\n\n\t\tconst inner = document.createElement('div')\n\t\tinner.className = 'epnc-pad-doc__inner'\n\n\t\tconst toolbar = document.createElement('div')\n\t\ttoolbar.className = 'epnc-pad-doc__toolbar'\n\n\t\t// A failed refresh is reported here rather than in place of the pad.\n\t\tconst toolbarError = document.createElement('span')\n\t\ttoolbarError.className = 'epnc-pad-doc__toolbar-error'\n\t\ttoolbarError.hidden = true\n\t\ttoolbar.appendChild(toolbarError)\n\n\t\tconst refresh = document.createElement('button')\n\t\trefresh.type = 'button'\n\t\trefresh.className = 'button epnc-pad-doc__refresh'\n\t\trefresh.textContent = contentRefreshText\n\t\ttoolbar.appendChild(refresh)\n\n\t\t// A read-only share has nothing to link to: the pad it would point\n\t\t// at is the one being withheld.\n\t\tif (String(url || '').trim() !== '') {\n\t\t\tconst link = document.createElement('a')\n\t\t\tlink.className = 'button epnc-pad-doc__link'\n\t\t\tlink.href = url\n\t\t\tlink.target = '_blank'\n\t\t\tlink.rel = 'noopener noreferrer'\n\t\t\tlink.textContent = externalLinkText\n\t\t\ttoolbar.appendChild(link)\n\t\t}\n\n\t\tconst body = document.createElement('div')\n\t\tbody.className = 'epnc-pad-doc__text'\n\t\tbody.textContent = contentLoadingText\n\n\t\tinner.appendChild(toolbar)\n\t\tinner.appendChild(body)\n\t\tsurface.appendChild(inner)\n\t\tloadingNode.appendChild(surface)\n\n\t\t// `loaded`: \"busy\" and \"nothing yet\" are two states, and only the\n\t\t// second may blank the view.\n\t\treturn { body, refresh, toolbarError, loaded: false }\n\t}\n\n\t// So a slower earlier answer cannot land on top of a newer one.\n\tlet contentGeneration = 0\n\n\t/** Each call re-checks access on the server. */\n\tconst loadContent = async (view, contentUrl) => {\n\t\tif (!view || !(view.body instanceof HTMLElement)) {\n\t\t\treturn\n\t\t}\n\t\tconst { body, refresh, toolbarError } = view\n\t\tcontentGeneration += 1\n\t\tconst generation = contentGeneration\n\t\tconst isCurrent = () => generation === contentGeneration\n\n\t\t// Only before the first answer; after that the button carries it.\n\t\tif (!view.loaded) {\n\t\t\tbody.className = 'epnc-pad-doc__text'\n\t\t\tbody.textContent = contentLoadingText\n\t\t}\n\t\tif (toolbarError instanceof HTMLElement) {\n\t\t\ttoolbarError.hidden = true\n\t\t}\n\t\tif (refresh instanceof HTMLButtonElement) {\n\t\t\trefresh.disabled = true\n\t\t\trefresh.textContent = contentRefreshingText\n\t\t}\n\n\t\ttry {\n\t\t\tif (contentUrl === '') {\n\t\t\t\t// Retrying cannot help, so the message says what is actually\n\t\t\t\t// wrong instead of inviting another press.\n\t\t\t\trenderContentError(view, contentUrl, contentNoUrlText, false)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst content = await loadPadContent(contentUrl)\n\t\t\tif (!isCurrent()) return\n\t\t\tview.loaded = true\n\t\t\tif (content.isEmpty) {\n\t\t\t\t// Left blank this would read as a failure nobody reported.\n\t\t\t\tbody.className = 'epnc-pad-doc__text'\n\t\t\t\tbody.textContent = contentEmptyText\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbody.className = 'epnc-pad-doc__text epnc-pad-doc__text--html'\n\t\t\tbody.innerHTML = content.html\n\t\t} catch (error) {\n\t\t\tif (!isCurrent()) return\n\t\t\trenderContentError(view, contentUrl, messageOf(error, contentErrorText))\n\t\t} finally {\n\t\t\tif (isCurrent() && refresh instanceof HTMLButtonElement) {\n\t\t\t\trefresh.disabled = false\n\t\t\t\trefresh.textContent = contentRefreshText\n\t\t\t}\n\t\t}\n\t}\n\n\tconst renderContentError = (view, contentUrl, message, canRetry = true) => {\n\t\tconst { body, toolbarError } = view\n\t\t// Something is on screen: keep it, and say the attempt failed.\n\t\tif (view.loaded && toolbarError instanceof HTMLElement) {\n\t\t\ttoolbarError.textContent = message || contentErrorText\n\t\t\ttoolbarError.hidden = false\n\t\t\treturn\n\t\t}\n\t\tbody.className = 'epnc-pad-doc__text'\n\t\tbody.textContent = ''\n\n\t\tconst text = document.createElement('p')\n\t\ttext.textContent = message || contentErrorText\n\n\t\tbody.appendChild(text)\n\t\tif (canRetry) {\n\t\t\tbody.appendChild(buildButton(contentRetryText, () => { void loadContent(view, contentUrl) }, 'button primary'))\n\t\t}\n\t}\n\n\tconst showIframe = (url) => {\n\t\tif (!(iframe instanceof HTMLIFrameElement)) {\n\t\t\tshowError('Embed iframe is not available.')\n\t\t\treturn\n\t\t}\n\t\t// The loading state the open started from stays up until the pad has loaded.\n\t\tconst revealIframe = () => {\n\t\t\tiframe.removeEventListener('load', revealIframe)\n\t\t\twindow.setTimeout(() => {\n\t\t\t\tif (loadingNode instanceof HTMLElement) {\n\t\t\t\t\tloadingNode.hidden = true\n\t\t\t\t}\n\t\t\t\tiframe.hidden = false\n\t\t\t}, IFRAME_REVEAL_DELAY_MS)\n\t\t}\n\t\tiframe.addEventListener('load', revealIframe, { once: true })\n\t\tiframe.src = url\n\t}\n\n\tconst postHostMessage = (source, origin, type, payload = {}) => {\n\t\t// Replies are only sent from the already origin-validated message handler.\n\t\tif (!source || typeof source.postMessage !== 'function') {\n\t\t\treturn\n\t\t}\n\t\tsource.postMessage(Object.assign({\n\t\t\ttype,\n\t\t\tfileId,\n\t\t}, payload), origin)\n\t}\n\n\tconst isAllowedMessageOrigin = (origin) => {\n\t\tif (!origin || origin === 'null') {\n\t\t\treturn false\n\t\t}\n\t\tif (origin === window.location.origin) {\n\t\t\treturn true\n\t\t}\n\t\treturn trustedOrigins.includes(origin)\n\t}\n\n\tconst installHostMessageHandler = () => {\n\t\tif (messageHandler) {\n\t\t\treturn\n\t\t}\n\t\tmessageHandler = (event) => {\n\t\t\tconst origin = String(event.origin || '')\n\t\t\tif (!isAllowedMessageOrigin(origin)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst payload = event.data\n\t\t\tconst type = typeof payload === 'string'\n\t\t\t\t? payload\n\t\t\t\t: (payload && typeof payload === 'object' && typeof payload.type === 'string' ? payload.type : '')\n\t\t\tif (!type) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (type === 'epnc:host-visible') {\n\t\t\t\tpadSync.start()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (type === 'epnc:host-hidden') {\n\t\t\t\tpadSync.fireAndForget(true, true)\n\t\t\t\tpadSync.stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (type === 'epnc:host-before-close' || type === 'epnc:host-sync-now') {\n\t\t\t\tconst keepalive = type !== 'epnc:host-sync-now'\n\t\t\t\tconst reason = type === 'epnc:host-before-close' ? 'before-close' : 'sync-now'\n\t\t\t\tpostHostMessage(event.source, origin, 'epnc:sync-flush-started', {\n\t\t\t\t\treason,\n\t\t\t\t})\n\t\t\t\tvoid padSync.sync(true, keepalive)\n\t\t\t\t\t.then((result) => {\n\t\t\t\t\t\tpostHostMessage(event.source, origin, 'epnc:sync-flush-finished', {\n\t\t\t\t\t\t\treason,\n\t\t\t\t\t\t\tresult: result && typeof result === 'object' ? result : {},\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\tpostHostMessage(event.source, origin, 'epnc:sync-flush-failed', {\n\t\t\t\t\t\t\treason,\n\t\t\t\t\t\t\tmessage: error instanceof Error ? error.message : 'Sync failed.',\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\tif (keepalive) {\n\t\t\t\t\tpadSync.stop()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twindow.addEventListener('message', messageHandler)\n\t}\n\n\tconst openPad = async () => {\n\t\tconst body = new URLSearchParams()\n\t\tbody.set('fileId', String(fileId))\n\t\tconst data = await fetchJson(openByIdUrl, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n\t\t\t\trequesttoken: requestToken(),\n\t\t\t},\n\t\t\tbody: body.toString(),\n\t\t})\n\t\treturn assertOpenPayload(data)\n\t}\n\n\tconst initializePad = async () => {\n\t\tconst url = initializeByIdUrlTemplate.replace('__FILE_ID__', encodeURIComponent(String(fileId)))\n\t\t// A write: see fetchJsonWithTimeout() for why it gets no timeout.\n\t\tconst data = await fetchJson(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\trequesttoken: requestToken(),\n\t\t\t},\n\t\t}, { timeoutMs: null })\n\t\tif (data && data.status === 'migrated_from_legacy') {\n\t\t\t// Mirror the backend audit-log entry to the browser console; no\n\t\t\t// toast surface is wired up in this app yet.\n\t\t\tconsole.info('Legacy Ownpad .pad migrated to managed format on first open.')\n\t\t}\n\t}\n\n\tconst hideAllPanels = () => {\n\t\tif (loadingNode instanceof HTMLElement) loadingNode.hidden = true\n\t\tif (errorNode instanceof HTMLElement) errorNode.hidden = true\n\t\tif (recoveryNode instanceof HTMLElement) recoveryNode.hidden = true\n\t\tif (iframe instanceof HTMLIFrameElement) {\n\t\t\tiframe.hidden = true\n\t\t\tiframe.removeAttribute('src')\n\t\t}\n\t}\n\n\tconst showRecoveryChecking = () => {\n\t\tif (!(recoveryNode instanceof HTMLElement)) return\n\t\thideAllPanels()\n\t\trecoveryNode.hidden = false\n\t\tif (recoveryMessageNode instanceof HTMLElement) recoveryMessageNode.textContent = recoveryCheckingText\n\t\tif (recoveryBodyNode instanceof HTMLElement) recoveryBodyNode.textContent = ''\n\t\tif (recoveryActionsNode instanceof HTMLElement) recoveryActionsNode.replaceChildren()\n\t}\n\n\tconst showRecoveryWithOriginal = (originalEmbedUrl, errorMessage) => {\n\t\tif (!(recoveryNode instanceof HTMLElement)) return\n\t\thideAllPanels()\n\t\trecoveryNode.hidden = false\n\t\tif (recoveryMessageNode instanceof HTMLElement) recoveryMessageNode.textContent = errorMessage\n\t\tif (recoveryBodyNode instanceof HTMLElement) recoveryBodyNode.textContent = recoveryCopyBodyText\n\t\tif (recoveryActionsNode instanceof HTMLElement) {\n\t\t\tconst openLink = document.createElement('a')\n\t\t\topenLink.className = PRIMARY_BUTTON_CLASS\n\t\t\t// Stay in embed mode: load the original's embed page in the same\n\t\t\t// frame so a host iframe doesn't need to deal with a new tab.\n\t\t\topenLink.href = originalEmbedUrl\n\t\t\topenLink.textContent = recoveryOpenOriginalText\n\t\t\trecoveryActionsNode.replaceChildren(\n\t\t\t\topenLink,\n\t\t\t\tbuildButton(recoveryCreateNewText, () => { void triggerRecovery() }),\n\t\t\t)\n\t\t}\n\t}\n\n\t/** $body: what the card says under the message; the orphan's by default. */\n\tconst showRecoveryWithoutOriginal = (errorMessage, body = recoveryOrphanBodyText) => {\n\t\tif (!(recoveryNode instanceof HTMLElement)) return\n\t\thideAllPanels()\n\t\trecoveryNode.hidden = false\n\t\tif (recoveryMessageNode instanceof HTMLElement) recoveryMessageNode.textContent = errorMessage\n\t\tif (recoveryBodyNode instanceof HTMLElement) recoveryBodyNode.textContent = body\n\t\tif (recoveryActionsNode instanceof HTMLElement) {\n\t\t\trecoveryActionsNode.replaceChildren(\n\t\t\t\tbuildButton(recoveryCreateNewText, () => { void triggerRecovery() }, PRIMARY_BUTTON_CLASS),\n\t\t\t)\n\t\t}\n\t}\n\n\tconst setRecoveryActionsBusy = (busy) => {\n\t\tif (!(recoveryActionsNode instanceof HTMLElement)) return\n\t\tconst buttons = recoveryActionsNode.querySelectorAll('button')\n\t\tbuttons.forEach((node) => {\n\t\t\tnode.disabled = busy\n\t\t\tif (busy) {\n\t\t\t\tnode.dataset.originalLabel = node.dataset.originalLabel || node.textContent || ''\n\t\t\t\tnode.textContent = recoveryCreatingText\n\t\t\t} else if (node.dataset.originalLabel) {\n\t\t\t\tnode.textContent = node.dataset.originalLabel\n\t\t\t\tdelete node.dataset.originalLabel\n\t\t\t}\n\t\t})\n\t}\n\n\tconst triggerRecovery = async () => {\n\t\tif (recoverUrlTemplate === '') {\n\t\t\tshowError('Recovery is not available in this embed.')\n\t\t\treturn\n\t\t}\n\t\tsetRecoveryActionsBusy(true)\n\t\tconst url = recoverUrlTemplate.replace('__FILE_ID__', encodeURIComponent(String(fileId)))\n\t\ttry {\n\t\t\t// A write, like initializePad().\n\t\t\tawait fetchJson(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { requesttoken: requestToken() },\n\t\t\t}, { timeoutMs: null })\n\t\t\t// Open again now that the binding exists.\n\t\t\tvoid run(true)\n\t\t} catch (error) {\n\t\t\t// No answer: the pad may be set up by now, and another recovery\n\t\t\t// would meet it. Opening tells, and is safe to repeat.\n\t\t\tif (isUnanswered(error)) {\n\t\t\t\tvoid run(true)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsetRecoveryActionsBusy(false)\n\t\t\tif (recoveryMessageNode instanceof HTMLElement) {\n\t\t\t\trecoveryMessageNode.textContent = messageOf(error, 'Recovery failed.')\n\t\t\t}\n\t\t\t// The clicked button lost the focus while it was disabled.\n\t\t\thandFocusToCard(recoveryActionsNode, recoveryMessageNode)\n\t\t}\n\t}\n\n\t/** The original's embed page, or '' when there is none or no answer. */\n\tconst findOriginalEmbedUrl = async () => {\n\t\tif (findOriginalUrlTemplate === '') {\n\t\t\treturn ''\n\t\t}\n\t\tconst lookupUrl = findOriginalUrlTemplate.replace('__FILE_ID__', encodeURIComponent(String(fileId)))\n\t\ttry {\n\t\t\tconst hint = await fetchJson(lookupUrl, { method: 'GET' })\n\t\t\tif (hint && hint.found === true && typeof hint.embed_url === 'string') {\n\t\t\t\treturn hint.embed_url\n\t\t\t}\n\t\t} catch {\n\t\t\t// Silent: the card then offers a new pad only.\n\t\t}\n\t\treturn ''\n\t}\n\n\tconst enterRecoveryFlow = async (initialError, afterClick, isCurrent) => {\n\t\tconst errorMessage = messageOf(initialError, 'Pad open failed.')\n\t\tshowRecoveryChecking()\n\t\tconst originalEmbedUrl = await findOriginalEmbedUrl()\n\t\tif (!isCurrent()) {\n\t\t\treturn\n\t\t}\n\t\tif (originalEmbedUrl !== '') {\n\t\t\tshowRecoveryWithOriginal(originalEmbedUrl, errorMessage)\n\t\t} else {\n\t\t\tshowRecoveryWithoutOriginal(errorMessage)\n\t\t}\n\t\tif (afterClick) {\n\t\t\thandFocusToCard(recoveryActionsNode, recoveryMessageNode)\n\t\t}\n\t}\n\n\t// So an open that answers late cannot undo a newer one.\n\tlet openGeneration = 0\n\n\t/** $afterClick: a second try or a recovery started it; see handFocusTo(). */\n\tconst run = async (afterClick = false) => {\n\t\topenGeneration += 1\n\t\tconst generation = openGeneration\n\t\tconst isCurrent = () => generation === openGeneration\n\t\tshowLoading()\n\t\tif (!Number.isFinite(fileId) || fileId <= 0 || openByIdUrl === '' || initializeByIdUrlTemplate === '') {\n\t\t\tshowError('Embed configuration is incomplete.')\n\t\t\treturn\n\t\t}\n\t\tif (requestToken() === '') {\n\t\t\tshowError('CSRF request token is missing.')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tconst data = await openWithFrontmatterRecovery({ open: openPad, initialize: initializePad, stillWanted: isCurrent })\n\t\t\tif (data === null || !isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { syncUrl, intervalMs } = syncSettingsFrom(data)\n\t\t\tpadSync.configure({ syncUrl, intervalMs })\n\t\t\tpadSync.installLifecycleHandlers()\n\t\t\tinstallHostMessageHandler()\n\t\t\t// No syncing for a viewer: it writes the pad back into the .pad\n\t\t\t// file, which is exactly what a read-only share may not do.\n\t\t\tif (syncUrl !== '') {\n\t\t\t\tpadSync.start()\n\t\t\t}\n\t\t\tconst contentUrl = contentUrlFrom(data)\n\t\t\tconst { isContentView, externalUrl } = contentViewFrom(data)\n\t\t\tif (isContentView) {\n\t\t\t\tconst view = showPadContentView(externalUrl)\n\t\t\t\tif (view !== null) {\n\t\t\t\t\tview.refresh.addEventListener('click', () => { void loadContent(view, contentUrl) })\n\t\t\t\t}\n\t\t\t\tvoid loadContent(view, contentUrl)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshowIframe(padUrlFrom(data))\n\t\t} catch (error) {\n\t\t\tif (!isCurrent()) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (isMissingBindingError(error)) {\n\t\t\t\tvoid enterRecoveryFlow(error, afterClick, isCurrent)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (isPadMissingError(error)) {\n\t\t\t\t// The message says what happened; the file is the original.\n\t\t\t\tshowRecoveryWithoutOriginal(messageOf(error, 'Pad open failed.'), '')\n\t\t\t\tif (afterClick) {\n\t\t\t\t\thandFocusToCard(recoveryActionsNode, recoveryMessageNode)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshowError(messageOf(error, 'Pad open failed.'), isRetryableOpenError(error), afterClick)\n\t\t}\n\t}\n\n\tvoid run()\n})()\n"],"names":["BUTTON_CLASS","PRIMARY_BUTTON_CLASS","root","fileId","openByIdUrl","initializeByIdUrlTemplate","recoverUrlTemplate","findOriginalUrlTemplate","templateRequestToken","trustedOrigins","value","loadingNode","errorNode","errorMessageNode","errorActionsNode","recoveryNode","recoveryMessageNode","recoveryBodyNode","recoveryActionsNode","iframe","contentEmptyText","contentLoadingText","contentErrorText","contentNoUrlText","contentRetryText","contentRefreshText","contentRefreshingText","externalLinkText","recoveryCheckingText","recoveryCopyBodyText","recoveryOrphanBodyText","recoveryOpenOriginalText","recoveryCreateNewText","recoveryCreatingText","unansweredText","messageHandler","requestToken","ocRequestToken","padSync","createPadSync","messageOf","error","fallback","requestErrorMessage","handFocusToCard","actionsNode","messageNode","handFocusTo","buildButton","label","onClick","className","button","showError","message","canRetry","afterClick","hideAllPanels","run","showLoading","showPadContentView","url","surface","inner","toolbar","toolbarError","refresh","link","body","contentGeneration","loadContent","view","contentUrl","generation","isCurrent","renderContentError","content","loadPadContent","text","showIframe","revealIframe","postHostMessage","source","origin","type","payload","isAllowedMessageOrigin","installHostMessageHandler","event","keepalive","reason","result","openPad","data","fetchJson","assertOpenPayload","initializePad","showRecoveryChecking","showRecoveryWithOriginal","originalEmbedUrl","errorMessage","openLink","triggerRecovery","showRecoveryWithoutOriginal","setRecoveryActionsBusy","busy","node","isUnanswered","findOriginalEmbedUrl","lookupUrl","hint","enterRecoveryFlow","initialError","openGeneration","openWithFrontmatterRecovery","syncUrl","intervalMs","syncSettingsFrom","contentUrlFrom","isContentView","externalUrl","contentViewFrom","padUrlFrom","isMissingBindingError","isPadMissingError","isRetryableOpenError"],"mappings":"gOAWC,UAAY,CAEZ,MAAMA,EAAe,8BACfC,EAAuBD,EAAe,wCAEtCE,EAAO,SAAS,eAAe,0BAA0B,EAC/D,GAAI,EAAEA,aAAgB,aACrB,OAGD,MAAMC,EAAS,OAAOD,EAAK,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8D,EAA4B/D,EAAUC,EAAO,kBAAkB,EAAG,EAAE,EAChEe,GACHZ,EAAgB1B,EAAqBF,CAAmB,EAEzD,MACD,CACAqC,EAAUb,EAAUC,EAAO,kBAAkB,EAAGoF,GAAqBpF,CAAK,EAAGe,CAAU,CACxF,CACD,EAEKE,EAAG,CACT,GAAC"} \ No newline at end of file diff --git a/js/etherpad_nextcloud-viewer-init.mjs b/js/etherpad_nextcloud-viewer-init.mjs index 27ba6b80..c006410f 100644 --- a/js/etherpad_nextcloud-viewer-init.mjs +++ b/js/etherpad_nextcloud-viewer-init.mjs @@ -1,2 +1,2 @@ -import{b as p,f,o as v,A as u,t as o,a as R,r as k,M as U,V as E}from"./fetch-helpers-BUxbvlK6.chunk.mjs";import{l as T,o as L,s as A,c as x,a as M,p as q,b as G,i as _,e as N,h as j,d as z}from"./pad-open-flow-By_FzSKk.chunk.mjs";import{p as H,i as m,a as $}from"./urls-Pchbg185.chunk.mjs";function V(t){if(W(t),window._oca_viewer_handlers??(window._oca_viewer_handlers=new Map),window._oca_viewer_handlers.has(t.id)){console.warn(`Handler with id ${t.id} is already registered.`);return}window._oca_viewer_handlers.set(t.id,t)}function W(t){const{id:e,mimes:n,mimesAliases:i,component:a}=t;if(!e||e.trim()===""||typeof e!="string")throw new Error("The handler does not have a valid id");if((!n||!Array.isArray(n))&&!i)throw new Error("Handler needs a valid mime array or mimesAliases");if(!a||typeof a!="object"&&typeof a!="function")throw new Error("The handler does not have a valid component")}const d=new Map,D=50,B=300*1e3,K=async(t,{bypassCache:e=!1}={})=>{const n="path:"+String(t),i=e?null:Q(n);if(i!==null)return i;const a=p("/apps/"+u+"/api/v1/pads/resolve")+"?file="+encodeURIComponent(t),c=I(a,{method:"GET",headers:{Accept:"application/json"}},"Pad resolve by path failed.").catch(s=>{throw d.delete(n),s});return X(n,c),c},Y=async t=>{const e=p("/apps/"+u+"/api/v1/pads/find-original/"+encodeURIComponent(String(t)));return I(e,{method:"GET",headers:{Accept:"application/json"}},"Lookup failed.")},J=async(t,e="")=>{const n=p("/apps/"+u+"/api/v1/pads/recover-from-snapshot/"+encodeURIComponent(String(t))),i=await f(n,{method:"POST",headers:{Accept:"application/json",requesttoken:v()}},{fallbackMessage:"Recovery failed.",timeoutMs:null});return typeof e=="string"&&e!==""&&d.delete("path:"+e),i},Q=t=>{const e=d.get(t);return e?Date.now()-e.createdAt>B?(d.delete(t),null):e.request:null},X=(t,e)=>{if(!d.has(t)&&d.size>=D){const n=d.keys().next().value;n!==void 0&&d.delete(n)}d.set(t,{createdAt:Date.now(),request:e})},I=async(t,e,n)=>f(t,e,{fallbackMessage:n}),C=t=>String(t||"").replace(/&/g,"&").replace(/"/g,""").replace(//g,">"),Z=["http:","https:"],tt=t=>{try{const e=new URL(String(t||""));return Z.includes(e.protocol)&&e.username===""&&e.password===""}catch{return!1}},et="default-src 'none'; frame-src http: https:; style-src 'unsafe-inline'",nt=t=>{const e=tt(t)?C(t):"";return''},w=(t,e)=>k(t,o("Nextcloud did not answer. Check your connection and try again."),e),rt={name:"EtherpadNextcloudViewer",props:{filename:{type:String,required:!1,default:""},basename:{type:String,required:!1,default:""},source:{type:String,required:!1,default:""},fileid:{type:[String,Number],required:!1,default:null},fileId:{type:[String,Number],required:!1,default:null},fileInfo:{type:Object,required:!1,default:null}},data(){return{iframeSrc:"",isLoading:!0,loadError:"",canRecover:!1,canRetryOpen:!1,maybeStaleFileId:!1,recoveryFileId:null,recoveryPath:"",isRecovering:!1,isCheckingOriginal:!1,originalPad:null,externalOpenUrl:"",contentMode:"",contentUrl:"",contentState:"idle",contentError:"",content:{html:"",isEmpty:!1},contentLoaded:!1,contentGeneration:0,resolveGeneration:0}},computed:{sourcePath(){const t=typeof this.source=="string"?this.source.trim():"";return t&&$(t)||""},filePath(){const t=r=>!r||r==="/"?"/":r.startsWith("/")?r:"/"+r,e=(r,l)=>{if(!l)return"";if(l.startsWith("/"))return l;const y=t(r);return y==="/"?"/"+l:y+"/"+l};if(m(this.sourcePath))return this.sourcePath;const n=this.fileInfo&&typeof this.fileInfo=="object"?this.fileInfo:null,i=n&&typeof n.path=="string"?n.path:"";if(m(i))return i.startsWith("/")?i:"/"+i;const a=String(this.filename||this.basename||n&&(n.name||n.basename)||"");if(!a)return"";const c=n&&typeof n.dirname=="string"?n.dirname:"";if(c){const r=e(c,a);if(m(r))return r}const s=new URLSearchParams(window.location.search||"").get("dir")||"/",h=e(s,a);return m(h)?h:"/"+a},openKey(){return`${this.resolvedFileId===null?"":this.resolvedFileId}::${this.filePath}`},resolvedFileId(){const t=[this.fileid,this.fileId,this.fileInfo&&(this.fileInfo.fileid||this.fileInfo.fileId||this.fileInfo.id)];for(const e of t){const n=Number(e);if(Number.isFinite(n)&&n>0)return n}return null}},watch:{openKey:{immediate:!0,handler(){this.resolveOpenUrl()}}},methods:{async fetchOpenPayload(t,e={}){return z(await f(t,Object.assign({method:"GET"},e)))},async initializeMissingFrontmatter(){const t={Accept:"application/json",requesttoken:v()},e={timeoutMs:null,fallbackMessage:"Pad initialization failed."},n=s=>{s&&s.status==="migrated_from_legacy"&&console.info("Legacy Ownpad .pad migrated to managed format on first open.")};if(this.resolvedFileId!==null){const s=p("/apps/"+u+"/api/v1/pads/initialize-by-id/"+encodeURIComponent(String(this.resolvedFileId))),h=await f(s,{method:"POST",headers:t},e);return n(h),h}if(!this.filePath)throw new Error("Pad initialization failed: missing file path.");const i=new URLSearchParams;i.set("file",this.filePath);const a=p("/apps/"+u+"/api/v1/pads/initialize"),c=await f(a,{method:"POST",headers:Object.assign({},t,{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"}),body:i.toString()},e);return n(c),c},async resolveRecoveryFileId(t){try{const e=await K(t,{bypassCache:!0}),n=Number(e&&e.file_id);return Number.isFinite(n)&&n>0?n:null}catch{return null}},markLoaded(){this.$emit("update:loaded",!0)},handFocusToErrorCard(){this.$nextTick(()=>{const t=this.$refs.errorCard;t instanceof HTMLElement&&j(t,t.querySelector(".epnc-native-error-message"))})},padSync(){return this._padSync||(this._padSync=N({requestToken:()=>v()})),this._padSync},teardownSync(){this._padSync&&(this._padSync.fireAndForget(!0,!0),this._padSync.stop(),this._padSync.removeLifecycleHandlers())},async resolveOpenUrl(t=!1){const e=++this.resolveGeneration,n=()=>e===this.resolveGeneration;this._openAbort?.abort();const i=typeof AbortController=="function"?new AbortController:null;if(this._openAbort=i,this.isLoading=!0,this.loadError="",this.canRecover=!1,this.canRetryOpen=!1,this.maybeStaleFileId=!1,this.recoveryFileId=null,this.recoveryPath="",this.isCheckingOriginal=!1,this.originalPad=null,this.iframeSrc="",this.externalOpenUrl="",this.contentMode="",this.contentUrl="",this.contentState="idle",this.contentError="",this.content={html:"",isEmpty:!1},this.contentLoaded=!1,this._contentAbort?.abort(),this._padSync&&(this._padSync.stop(),this._padSync.configure({syncUrl:""})),!this.filePath){if(!n())return;this.loadError="No .pad file selected.",this.isLoading=!1;return}const a=this.filePath,c=H(),s=(()=>{if(!c)return"";const r=new URL(p("/apps/"+u+"/api/v1/public/open/"+encodeURIComponent(c)),window.location.origin);return this.resolvedFileId!==null?r.searchParams.set("fileId",String(this.resolvedFileId)):r.searchParams.set("file",a),r.toString()})(),h={"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",requesttoken:v()};try{const r=await L({open:async()=>{const g=i?i.signal:void 0;if(s)return await this.fetchOpenPayload(s,{signal:g});if(this.resolvedFileId!==null){const S=new URLSearchParams;return S.set("fileId",String(this.resolvedFileId)),await this.fetchOpenPayload(p("/apps/"+u+"/api/v1/pads/open-by-id"),{method:"POST",headers:h,body:S.toString(),signal:g})}const b=new URLSearchParams;return b.set("file",a),await this.fetchOpenPayload(p("/apps/"+u+"/api/v1/pads/open"),{method:"POST",headers:h,body:b.toString(),signal:g})},initialize:()=>this.initializeMissingFrontmatter(),stillWanted:n});if(r===null||!n())return;const{syncUrl:l,intervalMs:y}=A(r);this.padSync().configure({syncUrl:l,intervalMs:y}),this.padSync().installLifecycleHandlers(),l&&this.padSync().start();const P=x(r),{isContentView:F,externalUrl:O}=M(r);if(F){this.externalOpenUrl=O,this.contentUrl=P,this.contentMode="content",this.markLoaded(),this.loadContent();return}this.iframeSrc=q(r),this.markLoaded()}catch(r){if(!n())return;this.loadError=w(r,"Could not load pad."),this.maybeStaleFileId=this.resolvedFileId!==null&&!!r&&r.status===404&&!r.code,this.canRetryOpen=G(r);let l=this.resolvedFileId;if(this.recoveryPath=a,l===null&&!s&&_(r)&&(l=await this.resolveRecoveryFileId(a),!n()))return;this.recoveryFileId=l,this.canRecover=_(r)&&l!==null&&!s,this.canRecover?this.fetchOriginalPadHint(n,t):t&&this.handFocusToErrorCard(),this.markLoaded()}finally{if(!n())return;this.isLoading=!1}},async fetchOriginalPadHint(t,e=!1){if(this.recoveryFileId!==null){this.isCheckingOriginal=!0;try{const n=await Y(this.recoveryFileId);if(!t())return;n&&n.found===!0&&typeof n.viewer_url=="string"&&n.viewer_url!==""&&(this.originalPad={viewerUrl:n.viewer_url,path:typeof n.path=="string"?n.path:""})}catch{}finally{t()&&(this.isCheckingOriginal=!1,e&&this.handFocusToErrorCard())}}},async recoverFromSnapshot(){if(!(!this.canRecover||this.isRecovering||this.recoveryFileId===null)){this.isRecovering=!0;try{await J(this.recoveryFileId,this.recoveryPath),this.loadError="",this.canRecover=!1,await this.resolveOpenUrl(!0)}catch(t){if(R(t)){await this.resolveOpenUrl(!0);return}this.isRecovering=!1,this.loadError=w(t,"Could not load pad."),this.handFocusToErrorCard()}finally{this.isRecovering=!1}}},async loadContent(){const t=this.resolveGeneration;this.contentGeneration+=1;const e=this.contentGeneration,n=()=>e===this.contentGeneration&&t===this.resolveGeneration;if(this.contentUrl===""){this.contentState="error",this.contentError=o("The server did not say where to load this pad from.");return}this._contentAbort?.abort();const i=typeof AbortController=="function"?new AbortController:null;this._contentAbort=i,this.contentState="loading",this.contentError="";try{const a=await T(this.contentUrl,{signal:i?.signal});if(!n())return;this.content=a,this.contentLoaded=!0,this.contentState="ready"}catch(a){if(!n()||a&&a.name==="AbortError")return;this.contentState="error",this.contentError=w(a,o("Could not load the pad content."))}},renderContentView(t,e){const n=Array.isArray(e.actions)?e.actions:[],i=this.contentState==="loading";return t("div",{class:"epnc-pad-doc"},[t("div",{class:"epnc-pad-doc__inner"},[t("div",{class:"epnc-pad-doc__toolbar"},[this.contentState==="error"&&this.contentLoaded?t("span",{class:"epnc-pad-doc__toolbar-error"},this.contentError||o("Could not load the pad content.")):null,t("button",{class:"button epnc-pad-doc__refresh",attrs:{type:"button",disabled:i},on:{click:()=>{this.loadContent()}}},i?o("Refreshing..."):o("Refresh")),...n]),this.renderContentBody(t)])])},renderContentBody(t){return this.contentLoaded&&this.contentState!=="ready"?this.renderContentText(t):this.contentState==="error"?t("div",{class:"epnc-pad-doc__text epnc-pad-doc__status"},[t("div",{},this.contentError||o("Could not load the pad content.")),t("button",{class:"button primary",attrs:{type:"button"},on:{click:()=>{this.loadContent()}}},o("Try again"))]):this.contentState!=="ready"?t("div",{class:"epnc-pad-doc__text epnc-pad-doc__status"},o("Loading pad content...")):this.renderContentText(t)},renderContentText(t){return this.content.isEmpty?t("div",{class:"epnc-pad-doc__text epnc-pad-doc__status"},o("This pad is still empty.")):t("div",{class:"epnc-pad-doc__text epnc-pad-doc__text--html",domProps:{innerHTML:this.content.html}})}},beforeDestroy(){this.resolveGeneration+=1,this._openAbort?.abort(),this._contentAbort?.abort(),this.teardownSync()},beforeUnmount(){this.resolveGeneration+=1,this._openAbort?.abort(),this._contentAbort?.abort(),this.teardownSync()},render(t){if(this.loadError){const e=[t("div",{class:"epnc-native-error-title"},o("Could not open pad")),t("div",{class:"epnc-native-error-message",attrs:{role:"alert"}},this.loadError)];return this.maybeStaleFileId&&e.push(t("div",{class:"epnc-native-error-message"},o("This file may have been moved or replaced since the list was loaded. Reload the page and open it again."))),this.canRetryOpen&&e.push(t("button",{class:"button primary epnc-native-error-action",attrs:{type:"button"},on:{click:()=>{this.resolveOpenUrl(!0)}}},o("Try again"))),this.canRecover&&(this.isCheckingOriginal?e.push(t("div",{class:"epnc-native-error-message"},o("Checking for the original pad..."))):this.originalPad?e.push(t("div",{class:"epnc-native-error-message"},o("This file looks like a copy of an existing .pad file in your account. Open the original to keep editing the linked pad, or create a new pad to fork the content stored in this file.")),t("a",{class:"button primary epnc-native-error-action",attrs:{href:this.originalPad.viewerUrl}},o("Open the original .pad file")),t("button",{class:"button epnc-native-error-action",attrs:{type:"button",disabled:this.isRecovering},on:{click:()=>{this.recoverFromSnapshot()}}},this.isRecovering?o("Creating new pad..."):o("Create new pad from this file"))):e.push(t("div",{class:"epnc-native-error-message"},o("We couldn't find a matching pad in this Nextcloud. You can create a new pad from the text stored in this file; from then on, opening this file will load the new pad.")),t("button",{class:"button primary epnc-native-error-action",attrs:{type:"button",disabled:this.isRecovering},on:{click:()=>{this.recoverFromSnapshot()}}},this.isRecovering?o("Creating new pad..."):o("Create new pad from this file")))),t("div",{class:"epnc-native-status epnc-native-status--error"},[t("div",{class:"epnc-native-error-card",ref:"errorCard"},e)])}return this.contentMode==="content"?this.renderContentView(t,this.externalOpenUrl===""?{}:{actions:[t("a",{class:"button epnc-pad-doc__link",attrs:{href:this.externalOpenUrl,target:"_blank",rel:"noopener noreferrer"}},o("Open original pad"))]}):this.isLoading||!this.iframeSrc?t("div",{class:"epnc-native-status"},"Loading pad..."):t("div",{class:"epnc-native-shell"},[t("iframe",{attrs:{srcdoc:nt(this.iframeSrc),title:"Etherpad"},on:{load:()=>this.markLoaded(),error:()=>this.markLoaded()},class:"epnc-native-iframe"})])}};V({id:E,mimes:[U],component:rt}); +import{b as p,f as y,o as v,A as u,t as a,a as k,r as O,M as L,V as U}from"./fetch-helpers-BUxbvlK6.chunk.mjs";import{l as E,o as T,s as A,c as x,a as M,p as q,d as G,i as N,b as _,f as j,h as z,e as H}from"./pad-open-flow-_qELVjOV.chunk.mjs";import{p as $,i as m,a as V}from"./urls-Pchbg185.chunk.mjs";function W(t){if(D(t),window._oca_viewer_handlers??(window._oca_viewer_handlers=new Map),window._oca_viewer_handlers.has(t.id)){console.warn(`Handler with id ${t.id} is already registered.`);return}window._oca_viewer_handlers.set(t.id,t)}function D(t){const{id:e,mimes:n,mimesAliases:i,component:o}=t;if(!e||e.trim()===""||typeof e!="string")throw new Error("The handler does not have a valid id");if((!n||!Array.isArray(n))&&!i)throw new Error("Handler needs a valid mime array or mimesAliases");if(!o||typeof o!="object"&&typeof o!="function")throw new Error("The handler does not have a valid component")}const d=new Map,B=50,K=300*1e3,Y=async(t,{bypassCache:e=!1}={})=>{const n="path:"+String(t),i=e?null:X(n);if(i!==null)return i;const o=p("/apps/"+u+"/api/v1/pads/resolve")+"?file="+encodeURIComponent(t),l=I(o,{method:"GET",headers:{Accept:"application/json"}},"Pad resolve by path failed.").catch(s=>{throw d.delete(n),s});return Z(n,l),l},J=async t=>{const e=p("/apps/"+u+"/api/v1/pads/find-original/"+encodeURIComponent(String(t)));return I(e,{method:"GET",headers:{Accept:"application/json"}},"Lookup failed.")},Q=async(t,e="")=>{const n=p("/apps/"+u+"/api/v1/pads/recover-from-snapshot/"+encodeURIComponent(String(t))),i=await y(n,{method:"POST",headers:{Accept:"application/json",requesttoken:v()}},{fallbackMessage:"Recovery failed.",timeoutMs:null});return typeof e=="string"&&e!==""&&d.delete("path:"+e),i},X=t=>{const e=d.get(t);return e?Date.now()-e.createdAt>K?(d.delete(t),null):e.request:null},Z=(t,e)=>{if(!d.has(t)&&d.size>=B){const n=d.keys().next().value;n!==void 0&&d.delete(n)}d.set(t,{createdAt:Date.now(),request:e})},I=async(t,e,n)=>y(t,e,{fallbackMessage:n}),C=t=>String(t||"").replace(/&/g,"&").replace(/"/g,""").replace(//g,">"),tt=["http:","https:"],et=t=>{try{const e=new URL(String(t||""));return tt.includes(e.protocol)&&e.username===""&&e.password===""}catch{return!1}},nt="default-src 'none'; frame-src http: https:; style-src 'unsafe-inline'",rt=t=>{const e=et(t)?C(t):"";return''},w=(t,e)=>O(t,a("Nextcloud did not answer. Check your connection and try again."),e),it={name:"EtherpadNextcloudViewer",props:{filename:{type:String,required:!1,default:""},basename:{type:String,required:!1,default:""},source:{type:String,required:!1,default:""},fileid:{type:[String,Number],required:!1,default:null},fileId:{type:[String,Number],required:!1,default:null},fileInfo:{type:Object,required:!1,default:null}},data(){return{iframeSrc:"",isLoading:!0,loadError:"",canRecover:!1,padLost:!1,canRetryOpen:!1,maybeStaleFileId:!1,recoveryFileId:null,recoveryPath:"",isRecovering:!1,isCheckingOriginal:!1,originalPad:null,externalOpenUrl:"",contentMode:"",contentUrl:"",contentState:"idle",contentError:"",content:{html:"",isEmpty:!1},contentLoaded:!1,contentGeneration:0,resolveGeneration:0}},computed:{sourcePath(){const t=typeof this.source=="string"?this.source.trim():"";return t&&V(t)||""},filePath(){const t=r=>!r||r==="/"?"/":r.startsWith("/")?r:"/"+r,e=(r,c)=>{if(!c)return"";if(c.startsWith("/"))return c;const f=t(r);return f==="/"?"/"+c:f+"/"+c};if(m(this.sourcePath))return this.sourcePath;const n=this.fileInfo&&typeof this.fileInfo=="object"?this.fileInfo:null,i=n&&typeof n.path=="string"?n.path:"";if(m(i))return i.startsWith("/")?i:"/"+i;const o=String(this.filename||this.basename||n&&(n.name||n.basename)||"");if(!o)return"";const l=n&&typeof n.dirname=="string"?n.dirname:"";if(l){const r=e(l,o);if(m(r))return r}const s=new URLSearchParams(window.location.search||"").get("dir")||"/",h=e(s,o);return m(h)?h:"/"+o},openKey(){return`${this.resolvedFileId===null?"":this.resolvedFileId}::${this.filePath}`},resolvedFileId(){const t=[this.fileid,this.fileId,this.fileInfo&&(this.fileInfo.fileid||this.fileInfo.fileId||this.fileInfo.id)];for(const e of t){const n=Number(e);if(Number.isFinite(n)&&n>0)return n}return null}},watch:{openKey:{immediate:!0,handler(){this.resolveOpenUrl()}}},methods:{async fetchOpenPayload(t,e={}){return H(await y(t,Object.assign({method:"GET"},e)))},async initializeMissingFrontmatter(){const t={Accept:"application/json",requesttoken:v()},e={timeoutMs:null,fallbackMessage:"Pad initialization failed."},n=s=>{s&&s.status==="migrated_from_legacy"&&console.info("Legacy Ownpad .pad migrated to managed format on first open.")};if(this.resolvedFileId!==null){const s=p("/apps/"+u+"/api/v1/pads/initialize-by-id/"+encodeURIComponent(String(this.resolvedFileId))),h=await y(s,{method:"POST",headers:t},e);return n(h),h}if(!this.filePath)throw new Error("Pad initialization failed: missing file path.");const i=new URLSearchParams;i.set("file",this.filePath);const o=p("/apps/"+u+"/api/v1/pads/initialize"),l=await y(o,{method:"POST",headers:Object.assign({},t,{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"}),body:i.toString()},e);return n(l),l},async resolveRecoveryFileId(t){try{const e=await Y(t,{bypassCache:!0}),n=Number(e&&e.file_id);return Number.isFinite(n)&&n>0?n:null}catch{return null}},markLoaded(){this.$emit("update:loaded",!0)},handFocusToErrorCard(){this.$nextTick(()=>{const t=this.$refs.errorCard;t instanceof HTMLElement&&z(t,t.querySelector(".epnc-native-error-message"))})},padSync(){return this._padSync||(this._padSync=j({requestToken:()=>v()})),this._padSync},teardownSync(){this._padSync&&(this._padSync.fireAndForget(!0,!0),this._padSync.stop(),this._padSync.removeLifecycleHandlers())},async resolveOpenUrl(t=!1){const e=++this.resolveGeneration,n=()=>e===this.resolveGeneration;this._openAbort?.abort();const i=typeof AbortController=="function"?new AbortController:null;if(this._openAbort=i,this.isLoading=!0,this.loadError="",this.canRecover=!1,this.padLost=!1,this.canRetryOpen=!1,this.maybeStaleFileId=!1,this.recoveryFileId=null,this.recoveryPath="",this.isCheckingOriginal=!1,this.originalPad=null,this.iframeSrc="",this.externalOpenUrl="",this.contentMode="",this.contentUrl="",this.contentState="idle",this.contentError="",this.content={html:"",isEmpty:!1},this.contentLoaded=!1,this._contentAbort?.abort(),this._padSync&&(this._padSync.stop(),this._padSync.configure({syncUrl:""})),!this.filePath){if(!n())return;this.loadError="No .pad file selected.",this.isLoading=!1;return}const o=this.filePath,l=$(),s=(()=>{if(!l)return"";const r=new URL(p("/apps/"+u+"/api/v1/public/open/"+encodeURIComponent(l)),window.location.origin);return this.resolvedFileId!==null?r.searchParams.set("fileId",String(this.resolvedFileId)):r.searchParams.set("file",o),r.toString()})(),h={"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",requesttoken:v()};try{const r=await T({open:async()=>{const g=i?i.signal:void 0;if(s)return await this.fetchOpenPayload(s,{signal:g});if(this.resolvedFileId!==null){const S=new URLSearchParams;return S.set("fileId",String(this.resolvedFileId)),await this.fetchOpenPayload(p("/apps/"+u+"/api/v1/pads/open-by-id"),{method:"POST",headers:h,body:S.toString(),signal:g})}const b=new URLSearchParams;return b.set("file",o),await this.fetchOpenPayload(p("/apps/"+u+"/api/v1/pads/open"),{method:"POST",headers:h,body:b.toString(),signal:g})},initialize:()=>this.initializeMissingFrontmatter(),stillWanted:n});if(r===null||!n())return;const{syncUrl:c,intervalMs:f}=A(r);this.padSync().configure({syncUrl:c,intervalMs:f}),this.padSync().installLifecycleHandlers(),c&&this.padSync().start();const P=x(r),{isContentView:R,externalUrl:F}=M(r);if(R){this.externalOpenUrl=F,this.contentUrl=P,this.contentMode="content",this.markLoaded(),this.loadContent();return}this.iframeSrc=q(r),this.markLoaded()}catch(r){if(!n())return;this.loadError=w(r,"Could not load pad."),this.maybeStaleFileId=this.resolvedFileId!==null&&!!r&&r.status===404&&!r.code,this.canRetryOpen=G(r);let c=this.resolvedFileId;this.recoveryPath=o;const f=N(r)||_(r);if(c===null&&!s&&f&&(c=await this.resolveRecoveryFileId(o),!n()))return;this.recoveryFileId=c,this.padLost=_(r),this.canRecover=f&&c!==null&&!s,this.canRecover&&!this.padLost?this.fetchOriginalPadHint(n,t):t&&this.handFocusToErrorCard(),this.markLoaded()}finally{if(!n())return;this.isLoading=!1}},async fetchOriginalPadHint(t,e=!1){if(this.recoveryFileId!==null){this.isCheckingOriginal=!0;try{const n=await J(this.recoveryFileId);if(!t())return;n&&n.found===!0&&typeof n.viewer_url=="string"&&n.viewer_url!==""&&(this.originalPad={viewerUrl:n.viewer_url,path:typeof n.path=="string"?n.path:""})}catch{}finally{t()&&(this.isCheckingOriginal=!1,e&&this.handFocusToErrorCard())}}},async recoverFromSnapshot(){if(!(!this.canRecover||this.isRecovering||this.recoveryFileId===null)){this.isRecovering=!0;try{await Q(this.recoveryFileId,this.recoveryPath),this.loadError="",this.canRecover=!1,await this.resolveOpenUrl(!0)}catch(t){if(k(t)){await this.resolveOpenUrl(!0);return}this.isRecovering=!1,this.loadError=w(t,"Could not load pad."),this.handFocusToErrorCard()}finally{this.isRecovering=!1}}},async loadContent(){const t=this.resolveGeneration;this.contentGeneration+=1;const e=this.contentGeneration,n=()=>e===this.contentGeneration&&t===this.resolveGeneration;if(this.contentUrl===""){this.contentState="error",this.contentError=a("The server did not say where to load this pad from.");return}this._contentAbort?.abort();const i=typeof AbortController=="function"?new AbortController:null;this._contentAbort=i,this.contentState="loading",this.contentError="";try{const o=await E(this.contentUrl,{signal:i?.signal});if(!n())return;this.content=o,this.contentLoaded=!0,this.contentState="ready"}catch(o){if(!n()||o&&o.name==="AbortError")return;this.contentState="error",this.contentError=w(o,a("Could not load the pad content."))}},renderContentView(t,e){const n=Array.isArray(e.actions)?e.actions:[],i=this.contentState==="loading";return t("div",{class:"epnc-pad-doc"},[t("div",{class:"epnc-pad-doc__inner"},[t("div",{class:"epnc-pad-doc__toolbar"},[this.contentState==="error"&&this.contentLoaded?t("span",{class:"epnc-pad-doc__toolbar-error"},this.contentError||a("Could not load the pad content.")):null,t("button",{class:"button epnc-pad-doc__refresh",attrs:{type:"button",disabled:i},on:{click:()=>{this.loadContent()}}},i?a("Refreshing..."):a("Refresh")),...n]),this.renderContentBody(t)])])},renderContentBody(t){return this.contentLoaded&&this.contentState!=="ready"?this.renderContentText(t):this.contentState==="error"?t("div",{class:"epnc-pad-doc__text epnc-pad-doc__status"},[t("div",{},this.contentError||a("Could not load the pad content.")),t("button",{class:"button primary",attrs:{type:"button"},on:{click:()=>{this.loadContent()}}},a("Try again"))]):this.contentState!=="ready"?t("div",{class:"epnc-pad-doc__text epnc-pad-doc__status"},a("Loading pad content...")):this.renderContentText(t)},renderContentText(t){return this.content.isEmpty?t("div",{class:"epnc-pad-doc__text epnc-pad-doc__status"},a("This pad is still empty.")):t("div",{class:"epnc-pad-doc__text epnc-pad-doc__text--html",domProps:{innerHTML:this.content.html}})}},beforeDestroy(){this.resolveGeneration+=1,this._openAbort?.abort(),this._contentAbort?.abort(),this.teardownSync()},beforeUnmount(){this.resolveGeneration+=1,this._openAbort?.abort(),this._contentAbort?.abort(),this.teardownSync()},render(t){if(this.loadError){const e=[t("div",{class:"epnc-native-error-title"},a("Could not open pad")),t("div",{class:"epnc-native-error-message",attrs:{role:"alert"}},this.loadError)];return this.maybeStaleFileId&&e.push(t("div",{class:"epnc-native-error-message"},a("This file may have been moved or replaced since the list was loaded. Reload the page and open it again."))),this.canRetryOpen&&e.push(t("button",{class:"button primary epnc-native-error-action",attrs:{type:"button"},on:{click:()=>{this.resolveOpenUrl(!0)}}},a("Try again"))),this.canRecover&&this.padLost?e.push(t("button",{class:"button primary epnc-native-error-action",attrs:{type:"button",disabled:this.isRecovering},on:{click:()=>{this.recoverFromSnapshot()}}},this.isRecovering?a("Creating new pad..."):a("Create new pad from this file"))):this.canRecover&&(this.isCheckingOriginal?e.push(t("div",{class:"epnc-native-error-message"},a("Checking for the original pad..."))):this.originalPad?e.push(t("div",{class:"epnc-native-error-message"},a("This file looks like a copy of an existing .pad file in your account. Open the original to keep editing the linked pad, or create a new pad to fork the content stored in this file.")),t("a",{class:"button primary epnc-native-error-action",attrs:{href:this.originalPad.viewerUrl}},a("Open the original .pad file")),t("button",{class:"button epnc-native-error-action",attrs:{type:"button",disabled:this.isRecovering},on:{click:()=>{this.recoverFromSnapshot()}}},this.isRecovering?a("Creating new pad..."):a("Create new pad from this file"))):e.push(t("div",{class:"epnc-native-error-message"},a("We couldn't find a matching pad in this Nextcloud. You can create a new pad from the text stored in this file; from then on, opening this file will load the new pad.")),t("button",{class:"button primary epnc-native-error-action",attrs:{type:"button",disabled:this.isRecovering},on:{click:()=>{this.recoverFromSnapshot()}}},this.isRecovering?a("Creating new pad..."):a("Create new pad from this file")))),t("div",{class:"epnc-native-status epnc-native-status--error"},[t("div",{class:"epnc-native-error-card",ref:"errorCard"},e)])}return this.contentMode==="content"?this.renderContentView(t,this.externalOpenUrl===""?{}:{actions:[t("a",{class:"button epnc-pad-doc__link",attrs:{href:this.externalOpenUrl,target:"_blank",rel:"noopener noreferrer"}},a("Open original pad"))]}):this.isLoading||!this.iframeSrc?t("div",{class:"epnc-native-status"},"Loading pad..."):t("div",{class:"epnc-native-shell"},[t("iframe",{attrs:{srcdoc:rt(this.iframeSrc),title:"Etherpad"},on:{load:()=>this.markLoaded(),error:()=>this.markLoaded()},class:"epnc-native-iframe"})])}};W({id:U,mimes:[L],component:it}); //# sourceMappingURL=etherpad_nextcloud-viewer-init.mjs.map diff --git a/js/etherpad_nextcloud-viewer-init.mjs.map b/js/etherpad_nextcloud-viewer-init.mjs.map index cb6ee868..18b4294b 100644 --- a/js/etherpad_nextcloud-viewer-init.mjs.map +++ b/js/etherpad_nextcloud-viewer-init.mjs.map @@ -1 +1 @@ -{"version":3,"file":"etherpad_nextcloud-viewer-init.mjs","sources":["../node_modules/@nextcloud/viewer/dist/index.js","../src/lib/api-client.js","../src/lib/pad-frame-srcdoc.js","../src/viewer-main.js","../src/viewer-init.js"],"sourcesContent":["/*!\n * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors\n * SPDX-License-Identifier: AGPL-3.0-or-later\n */\n/**\n * Register a new handler for the viewer.\n * This needs to be called before the viewer is initialized to ensure the handler is available.\n * So this should be called from an initialization script (`OCP\\Util::addInitScript`).\n *\n * @param handler - The handler to register\n * @throws Error if the handler is invalid\n */\nexport function registerHandler(handler) {\n validateHandler(handler);\n window._oca_viewer_handlers ?? (window._oca_viewer_handlers = new Map());\n if (window._oca_viewer_handlers.has(handler.id)) {\n console.warn(`Handler with id ${handler.id} is already registered.`);\n return;\n }\n window._oca_viewer_handlers.set(handler.id, handler);\n}\n/**\n * Validate the handler object.\n *\n * @param handler - The handler to validate\n */\nfunction validateHandler(handler) {\n const { id, mimes, mimesAliases, component } = handler;\n // checking valid handler id\n if (!id || id.trim() === '' || typeof id !== 'string') {\n throw new Error('The handler does not have a valid id');\n }\n // Nothing available to process! Failure\n if ((!mimes || !Array.isArray(mimes)) && !mimesAliases) {\n throw new Error('Handler needs a valid mime array or mimesAliases');\n }\n // checking valid handler component data\n if ((!component || (typeof component !== 'object' && typeof component !== 'function'))) {\n throw new Error('The handler does not have a valid component');\n }\n}\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/** Client helpers for pad resolution and snapshot recovery. */\n\nimport { APP_ID } from './constants.js'\nimport { ocGenerateUrl, ocRequestToken } from './oc-compat.js'\nimport { fetchJsonWithTimeout } from './fetch-helpers.js'\n\nconst RESOLVE_CACHE = new Map()\nconst RESOLVE_CACHE_MAX_ENTRIES = 50\nconst RESOLVE_CACHE_TTL_MS = 5 * 60 * 1000\n\n/**\n * Resolve a path to its pad metadata.\n *\n * Bypass the cache before a write. An entry is up to five minutes old, and\n * in five minutes a file can be moved and another `.pad` created at the\n * same path: for a read that is stale, for recovery it would bind a pad to\n * the wrong file.\n */\nexport const apiResolvePadByPath = async (path, { bypassCache = false } = {}) => {\n\tconst cacheKey = 'path:' + String(path)\n\tconst cached = bypassCache ? null : getResolveCache(cacheKey)\n\tif (cached !== null) {\n\t\treturn cached\n\t}\n\tconst url = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/resolve') + '?file=' + encodeURIComponent(path)\n\tconst request = fetchJson(url, {\n\t\tmethod: 'GET',\n\t\theaders: { Accept: 'application/json' },\n\t}, 'Pad resolve by path failed.')\n\t\t.catch((error) => {\n\t\t\tRESOLVE_CACHE.delete(cacheKey)\n\t\t\tthrow error\n\t\t})\n\tsetResolveCache(cacheKey, request)\n\treturn request\n}\n\nexport const apiFindOriginalPad = async (fileId) => {\n\tconst endpoint = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/find-original/' + encodeURIComponent(String(fileId)))\n\treturn fetchJson(endpoint, {\n\t\tmethod: 'GET',\n\t\theaders: { Accept: 'application/json' },\n\t}, 'Lookup failed.')\n}\n\nexport const apiRecoverFromSnapshot = async (fileId, path = '') => {\n\tconst endpoint = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/recover-from-snapshot/' + encodeURIComponent(String(fileId)))\n\t// A client timeout would not stop the server-side provisioning work.\n\tconst result = await fetchJsonWithTimeout(endpoint, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\tAccept: 'application/json',\n\t\t\trequesttoken: ocRequestToken(),\n\t\t},\n\t}, { fallbackMessage: 'Recovery failed.', timeoutMs: null })\n\t// Only this path: flushing every entry would throw away answers for\n\t// unrelated files the session has already looked up.\n\tif (typeof path === 'string' && path !== '') {\n\t\tRESOLVE_CACHE.delete('path:' + path)\n\t}\n\treturn result\n}\nconst getResolveCache = (cacheKey) => {\n\tconst cached = RESOLVE_CACHE.get(cacheKey)\n\tif (!cached) {\n\t\treturn null\n\t}\n\tif ((Date.now() - cached.createdAt) > RESOLVE_CACHE_TTL_MS) {\n\t\tRESOLVE_CACHE.delete(cacheKey)\n\t\treturn null\n\t}\n\treturn cached.request\n}\n\nconst setResolveCache = (cacheKey, request) => {\n\tif (!RESOLVE_CACHE.has(cacheKey) && RESOLVE_CACHE.size >= RESOLVE_CACHE_MAX_ENTRIES) {\n\t\tconst oldestKey = RESOLVE_CACHE.keys().next().value\n\t\tif (oldestKey !== undefined) {\n\t\t\tRESOLVE_CACHE.delete(oldestKey)\n\t\t}\n\t}\n\tRESOLVE_CACHE.set(cacheKey, {\n\t\tcreatedAt: Date.now(),\n\t\trequest,\n\t})\n}\n\nconst fetchJson = async (url, options, fallbackMessage) =>\n\tfetchJsonWithTimeout(url, options, { fallbackMessage })\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\nconst escapeAttribute = (value) => String(value || '')\n\t.replace(/&/g, '&')\n\t.replace(/\"/g, '"')\n\t.replace(//g, '>')\n\nconst ALLOWED_PAD_URL_SCHEMES = ['http:', 'https:']\n\nconst isSafePadUrl = (url) => {\n\ttry {\n\t\tconst parsed = new URL(String(url || ''))\n\t\treturn ALLOWED_PAD_URL_SCHEMES.includes(parsed.protocol)\n\t\t\t&& parsed.username === ''\n\t\t\t&& parsed.password === ''\n\t} catch {\n\t\treturn false\n\t}\n}\n\nconst SRC_DOC_CSP = \"default-src 'none'; frame-src http: https:; style-src 'unsafe-inline'\"\n\nexport const buildPadFrameSrcdoc = (url) => {\n\tconst safeUrl = isSafePadUrl(url) ? escapeAttribute(url) : ''\n\treturn ''\n\t+ ''\n\t+ ''\n\t+ ''\n}\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/** Nextcloud Viewer component for editable pads and read-only pad content. */\n\nimport { APP_ID } from './lib/constants.js'\nimport { apiFindOriginalPad, apiRecoverFromSnapshot, apiResolvePadByPath } from './lib/api-client.js'\nimport { fetchJsonWithTimeout, isUnanswered, requestErrorMessage } from './lib/fetch-helpers.js'\nimport { handFocusTo } from './lib/hand-focus.js'\nimport { ocGenerateUrl, ocRequestToken, translate } from './lib/oc-compat.js'\nimport { createPadSync } from './lib/pad-sync.js'\nimport { loadPadContent } from './lib/pad-content.js'\nimport { assertOpenPayload, contentUrlFrom, contentViewFrom, isMissingBindingError, isRetryableOpenError, openWithFrontmatterRecovery, padUrlFrom, syncSettingsFrom } from './lib/pad-open-flow.js'\nimport { buildPadFrameSrcdoc } from './lib/pad-frame-srcdoc.js'\nimport { isPadName, parsePadPathFromDavHref, parsePublicShareTokenFromLocation } from './lib/urls.js'\n\n// When nothing came back: our own sentence, not the browser's English.\nconst messageOf = (error, fallback) => requestErrorMessage(error, translate('Nextcloud did not answer. Check your connection and try again.'), fallback)\n\nconst component = {\n\tname: 'EtherpadNextcloudViewer',\n\tprops: {\n\t\tfilename: { type: String, required: false, default: '' },\n\t\tbasename: { type: String, required: false, default: '' },\n\t\tsource: { type: String, required: false, default: '' },\n\t\tfileid: { type: [String, Number], required: false, default: null },\n\t\tfileId: { type: [String, Number], required: false, default: null },\n\t\tfileInfo: { type: Object, required: false, default: null },\n\t},\n\tdata() {\n\t\treturn {\n\t\t\tiframeSrc: '',\n\t\t\tisLoading: true,\n\t\t\tloadError: '',\n\t\t\tcanRecover: false,\n\t\t\tcanRetryOpen: false,\n\t\t\tmaybeStaleFileId: false,\n\t\t\t// Recovery may resolve this from the path when Viewer supplies no id.\n\t\t\trecoveryFileId: null,\n\t\t\t// Kept with the id so recovery invalidates the matching cache entry.\n\t\t\trecoveryPath: '',\n\t\t\tisRecovering: false,\n\t\t\tisCheckingOriginal: false,\n\t\t\toriginalPad: null,\n\t\t\texternalOpenUrl: '',\n\t\t\tcontentMode: '',\n\t\t\tcontentUrl: '',\n\t\t\tcontentState: 'idle',\n\t\t\tcontentError: '',\n\t\t\tcontent: { html: '', isEmpty: false },\n\t\t\t// A refresh keeps previously loaded content visible.\n\t\t\tcontentLoaded: false,\n\t\t\t// Refreshes supersede each other without superseding the open.\n\t\t\tcontentGeneration: 0,\n\t\t\tresolveGeneration: 0,\n\t\t}\n\t},\n\tcomputed: {\n\t\tsourcePath() {\n\t\t\t// Whitespace inside the DAV URL is encoded; only surrounding noise is trimmed.\n\t\t\tconst value = typeof this.source === 'string' ? this.source.trim() : ''\n\t\t\tif (!value) return ''\n\t\t\treturn parsePadPathFromDavHref(value) || ''\n\t\t},\n\t\tfilePath() {\n\t\t\t// Whitespace is part of the name, not noise: `Notes .pad` and\n\t\t\t// `Notes.pad` are two files, and trimming here opened the wrong one.\n\t\t\tconst normalizeDir = (dir) => {\n\t\t\t\tif (!dir || dir === '/') return '/'\n\t\t\t\treturn dir.startsWith('/') ? dir : ('/' + dir)\n\t\t\t}\n\t\t\tconst joinPath = (dir, name) => {\n\t\t\t\tif (!name) return ''\n\t\t\t\tif (name.startsWith('/')) return name\n\t\t\t\tconst normalizedDir = normalizeDir(dir)\n\t\t\t\treturn normalizedDir === '/' ? '/' + name : normalizedDir + '/' + name\n\t\t\t}\n\t\t\tif (isPadName(this.sourcePath)) return this.sourcePath\n\n\t\t\tconst info = this.fileInfo && typeof this.fileInfo === 'object' ? this.fileInfo : null\n\t\t\tconst infoPath = info && typeof info.path === 'string' ? info.path : ''\n\t\t\tif (isPadName(infoPath)) return infoPath.startsWith('/') ? infoPath : ('/' + infoPath)\n\n\t\t\tconst baseName = String(this.filename || this.basename || (info && (info.name || info.basename)) || '')\n\t\t\tif (!baseName) return ''\n\n\t\t\tconst infoDir = info && typeof info.dirname === 'string' ? info.dirname : ''\n\t\t\tif (infoDir) {\n\t\t\t\tconst combined = joinPath(infoDir, baseName)\n\t\t\t\tif (isPadName(combined)) return combined\n\t\t\t}\n\n\t\t\tconst params = new URLSearchParams(window.location.search || '')\n\t\t\tconst urlDir = params.get('dir') || '/'\n\t\t\tconst fromDir = joinPath(urlDir, baseName)\n\t\t\tif (isPadName(fromDir)) return fromDir\n\t\t\treturn '/' + baseName\n\t\t},\n\t\topenKey() {\n\t\t\treturn `${this.resolvedFileId === null ? '' : this.resolvedFileId}::${this.filePath}`\n\t\t},\n\t\tresolvedFileId() {\n\t\t\tconst candidates = [this.fileid, this.fileId, this.fileInfo && (this.fileInfo.fileid || this.fileInfo.fileId || this.fileInfo.id)]\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst numeric = Number(candidate)\n\t\t\t\tif (Number.isFinite(numeric) && numeric > 0) return numeric\n\t\t\t}\n\t\t\t// Route ids can outlive the item shown after Viewer navigation.\n\t\t\treturn null\n\t\t},\n\t},\n\twatch: {\n\t\t// A file swap changes path and id together; open it only once.\n\t\topenKey: { immediate: true, handler() { void this.resolveOpenUrl() } },\n\t},\n\tmethods: {\n\t\tasync fetchOpenPayload(url, init = {}) {\n\t\t\treturn assertOpenPayload(await fetchJsonWithTimeout(url, Object.assign({ method: 'GET' }, init)))\n\t\t},\n\t\tasync initializeMissingFrontmatter() {\n\t\t\tconst headers = {\n\t\t\t\tAccept: 'application/json',\n\t\t\t\trequesttoken: ocRequestToken(),\n\t\t\t}\n\n\t\t\t// A client timeout would not stop the server-side provisioning work.\n\t\t\tconst initOptions = { timeoutMs: null, fallbackMessage: 'Pad initialization failed.' }\n\n\t\t\tconst announceMigratedStatus = (data) => {\n\t\t\t\tif (data && data.status === 'migrated_from_legacy') {\n\t\t\t\t\tconsole.info('Legacy Ownpad .pad migrated to managed format on first open.')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.resolvedFileId !== null) {\n\t\t\t\tconst url = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/initialize-by-id/' + encodeURIComponent(String(this.resolvedFileId)))\n\t\t\t\tconst data = await fetchJsonWithTimeout(url, { method: 'POST', headers }, initOptions)\n\t\t\t\tannounceMigratedStatus(data)\n\t\t\t\treturn data\n\t\t\t}\n\n\t\t\tif (!this.filePath) {\n\t\t\t\tthrow new Error('Pad initialization failed: missing file path.')\n\t\t\t}\n\n\t\t\tconst body = new URLSearchParams()\n\t\t\tbody.set('file', this.filePath)\n\t\t\tconst url = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/initialize')\n\t\t\tconst data = await fetchJsonWithTimeout(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: Object.assign({}, headers, {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n\t\t\t\t}),\n\t\t\t\tbody: body.toString(),\n\t\t\t}, initOptions)\n\t\t\tannounceMigratedStatus(data)\n\t\t\treturn data\n\t\t},\n\t\t/** Resolve a fresh id for recovery without changing the opened file. */\n\t\tasync resolveRecoveryFileId(openPath) {\n\t\t\ttry {\n\t\t\t\tconst resolved = await apiResolvePadByPath(openPath, { bypassCache: true })\n\t\t\t\tconst id = Number(resolved && resolved.file_id)\n\t\t\t\treturn Number.isFinite(id) && id > 0 ? id : null\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\tmarkLoaded() {\n\t\t\tthis.$emit('update:loaded', true)\n\t\t},\n\t\t/**\n\t\t * See handFocusTo(). On the next tick, once the card is drawn: call\n\t\t * it after setting what the card shows.\n\t\t */\n\t\thandFocusToErrorCard() {\n\t\t\tthis.$nextTick(() => {\n\t\t\t\tconst card = this.$refs.errorCard\n\t\t\t\tif (card instanceof HTMLElement) {\n\t\t\t\t\thandFocusTo(card, card.querySelector('.epnc-native-error-message'))\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t// Keep the sync controller non-reactive and available to the immediate watcher.\n\t\tpadSync() {\n\t\t\tif (!this._padSync) {\n\t\t\t\tthis._padSync = createPadSync({ requestToken: () => ocRequestToken() })\n\t\t\t}\n\t\t\treturn this._padSync\n\t\t},\n\t\t// Do not create a controller solely to tear it down.\n\t\tteardownSync() {\n\t\t\tif (!this._padSync) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis._padSync.fireAndForget(true, true)\n\t\t\tthis._padSync.stop()\n\t\t\tthis._padSync.removeLifecycleHandlers()\n\t\t},\n\t\t/** $afterClick: see handFocusToErrorCard(). */\n\t\tasync resolveOpenUrl(afterClick = false) {\n\t\t\tconst generation = ++this.resolveGeneration\n\t\t\tconst isCurrent = () => generation === this.resolveGeneration\n\t\t\t// Discarding a result is insufficient: a completed request may mint a session.\n\t\t\tthis._openAbort?.abort()\n\t\t\tconst abort = typeof AbortController === 'function' ? new AbortController() : null\n\t\t\tthis._openAbort = abort\n\n\t\t\tthis.isLoading = true\n\t\t\tthis.loadError = ''\n\t\t\tthis.canRecover = false\n\t\t\tthis.canRetryOpen = false\n\t\t\tthis.maybeStaleFileId = false\n\t\t\tthis.recoveryFileId = null\n\t\t\tthis.recoveryPath = ''\n\t\t\tthis.isCheckingOriginal = false\n\t\t\tthis.originalPad = null\n\t\t\tthis.iframeSrc = ''\n\t\t\tthis.externalOpenUrl = ''\n\t\t\tthis.contentMode = ''\n\t\t\tthis.contentUrl = ''\n\t\t\tthis.contentState = 'idle'\n\t\t\tthis.contentError = ''\n\t\t\tthis.content = { html: '', isEmpty: false }\n\t\t\tthis.contentLoaded = false\n\t\t\tthis._contentAbort?.abort()\n\t\t\t// Do not construct a sync controller while resetting viewer state.\n\t\t\tif (this._padSync) {\n\t\t\t\tthis._padSync.stop()\n\t\t\t\tthis._padSync.configure({ syncUrl: '' })\n\t\t\t}\n\n\t\t\tif (!this.filePath) {\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.loadError = 'No .pad file selected.'\n\t\t\t\tthis.isLoading = false\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Viewer props may change before the watcher starts the next open.\n\t\t\tconst openPath = this.filePath\n\t\t\tconst publicToken = parsePublicShareTokenFromLocation()\n\t\t\tconst byPublicUrl = (() => {\n\t\t\t\tif (!publicToken) return ''\n\t\t\t\tconst url = new URL(ocGenerateUrl('/apps/' + APP_ID + '/api/v1/public/open/' + encodeURIComponent(publicToken)), window.location.origin)\n\t\t\t\t// The public endpoint rejects conflicting id and path locators.\n\t\t\t\tif (this.resolvedFileId !== null) {\n\t\t\t\t\turl.searchParams.set('fileId', String(this.resolvedFileId))\n\t\t\t\t} else {\n\t\t\t\t\turl.searchParams.set('file', openPath)\n\t\t\t\t}\n\t\t\t\treturn url.toString()\n\t\t\t})()\n\t\t\tconst openPostHeaders = {\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n\t\t\t\trequesttoken: ocRequestToken(),\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst fetchOpenData = async () => {\n\t\t\t\t\t// Never retry a refused id by path: it could identify a different file.\n\t\t\t\t\tconst signal = abort ? abort.signal : undefined\n\t\t\t\t\tif (byPublicUrl) {\n\t\t\t\t\t\treturn await this.fetchOpenPayload(byPublicUrl, { signal })\n\t\t\t\t\t}\n\t\t\t\t\t// One way in, chosen once. An open by id that retries by\n\t\t\t\t\t// path is how a refused id ended up opening whatever the\n\t\t\t\t\t// path pointed at.\n\t\t\t\t\tif (this.resolvedFileId !== null) {\n\t\t\t\t\t\tconst byIdBody = new URLSearchParams()\n\t\t\t\t\t\tbyIdBody.set('fileId', String(this.resolvedFileId))\n\t\t\t\t\t\treturn await this.fetchOpenPayload(\n\t\t\t\t\t\t\tocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/open-by-id'),\n\t\t\t\t\t\t\t{ method: 'POST', headers: openPostHeaders, body: byIdBody.toString(), signal },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst byPathBody = new URLSearchParams()\n\t\t\t\t\tbyPathBody.set('file', openPath)\n\t\t\t\t\treturn await this.fetchOpenPayload(\n\t\t\t\t\t\tocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/open'),\n\t\t\t\t\t\t{ method: 'POST', headers: openPostHeaders, body: byPathBody.toString(), signal },\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst data = await openWithFrontmatterRecovery({\n\t\t\t\t\topen: fetchOpenData,\n\t\t\t\t\tinitialize: () => this.initializeMissingFrontmatter(),\n\t\t\t\t\tstillWanted: isCurrent,\n\t\t\t\t})\n\t\t\t\tif (data === null || !isCurrent()) return\n\n\t\t\t\tconst { syncUrl, intervalMs } = syncSettingsFrom(data)\n\n\t\t\t\tthis.padSync().configure({ syncUrl, intervalMs })\n\t\t\t\tthis.padSync().installLifecycleHandlers()\n\t\t\t\tif (syncUrl) {\n\t\t\t\t\tthis.padSync().start()\n\t\t\t\t}\n\n\t\t\t\tconst contentUrl = contentUrlFrom(data)\n\n\t\t\t\tconst { isContentView, externalUrl } = contentViewFrom(data)\n\t\t\t\tif (isContentView) {\n\t\t\t\t\tthis.externalOpenUrl = externalUrl\n\t\t\t\t\tthis.contentUrl = contentUrl\n\t\t\t\t\tthis.contentMode = 'content'\n\t\t\t\t\tthis.markLoaded()\n\t\t\t\t\t// Draw the content view while its body loads.\n\t\t\t\t\tvoid this.loadContent()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tthis.iframeSrc = padUrlFrom(data)\n\t\t\t\tthis.markLoaded()\n\t\t\t} catch (error) {\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.loadError = messageOf(error, 'Could not load pad.')\n\t\t\t\t// The server intentionally does not disclose why this id is unavailable.\n\t\t\t\tthis.maybeStaleFileId = this.resolvedFileId !== null\n\t\t\t\t\t&& Boolean(error) && error.status === 404 && !error.code\n\t\t\t\tthis.canRetryOpen = isRetryableOpenError(error)\n\t\t\t\t// Recovery may resolve only the same path that failed to open.\n\t\t\t\tlet recoveryFileId = this.resolvedFileId\n\t\t\t\tthis.recoveryPath = openPath\n\t\t\t\tif (recoveryFileId === null && !byPublicUrl && isMissingBindingError(error)) {\n\t\t\t\t\trecoveryFileId = await this.resolveRecoveryFileId(openPath)\n\t\t\t\t\t// A late lookup must not attach recovery to a newer Viewer item.\n\t\t\t\t\tif (!isCurrent()) return\n\t\t\t\t}\n\t\t\t\tthis.recoveryFileId = recoveryFileId\n\t\t\t\tthis.canRecover = isMissingBindingError(error)\n\t\t\t\t\t&& recoveryFileId !== null\n\t\t\t\t\t&& !byPublicUrl\n\t\t\t\tif (this.canRecover) {\n\t\t\t\t\tthis.fetchOriginalPadHint(isCurrent, afterClick)\n\t\t\t\t} else if (afterClick) {\n\t\t\t\t\tthis.handFocusToErrorCard()\n\t\t\t\t}\n\t\t\t\tthis.markLoaded()\n\t\t\t} finally {\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.isLoading = false\n\t\t\t}\n\t\t},\n\t\t/** $afterClick: the focus waits for the card's final actions. */\n\t\tasync fetchOriginalPadHint(isCurrent, afterClick = false) {\n\t\t\tif (this.recoveryFileId === null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.isCheckingOriginal = true\n\t\t\ttry {\n\t\t\t\tconst hint = await apiFindOriginalPad(this.recoveryFileId)\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tif (hint && hint.found === true && typeof hint.viewer_url === 'string' && hint.viewer_url !== '') {\n\t\t\t\t\tthis.originalPad = {\n\t\t\t\t\t\tviewerUrl: hint.viewer_url,\n\t\t\t\t\t\tpath: typeof hint.path === 'string' ? hint.path : '',\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Recovery remains available without an original-file hint.\n\t\t\t} finally {\n\t\t\t\tif (isCurrent()) {\n\t\t\t\t\tthis.isCheckingOriginal = false\n\t\t\t\t\tif (afterClick) {\n\t\t\t\t\t\tthis.handFocusToErrorCard()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync recoverFromSnapshot() {\n\t\t\tif (!this.canRecover || this.isRecovering || this.recoveryFileId === null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.isRecovering = true\n\t\t\ttry {\n\t\t\t\tawait apiRecoverFromSnapshot(this.recoveryFileId, this.recoveryPath)\n\t\t\t\tthis.loadError = ''\n\t\t\t\tthis.canRecover = false\n\t\t\t\tawait this.resolveOpenUrl(true)\n\t\t\t} catch (error) {\n\t\t\t\t// No answer: the pad may be set up by now, and another\n\t\t\t\t// recovery would meet it. Opening tells, and is safe to repeat.\n\t\t\t\tif (isUnanswered(error)) {\n\t\t\t\t\tawait this.resolveOpenUrl(true)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Enabled again before the card is drawn, so the focus lands.\n\t\t\t\tthis.isRecovering = false\n\t\t\t\tthis.loadError = messageOf(error, 'Could not load pad.')\n\t\t\t\t// The clicked button lost the focus while it was disabled.\n\t\t\t\tthis.handFocusToErrorCard()\n\t\t\t} finally {\n\t\t\t\tthis.isRecovering = false\n\t\t\t}\n\t\t},\n\t\t/** Refresh content through an endpoint that re-checks access. */\n\t\tasync loadContent() {\n\t\t\tconst openGeneration = this.resolveGeneration\n\t\t\tthis.contentGeneration += 1\n\t\t\tconst generation = this.contentGeneration\n\t\t\tconst isCurrent = () => generation === this.contentGeneration\n\t\t\t\t&& openGeneration === this.resolveGeneration\n\n\t\t\tif (this.contentUrl === '') {\n\t\t\t\tthis.contentState = 'error'\n\t\t\t\tthis.contentError = translate('The server did not say where to load this pad from.')\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tthis._contentAbort?.abort()\n\t\t\t// Abort superseded content refreshes.\n\t\t\tconst abort = typeof AbortController === 'function' ? new AbortController() : null\n\t\t\tthis._contentAbort = abort\n\t\t\tthis.contentState = 'loading'\n\t\t\tthis.contentError = ''\n\n\t\t\ttry {\n\t\t\t\tconst content = await loadPadContent(this.contentUrl, { signal: abort?.signal })\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.content = content\n\t\t\t\tthis.contentLoaded = true\n\t\t\t\tthis.contentState = 'ready'\n\t\t\t} catch (error) {\n\t\t\t\tif (!isCurrent() || (error && error.name === 'AbortError')) return\n\t\t\t\tthis.contentState = 'error'\n\t\t\t\tthis.contentError = messageOf(error, translate('Could not load the pad content.'))\n\t\t\t}\n\t\t},\n\t\trenderContentView(createElement, options) {\n\t\t\tconst extraActions = Array.isArray(options.actions) ? options.actions : []\n\t\t\tconst isBusy = this.contentState === 'loading'\n\n\t\t\treturn createElement('div', { class: 'epnc-pad-doc' }, [\n\t\t\t\tcreateElement('div', { class: 'epnc-pad-doc__inner' }, [\n\t\t\t\t\tcreateElement('div', { class: 'epnc-pad-doc__toolbar' }, [\n\t\t\t\t\t\t(this.contentState === 'error' && this.contentLoaded)\n\t\t\t\t\t\t\t? createElement('span', { class: 'epnc-pad-doc__toolbar-error' },\n\t\t\t\t\t\t\t\tthis.contentError || translate('Could not load the pad content.'))\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\t\tclass: 'button epnc-pad-doc__refresh',\n\t\t\t\t\t\t\tattrs: { type: 'button', disabled: isBusy },\n\t\t\t\t\t\t\ton: { click: () => { void this.loadContent() } },\n\t\t\t\t\t\t}, isBusy ? translate('Refreshing...') : translate('Refresh')),\n\t\t\t\t\t\t...extraActions,\n\t\t\t\t\t]),\n\t\t\t\t\tthis.renderContentBody(createElement),\n\t\t\t\t]),\n\t\t\t])\n\t\t},\n\t\trenderContentBody(createElement) {\n\t\t\tif (this.contentLoaded && this.contentState !== 'ready') {\n\t\t\t\treturn this.renderContentText(createElement)\n\t\t\t}\n\t\t\tif (this.contentState === 'error') {\n\t\t\t\treturn createElement('div', { class: 'epnc-pad-doc__text epnc-pad-doc__status' }, [\n\t\t\t\t\tcreateElement('div', {},\n\t\t\t\t\t\tthis.contentError || translate('Could not load the pad content.')),\n\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\tclass: 'button primary',\n\t\t\t\t\t\tattrs: { type: 'button' },\n\t\t\t\t\t\ton: { click: () => { void this.loadContent() } },\n\t\t\t\t\t}, translate('Try again')),\n\t\t\t\t])\n\t\t\t}\n\t\t\tif (this.contentState !== 'ready') {\n\t\t\t\treturn createElement('div', { class: 'epnc-pad-doc__text epnc-pad-doc__status' }, translate('Loading pad content...'))\n\t\t\t}\n\t\t\treturn this.renderContentText(createElement)\n\t\t},\n\t\trenderContentText(createElement) {\n\t\t\tif (this.content.isEmpty) {\n\t\t\t\treturn createElement('div', { class: 'epnc-pad-doc__text epnc-pad-doc__status' }, translate('This pad is still empty.'))\n\t\t\t}\n\t\t\treturn createElement('div', {\n\t\t\t\tclass: 'epnc-pad-doc__text epnc-pad-doc__text--html',\n\t\t\t\tdomProps: { innerHTML: this.content.html },\n\t\t\t})\n\t\t},\n\t},\n\tbeforeDestroy() {\n\t\tthis.resolveGeneration += 1\n\t\t// Abort work that could otherwise finish after teardown.\n\t\tthis._openAbort?.abort()\n\t\tthis._contentAbort?.abort()\n\t\tthis.teardownSync()\n\t},\n\tbeforeUnmount() {\n\t\tthis.resolveGeneration += 1\n\t\tthis._openAbort?.abort()\n\t\tthis._contentAbort?.abort()\n\t\tthis.teardownSync()\n\t},\n\trender(createElement) {\n\t\tif (this.loadError) {\n\t\t\tconst cardChildren = [\n\t\t\t\tcreateElement('div', { class: 'epnc-native-error-title' }, translate('Could not open pad')),\n\t\t\t\t// Read out when it appears, not only when someone looks.\n\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message', attrs: { role: 'alert' } }, this.loadError),\n\t\t\t]\n\t\t\tif (this.maybeStaleFileId) {\n\t\t\t\tcardChildren.push(\n\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\ttranslate('This file may have been moved or replaced since the list was loaded. Reload the page and open it again.')),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.canRetryOpen) {\n\t\t\t\tcardChildren.push(\n\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\tattrs: { type: 'button' },\n\t\t\t\t\t\ton: { click: () => { void this.resolveOpenUrl(true) } },\n\t\t\t\t\t}, translate('Try again')),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.canRecover) {\n\t\t\t\tif (this.isCheckingOriginal) {\n\t\t\t\t\t// Wait before choosing the primary recovery action.\n\t\t\t\t\tcardChildren.push(\n\t\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\t\ttranslate('Checking for the original pad...')),\n\t\t\t\t\t)\n\t\t\t\t} else if (this.originalPad) {\n\t\t\t\t\tcardChildren.push(\n\t\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\t\ttranslate('This file looks like a copy of an existing .pad file in your account. Open the original to keep editing the linked pad, or create a new pad to fork the content stored in this file.')),\n\t\t\t\t\t\tcreateElement('a', {\n\t\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\t\tattrs: { href: this.originalPad.viewerUrl },\n\t\t\t\t\t\t}, translate('Open the original .pad file')),\n\t\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\t\tclass: 'button epnc-native-error-action',\n\t\t\t\t\t\t\tattrs: { type: 'button', disabled: this.isRecovering },\n\t\t\t\t\t\t\ton: { click: () => { void this.recoverFromSnapshot() } },\n\t\t\t\t\t\t}, this.isRecovering ? translate('Creating new pad...') : translate('Create new pad from this file')),\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tcardChildren.push(\n\t\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\t\ttranslate(\"We couldn't find a matching pad in this Nextcloud. You can create a new pad from the text stored in this file; from then on, opening this file will load the new pad.\")),\n\t\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\t\tattrs: { type: 'button', disabled: this.isRecovering },\n\t\t\t\t\t\t\ton: { click: () => { void this.recoverFromSnapshot() } },\n\t\t\t\t\t\t}, this.isRecovering ? translate('Creating new pad...') : translate('Create new pad from this file')),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn createElement('div', { class: 'epnc-native-status epnc-native-status--error' }, [\n\t\t\t\tcreateElement('div', { class: 'epnc-native-error-card', ref: 'errorCard' }, cardChildren),\n\t\t\t])\n\t\t}\n\t\tif (this.contentMode === 'content') {\n\t\t\treturn this.renderContentView(createElement, this.externalOpenUrl === ''\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\tactions: [\n\t\t\t\t\t\tcreateElement('a', {\n\t\t\t\t\t\t\tclass: 'button epnc-pad-doc__link',\n\t\t\t\t\t\t\tattrs: {\n\t\t\t\t\t\t\t\thref: this.externalOpenUrl,\n\t\t\t\t\t\t\t\ttarget: '_blank',\n\t\t\t\t\t\t\t\trel: 'noopener noreferrer',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}, translate('Open original pad')),\n\t\t\t\t\t],\n\t\t\t\t})\n\t\t}\n\t\tif (this.isLoading || !this.iframeSrc) {\n\t\t\treturn createElement('div', { class: 'epnc-native-status' }, 'Loading pad...')\n\t\t}\n\n\t\treturn createElement('div', { class: 'epnc-native-shell' }, [\n\t\t\t// Nextcloud inspects direct iframe children, so keep this wrapper same-origin.\n\t\t\tcreateElement('iframe', {\n\t\t\t\tattrs: { srcdoc: buildPadFrameSrcdoc(this.iframeSrc), title: 'Etherpad' },\n\t\t\t\t// Etherpad provides its own loading state inside the nested iframe.\n\t\t\t\ton: { load: () => this.markLoaded(), error: () => this.markLoaded() },\n\t\t\t\tclass: 'epnc-native-iframe',\n\t\t\t}),\n\t\t])\n\t},\n}\n\nexport default component\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/** Registers the pad MIME handler with the Viewer. */\n\nimport { registerHandler } from '@nextcloud/viewer'\n\nimport { MIME, VIEWER_HANDLER_ID } from './lib/constants.js'\nimport component from './viewer-main.js'\n\n// The options object itself, not a loader for it: the Viewer assigns its\n// Mime mixin onto what it is given and registers it under `component.name`,\n// and a function silently takes neither.\nregisterHandler({ id: VIEWER_HANDLER_ID, mimes: [MIME], component })\n"],"names":["registerHandler","handler","validateHandler","id","mimes","mimesAliases","component","RESOLVE_CACHE","RESOLVE_CACHE_MAX_ENTRIES","RESOLVE_CACHE_TTL_MS","apiResolvePadByPath","path","bypassCache","cacheKey","cached","getResolveCache","url","ocGenerateUrl","APP_ID","request","fetchJson","error","setResolveCache","apiFindOriginalPad","fileId","endpoint","apiRecoverFromSnapshot","result","fetchJsonWithTimeout","ocRequestToken","oldestKey","options","fallbackMessage","escapeAttribute","value","ALLOWED_PAD_URL_SCHEMES","isSafePadUrl","parsed","SRC_DOC_CSP","buildPadFrameSrcdoc","safeUrl","messageOf","fallback","requestErrorMessage","translate","parsePadPathFromDavHref","normalizeDir","dir","joinPath","name","normalizedDir","isPadName","info","infoPath","baseName","infoDir","combined","urlDir","fromDir","candidates","candidate","numeric","init","assertOpenPayload","headers","initOptions","announceMigratedStatus","data","body","openPath","resolved","card","handFocusTo","createPadSync","afterClick","generation","isCurrent","abort","publicToken","parsePublicShareTokenFromLocation","byPublicUrl","openPostHeaders","openWithFrontmatterRecovery","signal","byIdBody","byPathBody","syncUrl","intervalMs","syncSettingsFrom","contentUrl","contentUrlFrom","isContentView","externalUrl","contentViewFrom","padUrlFrom","isRetryableOpenError","recoveryFileId","isMissingBindingError","hint","isUnanswered","openGeneration","content","loadPadContent","createElement","extraActions","isBusy","cardChildren","VIEWER_HANDLER_ID","MIME"],"mappings":"mSAYO,SAASA,EAAgBC,EAAS,CAGrC,GAFAC,EAAgBD,CAAO,EACvB,OAAO,uBAAyB,OAAO,qBAAuB,IAAI,KAC9D,OAAO,qBAAqB,IAAIA,EAAQ,EAAE,EAAG,CAC7C,QAAQ,KAAK,mBAAmBA,EAAQ,EAAE,yBAAyB,EACnE,MACJ,CACA,OAAO,qBAAqB,IAAIA,EAAQ,GAAIA,CAAO,CACvD,CAMA,SAASC,EAAgBD,EAAS,CAC9B,KAAM,CAAE,GAAAE,EAAI,MAAAC,EAAO,aAAAC,EAAc,UAAAC,CAAS,EAAKL,EAE/C,GAAI,CAACE,GAAMA,EAAG,KAAI,IAAO,IAAM,OAAOA,GAAO,SACzC,MAAM,IAAI,MAAM,sCAAsC,EAG1D,IAAK,CAACC,GAAS,CAAC,MAAM,QAAQA,CAAK,IAAM,CAACC,EACtC,MAAM,IAAI,MAAM,kDAAkD,EAGtE,GAAK,CAACC,GAAc,OAAOA,GAAc,UAAY,OAAOA,GAAc,WACtE,MAAM,IAAI,MAAM,6CAA6C,CAErE,CC7BA,MAAMC,EAAgB,IAAI,IACpBC,EAA4B,GAC5BC,EAAuB,IAAS,IAUzBC,EAAsB,MAAOC,EAAM,CAAE,YAAAC,EAAc,EAAK,EAAK,CAAA,IAAO,CAChF,MAAMC,EAAW,QAAU,OAAOF,CAAI,EAChCG,EAASF,EAAc,KAAOG,EAAgBF,CAAQ,EAC5D,GAAIC,IAAW,KACd,OAAOA,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,MAAO,0CACP,MAAO,CAAE,KAAM,SAAU,SAAU,KAAK,YAAY,EACpD,GAAI,CAAE,MAAO,IAAM,CAAO,KAAK,oBAAmB,CAAG,CAAC,CAC7D,EAAS,KAAK,aAAe3D,EAAU,qBAAqB,EAAIA,EAAU,+BAA+B,CAAC,CAC1G,GAGU2D,EAAc,MAAO,CAAE,MAAO,8CAA8C,EAAI,CACtFA,EAAc,MAAO,CAAE,MAAO,yBAA0B,IAAK,WAAW,EAAIG,CAAY,CAC5F,CAAI,CACF,CACA,OAAI,KAAK,cAAgB,UACjB,KAAK,kBAAkBH,EAAe,KAAK,kBAAoB,GACnE,CAAA,EACA,CACD,QAAS,CACRA,EAAc,IAAK,CAClB,MAAO,4BACP,MAAO,CACN,KAAM,KAAK,gBACX,OAAQ,SACR,IAAK,qBACb,CACA,EAAS3D,EAAU,mBAAmB,CAAC,CACvC,CACA,CAAK,EAEC,KAAK,WAAa,CAAC,KAAK,UACpB2D,EAAc,MAAO,CAAE,MAAO,oBAAoB,EAAI,gBAAgB,EAGvEA,EAAc,MAAO,CAAE,MAAO,mBAAmB,EAAI,CAE3DA,EAAc,SAAU,CACvB,MAAO,CAAE,OAAQhE,GAAoB,KAAK,SAAS,EAAG,MAAO,UAAU,EAEvE,GAAI,CAAE,KAAM,IAAM,KAAK,WAAU,EAAI,MAAO,IAAM,KAAK,YAAY,EACnE,MAAO,oBACX,CAAI,CACJ,CAAG,CACF,CACD,EC1jBAvC,EAAgB,CAAE,GAAI2G,EAAmB,MAAO,CAACC,CAAI,EAAG,UAAAtG,EAAS,CAAE","x_google_ignoreList":[0]} \ No newline at end of file +{"version":3,"file":"etherpad_nextcloud-viewer-init.mjs","sources":["../node_modules/@nextcloud/viewer/dist/index.js","../src/lib/api-client.js","../src/lib/pad-frame-srcdoc.js","../src/viewer-main.js","../src/viewer-init.js"],"sourcesContent":["/*!\n * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors\n * SPDX-License-Identifier: AGPL-3.0-or-later\n */\n/**\n * Register a new handler for the viewer.\n * This needs to be called before the viewer is initialized to ensure the handler is available.\n * So this should be called from an initialization script (`OCP\\Util::addInitScript`).\n *\n * @param handler - The handler to register\n * @throws Error if the handler is invalid\n */\nexport function registerHandler(handler) {\n validateHandler(handler);\n window._oca_viewer_handlers ?? (window._oca_viewer_handlers = new Map());\n if (window._oca_viewer_handlers.has(handler.id)) {\n console.warn(`Handler with id ${handler.id} is already registered.`);\n return;\n }\n window._oca_viewer_handlers.set(handler.id, handler);\n}\n/**\n * Validate the handler object.\n *\n * @param handler - The handler to validate\n */\nfunction validateHandler(handler) {\n const { id, mimes, mimesAliases, component } = handler;\n // checking valid handler id\n if (!id || id.trim() === '' || typeof id !== 'string') {\n throw new Error('The handler does not have a valid id');\n }\n // Nothing available to process! Failure\n if ((!mimes || !Array.isArray(mimes)) && !mimesAliases) {\n throw new Error('Handler needs a valid mime array or mimesAliases');\n }\n // checking valid handler component data\n if ((!component || (typeof component !== 'object' && typeof component !== 'function'))) {\n throw new Error('The handler does not have a valid component');\n }\n}\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/** Client helpers for pad resolution and snapshot recovery. */\n\nimport { APP_ID } from './constants.js'\nimport { ocGenerateUrl, ocRequestToken } from './oc-compat.js'\nimport { fetchJsonWithTimeout } from './fetch-helpers.js'\n\nconst RESOLVE_CACHE = new Map()\nconst RESOLVE_CACHE_MAX_ENTRIES = 50\nconst RESOLVE_CACHE_TTL_MS = 5 * 60 * 1000\n\n/**\n * Resolve a path to its pad metadata.\n *\n * Bypass the cache before a write. An entry is up to five minutes old, and\n * in five minutes a file can be moved and another `.pad` created at the\n * same path: for a read that is stale, for recovery it would bind a pad to\n * the wrong file.\n */\nexport const apiResolvePadByPath = async (path, { bypassCache = false } = {}) => {\n\tconst cacheKey = 'path:' + String(path)\n\tconst cached = bypassCache ? null : getResolveCache(cacheKey)\n\tif (cached !== null) {\n\t\treturn cached\n\t}\n\tconst url = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/resolve') + '?file=' + encodeURIComponent(path)\n\tconst request = fetchJson(url, {\n\t\tmethod: 'GET',\n\t\theaders: { Accept: 'application/json' },\n\t}, 'Pad resolve by path failed.')\n\t\t.catch((error) => {\n\t\t\tRESOLVE_CACHE.delete(cacheKey)\n\t\t\tthrow error\n\t\t})\n\tsetResolveCache(cacheKey, request)\n\treturn request\n}\n\nexport const apiFindOriginalPad = async (fileId) => {\n\tconst endpoint = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/find-original/' + encodeURIComponent(String(fileId)))\n\treturn fetchJson(endpoint, {\n\t\tmethod: 'GET',\n\t\theaders: { Accept: 'application/json' },\n\t}, 'Lookup failed.')\n}\n\nexport const apiRecoverFromSnapshot = async (fileId, path = '') => {\n\tconst endpoint = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/recover-from-snapshot/' + encodeURIComponent(String(fileId)))\n\t// A client timeout would not stop the server-side provisioning work.\n\tconst result = await fetchJsonWithTimeout(endpoint, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\tAccept: 'application/json',\n\t\t\trequesttoken: ocRequestToken(),\n\t\t},\n\t}, { fallbackMessage: 'Recovery failed.', timeoutMs: null })\n\t// Only this path: flushing every entry would throw away answers for\n\t// unrelated files the session has already looked up.\n\tif (typeof path === 'string' && path !== '') {\n\t\tRESOLVE_CACHE.delete('path:' + path)\n\t}\n\treturn result\n}\nconst getResolveCache = (cacheKey) => {\n\tconst cached = RESOLVE_CACHE.get(cacheKey)\n\tif (!cached) {\n\t\treturn null\n\t}\n\tif ((Date.now() - cached.createdAt) > RESOLVE_CACHE_TTL_MS) {\n\t\tRESOLVE_CACHE.delete(cacheKey)\n\t\treturn null\n\t}\n\treturn cached.request\n}\n\nconst setResolveCache = (cacheKey, request) => {\n\tif (!RESOLVE_CACHE.has(cacheKey) && RESOLVE_CACHE.size >= RESOLVE_CACHE_MAX_ENTRIES) {\n\t\tconst oldestKey = RESOLVE_CACHE.keys().next().value\n\t\tif (oldestKey !== undefined) {\n\t\t\tRESOLVE_CACHE.delete(oldestKey)\n\t\t}\n\t}\n\tRESOLVE_CACHE.set(cacheKey, {\n\t\tcreatedAt: Date.now(),\n\t\trequest,\n\t})\n}\n\nconst fetchJson = async (url, options, fallbackMessage) =>\n\tfetchJsonWithTimeout(url, options, { fallbackMessage })\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\nconst escapeAttribute = (value) => String(value || '')\n\t.replace(/&/g, '&')\n\t.replace(/\"/g, '"')\n\t.replace(//g, '>')\n\nconst ALLOWED_PAD_URL_SCHEMES = ['http:', 'https:']\n\nconst isSafePadUrl = (url) => {\n\ttry {\n\t\tconst parsed = new URL(String(url || ''))\n\t\treturn ALLOWED_PAD_URL_SCHEMES.includes(parsed.protocol)\n\t\t\t&& parsed.username === ''\n\t\t\t&& parsed.password === ''\n\t} catch {\n\t\treturn false\n\t}\n}\n\nconst SRC_DOC_CSP = \"default-src 'none'; frame-src http: https:; style-src 'unsafe-inline'\"\n\nexport const buildPadFrameSrcdoc = (url) => {\n\tconst safeUrl = isSafePadUrl(url) ? escapeAttribute(url) : ''\n\treturn ''\n\t+ ''\n\t+ ''\n\t+ ''\n}\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/** Nextcloud Viewer component for editable pads and read-only pad content. */\n\nimport { APP_ID } from './lib/constants.js'\nimport { apiFindOriginalPad, apiRecoverFromSnapshot, apiResolvePadByPath } from './lib/api-client.js'\nimport { fetchJsonWithTimeout, isUnanswered, requestErrorMessage } from './lib/fetch-helpers.js'\nimport { handFocusTo } from './lib/hand-focus.js'\nimport { ocGenerateUrl, ocRequestToken, translate } from './lib/oc-compat.js'\nimport { createPadSync } from './lib/pad-sync.js'\nimport { loadPadContent } from './lib/pad-content.js'\nimport { assertOpenPayload, contentUrlFrom, contentViewFrom, isMissingBindingError, isPadMissingError, isRetryableOpenError, openWithFrontmatterRecovery, padUrlFrom, syncSettingsFrom } from './lib/pad-open-flow.js'\nimport { buildPadFrameSrcdoc } from './lib/pad-frame-srcdoc.js'\nimport { isPadName, parsePadPathFromDavHref, parsePublicShareTokenFromLocation } from './lib/urls.js'\n\n// When nothing came back: our own sentence, not the browser's English.\nconst messageOf = (error, fallback) => requestErrorMessage(error, translate('Nextcloud did not answer. Check your connection and try again.'), fallback)\n\nconst component = {\n\tname: 'EtherpadNextcloudViewer',\n\tprops: {\n\t\tfilename: { type: String, required: false, default: '' },\n\t\tbasename: { type: String, required: false, default: '' },\n\t\tsource: { type: String, required: false, default: '' },\n\t\tfileid: { type: [String, Number], required: false, default: null },\n\t\tfileId: { type: [String, Number], required: false, default: null },\n\t\tfileInfo: { type: Object, required: false, default: null },\n\t},\n\tdata() {\n\t\treturn {\n\t\t\tiframeSrc: '',\n\t\t\tisLoading: true,\n\t\t\tloadError: '',\n\t\t\tcanRecover: false,\n\t\t\tpadLost: false,\n\t\t\tcanRetryOpen: false,\n\t\t\tmaybeStaleFileId: false,\n\t\t\t// Recovery may resolve this from the path when Viewer supplies no id.\n\t\t\trecoveryFileId: null,\n\t\t\t// Kept with the id so recovery invalidates the matching cache entry.\n\t\t\trecoveryPath: '',\n\t\t\tisRecovering: false,\n\t\t\tisCheckingOriginal: false,\n\t\t\toriginalPad: null,\n\t\t\texternalOpenUrl: '',\n\t\t\tcontentMode: '',\n\t\t\tcontentUrl: '',\n\t\t\tcontentState: 'idle',\n\t\t\tcontentError: '',\n\t\t\tcontent: { html: '', isEmpty: false },\n\t\t\t// A refresh keeps previously loaded content visible.\n\t\t\tcontentLoaded: false,\n\t\t\t// Refreshes supersede each other without superseding the open.\n\t\t\tcontentGeneration: 0,\n\t\t\tresolveGeneration: 0,\n\t\t}\n\t},\n\tcomputed: {\n\t\tsourcePath() {\n\t\t\t// Whitespace inside the DAV URL is encoded; only surrounding noise is trimmed.\n\t\t\tconst value = typeof this.source === 'string' ? this.source.trim() : ''\n\t\t\tif (!value) return ''\n\t\t\treturn parsePadPathFromDavHref(value) || ''\n\t\t},\n\t\tfilePath() {\n\t\t\t// Whitespace is part of the name, not noise: `Notes .pad` and\n\t\t\t// `Notes.pad` are two files, and trimming here opened the wrong one.\n\t\t\tconst normalizeDir = (dir) => {\n\t\t\t\tif (!dir || dir === '/') return '/'\n\t\t\t\treturn dir.startsWith('/') ? dir : ('/' + dir)\n\t\t\t}\n\t\t\tconst joinPath = (dir, name) => {\n\t\t\t\tif (!name) return ''\n\t\t\t\tif (name.startsWith('/')) return name\n\t\t\t\tconst normalizedDir = normalizeDir(dir)\n\t\t\t\treturn normalizedDir === '/' ? '/' + name : normalizedDir + '/' + name\n\t\t\t}\n\t\t\tif (isPadName(this.sourcePath)) return this.sourcePath\n\n\t\t\tconst info = this.fileInfo && typeof this.fileInfo === 'object' ? this.fileInfo : null\n\t\t\tconst infoPath = info && typeof info.path === 'string' ? info.path : ''\n\t\t\tif (isPadName(infoPath)) return infoPath.startsWith('/') ? infoPath : ('/' + infoPath)\n\n\t\t\tconst baseName = String(this.filename || this.basename || (info && (info.name || info.basename)) || '')\n\t\t\tif (!baseName) return ''\n\n\t\t\tconst infoDir = info && typeof info.dirname === 'string' ? info.dirname : ''\n\t\t\tif (infoDir) {\n\t\t\t\tconst combined = joinPath(infoDir, baseName)\n\t\t\t\tif (isPadName(combined)) return combined\n\t\t\t}\n\n\t\t\tconst params = new URLSearchParams(window.location.search || '')\n\t\t\tconst urlDir = params.get('dir') || '/'\n\t\t\tconst fromDir = joinPath(urlDir, baseName)\n\t\t\tif (isPadName(fromDir)) return fromDir\n\t\t\treturn '/' + baseName\n\t\t},\n\t\topenKey() {\n\t\t\treturn `${this.resolvedFileId === null ? '' : this.resolvedFileId}::${this.filePath}`\n\t\t},\n\t\tresolvedFileId() {\n\t\t\tconst candidates = [this.fileid, this.fileId, this.fileInfo && (this.fileInfo.fileid || this.fileInfo.fileId || this.fileInfo.id)]\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst numeric = Number(candidate)\n\t\t\t\tif (Number.isFinite(numeric) && numeric > 0) return numeric\n\t\t\t}\n\t\t\t// Route ids can outlive the item shown after Viewer navigation.\n\t\t\treturn null\n\t\t},\n\t},\n\twatch: {\n\t\t// A file swap changes path and id together; open it only once.\n\t\topenKey: { immediate: true, handler() { void this.resolveOpenUrl() } },\n\t},\n\tmethods: {\n\t\tasync fetchOpenPayload(url, init = {}) {\n\t\t\treturn assertOpenPayload(await fetchJsonWithTimeout(url, Object.assign({ method: 'GET' }, init)))\n\t\t},\n\t\tasync initializeMissingFrontmatter() {\n\t\t\tconst headers = {\n\t\t\t\tAccept: 'application/json',\n\t\t\t\trequesttoken: ocRequestToken(),\n\t\t\t}\n\n\t\t\t// A client timeout would not stop the server-side provisioning work.\n\t\t\tconst initOptions = { timeoutMs: null, fallbackMessage: 'Pad initialization failed.' }\n\n\t\t\tconst announceMigratedStatus = (data) => {\n\t\t\t\tif (data && data.status === 'migrated_from_legacy') {\n\t\t\t\t\tconsole.info('Legacy Ownpad .pad migrated to managed format on first open.')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.resolvedFileId !== null) {\n\t\t\t\tconst url = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/initialize-by-id/' + encodeURIComponent(String(this.resolvedFileId)))\n\t\t\t\tconst data = await fetchJsonWithTimeout(url, { method: 'POST', headers }, initOptions)\n\t\t\t\tannounceMigratedStatus(data)\n\t\t\t\treturn data\n\t\t\t}\n\n\t\t\tif (!this.filePath) {\n\t\t\t\tthrow new Error('Pad initialization failed: missing file path.')\n\t\t\t}\n\n\t\t\tconst body = new URLSearchParams()\n\t\t\tbody.set('file', this.filePath)\n\t\t\tconst url = ocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/initialize')\n\t\t\tconst data = await fetchJsonWithTimeout(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: Object.assign({}, headers, {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n\t\t\t\t}),\n\t\t\t\tbody: body.toString(),\n\t\t\t}, initOptions)\n\t\t\tannounceMigratedStatus(data)\n\t\t\treturn data\n\t\t},\n\t\t/** Resolve a fresh id for recovery without changing the opened file. */\n\t\tasync resolveRecoveryFileId(openPath) {\n\t\t\ttry {\n\t\t\t\tconst resolved = await apiResolvePadByPath(openPath, { bypassCache: true })\n\t\t\t\tconst id = Number(resolved && resolved.file_id)\n\t\t\t\treturn Number.isFinite(id) && id > 0 ? id : null\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\tmarkLoaded() {\n\t\t\tthis.$emit('update:loaded', true)\n\t\t},\n\t\t/**\n\t\t * See handFocusTo(). On the next tick, once the card is drawn: call\n\t\t * it after setting what the card shows.\n\t\t */\n\t\thandFocusToErrorCard() {\n\t\t\tthis.$nextTick(() => {\n\t\t\t\tconst card = this.$refs.errorCard\n\t\t\t\tif (card instanceof HTMLElement) {\n\t\t\t\t\thandFocusTo(card, card.querySelector('.epnc-native-error-message'))\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t// Keep the sync controller non-reactive and available to the immediate watcher.\n\t\tpadSync() {\n\t\t\tif (!this._padSync) {\n\t\t\t\tthis._padSync = createPadSync({ requestToken: () => ocRequestToken() })\n\t\t\t}\n\t\t\treturn this._padSync\n\t\t},\n\t\t// Do not create a controller solely to tear it down.\n\t\tteardownSync() {\n\t\t\tif (!this._padSync) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis._padSync.fireAndForget(true, true)\n\t\t\tthis._padSync.stop()\n\t\t\tthis._padSync.removeLifecycleHandlers()\n\t\t},\n\t\t/** $afterClick: see handFocusToErrorCard(). */\n\t\tasync resolveOpenUrl(afterClick = false) {\n\t\t\tconst generation = ++this.resolveGeneration\n\t\t\tconst isCurrent = () => generation === this.resolveGeneration\n\t\t\t// Discarding a result is insufficient: a completed request may mint a session.\n\t\t\tthis._openAbort?.abort()\n\t\t\tconst abort = typeof AbortController === 'function' ? new AbortController() : null\n\t\t\tthis._openAbort = abort\n\n\t\t\tthis.isLoading = true\n\t\t\tthis.loadError = ''\n\t\t\tthis.canRecover = false\n\t\t\tthis.padLost = false\n\t\t\tthis.canRetryOpen = false\n\t\t\tthis.maybeStaleFileId = false\n\t\t\tthis.recoveryFileId = null\n\t\t\tthis.recoveryPath = ''\n\t\t\tthis.isCheckingOriginal = false\n\t\t\tthis.originalPad = null\n\t\t\tthis.iframeSrc = ''\n\t\t\tthis.externalOpenUrl = ''\n\t\t\tthis.contentMode = ''\n\t\t\tthis.contentUrl = ''\n\t\t\tthis.contentState = 'idle'\n\t\t\tthis.contentError = ''\n\t\t\tthis.content = { html: '', isEmpty: false }\n\t\t\tthis.contentLoaded = false\n\t\t\tthis._contentAbort?.abort()\n\t\t\t// Do not construct a sync controller while resetting viewer state.\n\t\t\tif (this._padSync) {\n\t\t\t\tthis._padSync.stop()\n\t\t\t\tthis._padSync.configure({ syncUrl: '' })\n\t\t\t}\n\n\t\t\tif (!this.filePath) {\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.loadError = 'No .pad file selected.'\n\t\t\t\tthis.isLoading = false\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Viewer props may change before the watcher starts the next open.\n\t\t\tconst openPath = this.filePath\n\t\t\tconst publicToken = parsePublicShareTokenFromLocation()\n\t\t\tconst byPublicUrl = (() => {\n\t\t\t\tif (!publicToken) return ''\n\t\t\t\tconst url = new URL(ocGenerateUrl('/apps/' + APP_ID + '/api/v1/public/open/' + encodeURIComponent(publicToken)), window.location.origin)\n\t\t\t\t// The public endpoint rejects conflicting id and path locators.\n\t\t\t\tif (this.resolvedFileId !== null) {\n\t\t\t\t\turl.searchParams.set('fileId', String(this.resolvedFileId))\n\t\t\t\t} else {\n\t\t\t\t\turl.searchParams.set('file', openPath)\n\t\t\t\t}\n\t\t\t\treturn url.toString()\n\t\t\t})()\n\t\t\tconst openPostHeaders = {\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n\t\t\t\trequesttoken: ocRequestToken(),\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst fetchOpenData = async () => {\n\t\t\t\t\t// Never retry a refused id by path: it could identify a different file.\n\t\t\t\t\tconst signal = abort ? abort.signal : undefined\n\t\t\t\t\tif (byPublicUrl) {\n\t\t\t\t\t\treturn await this.fetchOpenPayload(byPublicUrl, { signal })\n\t\t\t\t\t}\n\t\t\t\t\t// One way in, chosen once. An open by id that retries by\n\t\t\t\t\t// path is how a refused id ended up opening whatever the\n\t\t\t\t\t// path pointed at.\n\t\t\t\t\tif (this.resolvedFileId !== null) {\n\t\t\t\t\t\tconst byIdBody = new URLSearchParams()\n\t\t\t\t\t\tbyIdBody.set('fileId', String(this.resolvedFileId))\n\t\t\t\t\t\treturn await this.fetchOpenPayload(\n\t\t\t\t\t\t\tocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/open-by-id'),\n\t\t\t\t\t\t\t{ method: 'POST', headers: openPostHeaders, body: byIdBody.toString(), signal },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst byPathBody = new URLSearchParams()\n\t\t\t\t\tbyPathBody.set('file', openPath)\n\t\t\t\t\treturn await this.fetchOpenPayload(\n\t\t\t\t\t\tocGenerateUrl('/apps/' + APP_ID + '/api/v1/pads/open'),\n\t\t\t\t\t\t{ method: 'POST', headers: openPostHeaders, body: byPathBody.toString(), signal },\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst data = await openWithFrontmatterRecovery({\n\t\t\t\t\topen: fetchOpenData,\n\t\t\t\t\tinitialize: () => this.initializeMissingFrontmatter(),\n\t\t\t\t\tstillWanted: isCurrent,\n\t\t\t\t})\n\t\t\t\tif (data === null || !isCurrent()) return\n\n\t\t\t\tconst { syncUrl, intervalMs } = syncSettingsFrom(data)\n\n\t\t\t\tthis.padSync().configure({ syncUrl, intervalMs })\n\t\t\t\tthis.padSync().installLifecycleHandlers()\n\t\t\t\tif (syncUrl) {\n\t\t\t\t\tthis.padSync().start()\n\t\t\t\t}\n\n\t\t\t\tconst contentUrl = contentUrlFrom(data)\n\n\t\t\t\tconst { isContentView, externalUrl } = contentViewFrom(data)\n\t\t\t\tif (isContentView) {\n\t\t\t\t\tthis.externalOpenUrl = externalUrl\n\t\t\t\t\tthis.contentUrl = contentUrl\n\t\t\t\t\tthis.contentMode = 'content'\n\t\t\t\t\tthis.markLoaded()\n\t\t\t\t\t// Draw the content view while its body loads.\n\t\t\t\t\tvoid this.loadContent()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tthis.iframeSrc = padUrlFrom(data)\n\t\t\t\tthis.markLoaded()\n\t\t\t} catch (error) {\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.loadError = messageOf(error, 'Could not load pad.')\n\t\t\t\t// The server intentionally does not disclose why this id is unavailable.\n\t\t\t\tthis.maybeStaleFileId = this.resolvedFileId !== null\n\t\t\t\t\t&& Boolean(error) && error.status === 404 && !error.code\n\t\t\t\tthis.canRetryOpen = isRetryableOpenError(error)\n\t\t\t\t// Recovery may resolve only the same path that failed to open.\n\t\t\t\tlet recoveryFileId = this.resolvedFileId\n\t\t\t\tthis.recoveryPath = openPath\n\t\t\t\tconst recoverable = isMissingBindingError(error) || isPadMissingError(error)\n\t\t\t\tif (recoveryFileId === null && !byPublicUrl && recoverable) {\n\t\t\t\t\trecoveryFileId = await this.resolveRecoveryFileId(openPath)\n\t\t\t\t\t// A late lookup must not attach recovery to a newer Viewer item.\n\t\t\t\t\tif (!isCurrent()) return\n\t\t\t\t}\n\t\t\t\tthis.recoveryFileId = recoveryFileId\n\t\t\t\tthis.padLost = isPadMissingError(error)\n\t\t\t\tthis.canRecover = recoverable\n\t\t\t\t\t&& recoveryFileId !== null\n\t\t\t\t\t&& !byPublicUrl\n\t\t\t\tif (this.canRecover && !this.padLost) {\n\t\t\t\t\tthis.fetchOriginalPadHint(isCurrent, afterClick)\n\t\t\t\t} else if (afterClick) {\n\t\t\t\t\tthis.handFocusToErrorCard()\n\t\t\t\t}\n\t\t\t\tthis.markLoaded()\n\t\t\t} finally {\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.isLoading = false\n\t\t\t}\n\t\t},\n\t\t/** $afterClick: the focus waits for the card's final actions. */\n\t\tasync fetchOriginalPadHint(isCurrent, afterClick = false) {\n\t\t\tif (this.recoveryFileId === null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.isCheckingOriginal = true\n\t\t\ttry {\n\t\t\t\tconst hint = await apiFindOriginalPad(this.recoveryFileId)\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tif (hint && hint.found === true && typeof hint.viewer_url === 'string' && hint.viewer_url !== '') {\n\t\t\t\t\tthis.originalPad = {\n\t\t\t\t\t\tviewerUrl: hint.viewer_url,\n\t\t\t\t\t\tpath: typeof hint.path === 'string' ? hint.path : '',\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Recovery remains available without an original-file hint.\n\t\t\t} finally {\n\t\t\t\tif (isCurrent()) {\n\t\t\t\t\tthis.isCheckingOriginal = false\n\t\t\t\t\tif (afterClick) {\n\t\t\t\t\t\tthis.handFocusToErrorCard()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync recoverFromSnapshot() {\n\t\t\tif (!this.canRecover || this.isRecovering || this.recoveryFileId === null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.isRecovering = true\n\t\t\ttry {\n\t\t\t\tawait apiRecoverFromSnapshot(this.recoveryFileId, this.recoveryPath)\n\t\t\t\tthis.loadError = ''\n\t\t\t\tthis.canRecover = false\n\t\t\t\tawait this.resolveOpenUrl(true)\n\t\t\t} catch (error) {\n\t\t\t\t// No answer: the pad may be set up by now, and another\n\t\t\t\t// recovery would meet it. Opening tells, and is safe to repeat.\n\t\t\t\tif (isUnanswered(error)) {\n\t\t\t\t\tawait this.resolveOpenUrl(true)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Enabled again before the card is drawn, so the focus lands.\n\t\t\t\tthis.isRecovering = false\n\t\t\t\tthis.loadError = messageOf(error, 'Could not load pad.')\n\t\t\t\t// The clicked button lost the focus while it was disabled.\n\t\t\t\tthis.handFocusToErrorCard()\n\t\t\t} finally {\n\t\t\t\tthis.isRecovering = false\n\t\t\t}\n\t\t},\n\t\t/** Refresh content through an endpoint that re-checks access. */\n\t\tasync loadContent() {\n\t\t\tconst openGeneration = this.resolveGeneration\n\t\t\tthis.contentGeneration += 1\n\t\t\tconst generation = this.contentGeneration\n\t\t\tconst isCurrent = () => generation === this.contentGeneration\n\t\t\t\t&& openGeneration === this.resolveGeneration\n\n\t\t\tif (this.contentUrl === '') {\n\t\t\t\tthis.contentState = 'error'\n\t\t\t\tthis.contentError = translate('The server did not say where to load this pad from.')\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tthis._contentAbort?.abort()\n\t\t\t// Abort superseded content refreshes.\n\t\t\tconst abort = typeof AbortController === 'function' ? new AbortController() : null\n\t\t\tthis._contentAbort = abort\n\t\t\tthis.contentState = 'loading'\n\t\t\tthis.contentError = ''\n\n\t\t\ttry {\n\t\t\t\tconst content = await loadPadContent(this.contentUrl, { signal: abort?.signal })\n\t\t\t\tif (!isCurrent()) return\n\t\t\t\tthis.content = content\n\t\t\t\tthis.contentLoaded = true\n\t\t\t\tthis.contentState = 'ready'\n\t\t\t} catch (error) {\n\t\t\t\tif (!isCurrent() || (error && error.name === 'AbortError')) return\n\t\t\t\tthis.contentState = 'error'\n\t\t\t\tthis.contentError = messageOf(error, translate('Could not load the pad content.'))\n\t\t\t}\n\t\t},\n\t\trenderContentView(createElement, options) {\n\t\t\tconst extraActions = Array.isArray(options.actions) ? options.actions : []\n\t\t\tconst isBusy = this.contentState === 'loading'\n\n\t\t\treturn createElement('div', { class: 'epnc-pad-doc' }, [\n\t\t\t\tcreateElement('div', { class: 'epnc-pad-doc__inner' }, [\n\t\t\t\t\tcreateElement('div', { class: 'epnc-pad-doc__toolbar' }, [\n\t\t\t\t\t\t(this.contentState === 'error' && this.contentLoaded)\n\t\t\t\t\t\t\t? createElement('span', { class: 'epnc-pad-doc__toolbar-error' },\n\t\t\t\t\t\t\t\tthis.contentError || translate('Could not load the pad content.'))\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\t\tclass: 'button epnc-pad-doc__refresh',\n\t\t\t\t\t\t\tattrs: { type: 'button', disabled: isBusy },\n\t\t\t\t\t\t\ton: { click: () => { void this.loadContent() } },\n\t\t\t\t\t\t}, isBusy ? translate('Refreshing...') : translate('Refresh')),\n\t\t\t\t\t\t...extraActions,\n\t\t\t\t\t]),\n\t\t\t\t\tthis.renderContentBody(createElement),\n\t\t\t\t]),\n\t\t\t])\n\t\t},\n\t\trenderContentBody(createElement) {\n\t\t\tif (this.contentLoaded && this.contentState !== 'ready') {\n\t\t\t\treturn this.renderContentText(createElement)\n\t\t\t}\n\t\t\tif (this.contentState === 'error') {\n\t\t\t\treturn createElement('div', { class: 'epnc-pad-doc__text epnc-pad-doc__status' }, [\n\t\t\t\t\tcreateElement('div', {},\n\t\t\t\t\t\tthis.contentError || translate('Could not load the pad content.')),\n\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\tclass: 'button primary',\n\t\t\t\t\t\tattrs: { type: 'button' },\n\t\t\t\t\t\ton: { click: () => { void this.loadContent() } },\n\t\t\t\t\t}, translate('Try again')),\n\t\t\t\t])\n\t\t\t}\n\t\t\tif (this.contentState !== 'ready') {\n\t\t\t\treturn createElement('div', { class: 'epnc-pad-doc__text epnc-pad-doc__status' }, translate('Loading pad content...'))\n\t\t\t}\n\t\t\treturn this.renderContentText(createElement)\n\t\t},\n\t\trenderContentText(createElement) {\n\t\t\tif (this.content.isEmpty) {\n\t\t\t\treturn createElement('div', { class: 'epnc-pad-doc__text epnc-pad-doc__status' }, translate('This pad is still empty.'))\n\t\t\t}\n\t\t\treturn createElement('div', {\n\t\t\t\tclass: 'epnc-pad-doc__text epnc-pad-doc__text--html',\n\t\t\t\tdomProps: { innerHTML: this.content.html },\n\t\t\t})\n\t\t},\n\t},\n\tbeforeDestroy() {\n\t\tthis.resolveGeneration += 1\n\t\t// Abort work that could otherwise finish after teardown.\n\t\tthis._openAbort?.abort()\n\t\tthis._contentAbort?.abort()\n\t\tthis.teardownSync()\n\t},\n\tbeforeUnmount() {\n\t\tthis.resolveGeneration += 1\n\t\tthis._openAbort?.abort()\n\t\tthis._contentAbort?.abort()\n\t\tthis.teardownSync()\n\t},\n\trender(createElement) {\n\t\tif (this.loadError) {\n\t\t\tconst cardChildren = [\n\t\t\t\tcreateElement('div', { class: 'epnc-native-error-title' }, translate('Could not open pad')),\n\t\t\t\t// Read out when it appears, not only when someone looks.\n\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message', attrs: { role: 'alert' } }, this.loadError),\n\t\t\t]\n\t\t\tif (this.maybeStaleFileId) {\n\t\t\t\tcardChildren.push(\n\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\ttranslate('This file may have been moved or replaced since the list was loaded. Reload the page and open it again.')),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.canRetryOpen) {\n\t\t\t\tcardChildren.push(\n\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\tattrs: { type: 'button' },\n\t\t\t\t\t\ton: { click: () => { void this.resolveOpenUrl(true) } },\n\t\t\t\t\t}, translate('Try again')),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.canRecover && this.padLost) {\n\t\t\t\t// The message says what happened; the file is the original.\n\t\t\t\tcardChildren.push(\n\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\tattrs: { type: 'button', disabled: this.isRecovering },\n\t\t\t\t\t\ton: { click: () => { void this.recoverFromSnapshot() } },\n\t\t\t\t\t}, this.isRecovering ? translate('Creating new pad...') : translate('Create new pad from this file')),\n\t\t\t\t)\n\t\t\t} else if (this.canRecover) {\n\t\t\t\tif (this.isCheckingOriginal) {\n\t\t\t\t\t// Wait before choosing the primary recovery action.\n\t\t\t\t\tcardChildren.push(\n\t\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\t\ttranslate('Checking for the original pad...')),\n\t\t\t\t\t)\n\t\t\t\t} else if (this.originalPad) {\n\t\t\t\t\tcardChildren.push(\n\t\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\t\ttranslate('This file looks like a copy of an existing .pad file in your account. Open the original to keep editing the linked pad, or create a new pad to fork the content stored in this file.')),\n\t\t\t\t\t\tcreateElement('a', {\n\t\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\t\tattrs: { href: this.originalPad.viewerUrl },\n\t\t\t\t\t\t}, translate('Open the original .pad file')),\n\t\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\t\tclass: 'button epnc-native-error-action',\n\t\t\t\t\t\t\tattrs: { type: 'button', disabled: this.isRecovering },\n\t\t\t\t\t\t\ton: { click: () => { void this.recoverFromSnapshot() } },\n\t\t\t\t\t\t}, this.isRecovering ? translate('Creating new pad...') : translate('Create new pad from this file')),\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tcardChildren.push(\n\t\t\t\t\t\tcreateElement('div', { class: 'epnc-native-error-message' },\n\t\t\t\t\t\t\ttranslate(\"We couldn't find a matching pad in this Nextcloud. You can create a new pad from the text stored in this file; from then on, opening this file will load the new pad.\")),\n\t\t\t\t\t\tcreateElement('button', {\n\t\t\t\t\t\t\tclass: 'button primary epnc-native-error-action',\n\t\t\t\t\t\t\tattrs: { type: 'button', disabled: this.isRecovering },\n\t\t\t\t\t\t\ton: { click: () => { void this.recoverFromSnapshot() } },\n\t\t\t\t\t\t}, this.isRecovering ? translate('Creating new pad...') : translate('Create new pad from this file')),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn createElement('div', { class: 'epnc-native-status epnc-native-status--error' }, [\n\t\t\t\tcreateElement('div', { class: 'epnc-native-error-card', ref: 'errorCard' }, cardChildren),\n\t\t\t])\n\t\t}\n\t\tif (this.contentMode === 'content') {\n\t\t\treturn this.renderContentView(createElement, this.externalOpenUrl === ''\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\tactions: [\n\t\t\t\t\t\tcreateElement('a', {\n\t\t\t\t\t\t\tclass: 'button epnc-pad-doc__link',\n\t\t\t\t\t\t\tattrs: {\n\t\t\t\t\t\t\t\thref: this.externalOpenUrl,\n\t\t\t\t\t\t\t\ttarget: '_blank',\n\t\t\t\t\t\t\t\trel: 'noopener noreferrer',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}, translate('Open original pad')),\n\t\t\t\t\t],\n\t\t\t\t})\n\t\t}\n\t\tif (this.isLoading || !this.iframeSrc) {\n\t\t\treturn createElement('div', { class: 'epnc-native-status' }, 'Loading pad...')\n\t\t}\n\n\t\treturn createElement('div', { class: 'epnc-native-shell' }, [\n\t\t\t// Nextcloud inspects direct iframe children, so keep this wrapper same-origin.\n\t\t\tcreateElement('iframe', {\n\t\t\t\tattrs: { srcdoc: buildPadFrameSrcdoc(this.iframeSrc), title: 'Etherpad' },\n\t\t\t\t// Etherpad provides its own loading state inside the nested iframe.\n\t\t\t\ton: { load: () => this.markLoaded(), error: () => this.markLoaded() },\n\t\t\t\tclass: 'epnc-native-iframe',\n\t\t\t}),\n\t\t])\n\t},\n}\n\nexport default component\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/** Registers the pad MIME handler with the Viewer. */\n\nimport { registerHandler } from '@nextcloud/viewer'\n\nimport { MIME, VIEWER_HANDLER_ID } from './lib/constants.js'\nimport component from './viewer-main.js'\n\n// The options object itself, not a loader for it: the Viewer assigns its\n// Mime mixin onto what it is given and registers it under `component.name`,\n// and a function silently takes neither.\nregisterHandler({ id: VIEWER_HANDLER_ID, mimes: [MIME], component })\n"],"names":["registerHandler","handler","validateHandler","id","mimes","mimesAliases","component","RESOLVE_CACHE","RESOLVE_CACHE_MAX_ENTRIES","RESOLVE_CACHE_TTL_MS","apiResolvePadByPath","path","bypassCache","cacheKey","cached","getResolveCache","url","ocGenerateUrl","APP_ID","request","fetchJson","error","setResolveCache","apiFindOriginalPad","fileId","endpoint","apiRecoverFromSnapshot","result","fetchJsonWithTimeout","ocRequestToken","oldestKey","options","fallbackMessage","escapeAttribute","value","ALLOWED_PAD_URL_SCHEMES","isSafePadUrl","parsed","SRC_DOC_CSP","buildPadFrameSrcdoc","safeUrl","messageOf","fallback","requestErrorMessage","translate","parsePadPathFromDavHref","normalizeDir","dir","joinPath","name","normalizedDir","isPadName","info","infoPath","baseName","infoDir","combined","urlDir","fromDir","candidates","candidate","numeric","init","assertOpenPayload","headers","initOptions","announceMigratedStatus","data","body","openPath","resolved","card","handFocusTo","createPadSync","afterClick","generation","isCurrent","abort","publicToken","parsePublicShareTokenFromLocation","byPublicUrl","openPostHeaders","openWithFrontmatterRecovery","signal","byIdBody","byPathBody","syncUrl","intervalMs","syncSettingsFrom","contentUrl","contentUrlFrom","isContentView","externalUrl","contentViewFrom","padUrlFrom","isRetryableOpenError","recoveryFileId","recoverable","isMissingBindingError","isPadMissingError","hint","isUnanswered","openGeneration","content","loadPadContent","createElement","extraActions","isBusy","cardChildren","VIEWER_HANDLER_ID","MIME"],"mappings":"+SAYO,SAASA,EAAgBC,EAAS,CAGrC,GAFAC,EAAgBD,CAAO,EACvB,OAAO,uBAAyB,OAAO,qBAAuB,IAAI,KAC9D,OAAO,qBAAqB,IAAIA,EAAQ,EAAE,EAAG,CAC7C,QAAQ,KAAK,mBAAmBA,EA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AAK,aAAe7D,EAAU,qBAAqB,EAAIA,EAAU,+BAA+B,CAAC,CAC1G,GAGU6D,EAAc,MAAO,CAAE,MAAO,8CAA8C,EAAI,CACtFA,EAAc,MAAO,CAAE,MAAO,yBAA0B,IAAK,WAAW,EAAIG,CAAY,CAC5F,CAAI,CACF,CACA,OAAI,KAAK,cAAgB,UACjB,KAAK,kBAAkBH,EAAe,KAAK,kBAAoB,GACnE,CAAA,EACA,CACD,QAAS,CACRA,EAAc,IAAK,CAClB,MAAO,4BACP,MAAO,CACN,KAAM,KAAK,gBACX,OAAQ,SACR,IAAK,qBACb,CACA,EAAS7D,EAAU,mBAAmB,CAAC,CACvC,CACA,CAAK,EAEC,KAAK,WAAa,CAAC,KAAK,UACpB6D,EAAc,MAAO,CAAE,MAAO,oBAAoB,EAAI,gBAAgB,EAGvEA,EAAc,MAAO,CAAE,MAAO,mBAAmB,EAAI,CAE3DA,EAAc,SAAU,CACvB,MAAO,CAAE,OAAQlE,GAAoB,KAAK,SAAS,EAAG,MAAO,UAAU,EAEvE,GAAI,CAAE,KAAM,IAAM,KAAK,WAAU,EAAI,MAAO,IAAM,KAAK,YAAY,EACnE,MAAO,oBACX,CAAI,CACJ,CAAG,CACF,CACD,ECvkBAvC,EAAgB,CAAE,GAAI6G,EAAmB,MAAO,CAACC,CAAI,EAAG,UAAAxG,EAAS,CAAE","x_google_ignoreList":[0]} \ No newline at end of file diff --git a/js/pad-open-flow-By_FzSKk.chunk.mjs b/js/pad-open-flow-_qELVjOV.chunk.mjs similarity index 84% rename from js/pad-open-flow-By_FzSKk.chunk.mjs rename to js/pad-open-flow-_qELVjOV.chunk.mjs index e1d60699..39e9779c 100644 --- a/js/pad-open-flow-By_FzSKk.chunk.mjs +++ b/js/pad-open-flow-_qELVjOV.chunk.mjs @@ -1,4 +1,4 @@ -import{f as jn,a as Wn}from"./fetch-helpers-BUxbvlK6.chunk.mjs";const Bn=12e4;function Io({requestToken:t,fetchImpl:r}={}){const a=typeof r=="function"?r:(...S)=>window.fetch(...S),l=typeof t=="function"?t:()=>"";let u="",g=Bn,b=null,Y=!1,E=!1,G=!1,q=null,L=null,O=null;const je=({syncUrl:S,intervalMs:M}={})=>{typeof S=="string"&&(u=S),Number.isFinite(M)&&M>0&&(g=M)},Z=()=>{q!==null&&(window.clearInterval(q),q=null)},be=()=>{!u||q!==null||(q=window.setInterval(()=>{document.visibilityState==="visible"&&le(!1,!1)},g))},le=(S,M)=>{I(S,M).catch(()=>{})},I=async(S,M)=>{if(!u)return{status:"disabled"};if(b)return S&&!Y?(E=!0,G=G||!!M,b.catch(()=>{}).then(()=>I(!0,G))):b;Y=!!S;const J=(async()=>{const ee=S?u+(u.includes("?")?"&":"?")+"force=1":u,v=await a(ee,{method:"POST",credentials:"same-origin",headers:{Accept:"application/json",requesttoken:l()},keepalive:!!M}),z=await v.json().catch(()=>({}));if(!v.ok)throw new Error(z&&z.message||"Sync request failed.");return z})();b=J;let U,F=null;try{U=await J}catch(ee){F=ee}finally{b===J&&(b=null),Y=!1}const ce=E,Q=G;if(E=!1,G=!1,ce)return I(!0,Q);if(F instanceof Error)throw F;return U};return{configure:je,start:be,stop:Z,sync:I,fireAndForget:le,installLifecycleHandlers:()=>{L||O||(L=()=>{if(document.visibilityState==="hidden"){le(!0,!0),Z();return}be()},O=()=>{le(!0,!0),Z()},document.addEventListener("visibilitychange",L),window.addEventListener("pagehide",O))},removeLifecycleHandlers:()=>{L&&(document.removeEventListener("visibilitychange",L),L=null),O&&(window.removeEventListener("pagehide",O),O=null)}}}const Mo=(t,r,{preventScroll:a=!1}={})=>{const l=(t instanceof HTMLElement?t.querySelector("a, button"):null)||r;l instanceof HTMLElement&&(l===r&&(l.tabIndex=-1),l.focus({preventScroll:a}))};function Gt(t,r){(r==null||r>t.length)&&(r=t.length);for(var a=0,l=Array(r);a2?a-2:0),u=2;u1?r-1:0),l=1;l"u"?null:T(BigInt.prototype.toString),Zt=typeof Symbol>"u"?null:T(Symbol.prototype.toString),D=T(Object.prototype.hasOwnProperty),_e=T(Object.prototype.toString),N=T(RegExp.prototype.test),ie=oo(TypeError);function T(t){return function(r){r instanceof RegExp&&(r.lastIndex=0);for(var a=arguments.length,l=new Array(a>1?a-1:0),u=1;u2&&arguments[2]!==void 0?arguments[2]:Ne;if(qt&&qt(t,null),!ye(r))return t;let l=r.length;for(;l--;){let u=r[l];if(typeof u=="string"){const g=a(u);g!==u&&($n(r)||(r[l]=g),u=g)}t[u]=!0}return t}function ro(t){for(let r=0;r/g),fo=A(/\${[\w\W]*/g),mo=A(/^data-[\-\w.\u00B7-\uFFFF]+$/),po=A(/^aria-[\-\w]+$/),nn=A(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ho=A(/^(?:\w+script|data):/i),go=A(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),yo=A(/^html$/i),bo=A(/^[a-z][.\w]*(-[.\w]+)+$/i),on=A(/<[/\w!]/g),rn=A(/<[/\w]/g),To=A(/<\/no(script|embed|frames)/i),wo=A(/\/>/i),k={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},sn=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],Ao=w(m({},sn)),Eo=(function(){const t={};return ae(sn,r=>{t[r]=A(new RegExp("])","i"))}),w(t)})(),So=function(){return typeof window>"u"?null:window},vo=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let a=null;const l="data-tt-policy-suffix";r&&r.hasAttribute(l)&&(a=r.getAttribute(l));const u="dompurify"+(a?"#"+a:"");try{return t.createPolicy(u,{createHTML(g){return g},createScriptURL(g){return g}})}catch{return console.warn("TrustedTypes policy "+u+" could not be created."),null}},an=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},K=function(t,r,a,l){return D(t,r)&&ye(t[r])?m(l.base?R(l.base):{},t[r],l.transform):a},st=function(t,r,a){const l=D(t,r)?t[r]:void 0;return l&&typeof l=="object"?R(l):a()};function un(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:So();const r=e=>un(e);if(r.version="3.4.15",r.removed=[],!t||!t.document||t.document.nodeType!==k.document||!t.Element)return r.isSupported=!1,r;let a=t.document;const l=a,u=l.currentScript;t.DocumentFragment;const g=t.HTMLTemplateElement,b=t.Node,Y=t.Element,E=t.NodeFilter;t.NamedNodeMap===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const q=t.DOMParser,L=t.trustedTypes,O=Y.prototype,je=C(O,"cloneNode"),Z=C(O,"remove"),be=C(O,"removeAttributeNode"),le=C(O,"nextSibling"),I=C(O,"childNodes"),S=C(O,"parentNode"),M=C(O,"shadowRoot"),J=C(O,"attributes"),U=b&&b.prototype?C(b.prototype,"nodeType"):null,F=b&&b.prototype?C(b.prototype,"nodeName"):null,ce=b&&b.prototype?C(b.prototype,"ownerDocument"):null,Q=function(e){return U?U(e):e.nodeType},ee=function(e){return F?F(e):e.nodeName};if(typeof g=="function"){const e=a.createElement("template");e.content&&e.content.ownerDocument&&(a=e.content.ownerDocument)}let v,z="",We,mt=!1,Te=0;const pt=function(){if(Te>0)throw ie('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},se=function(e){pt(),Te++;try{return v.createHTML(e)}finally{Te--}},pn=function(e){pt(),Te++;try{return v.createScriptURL(e)}finally{Te--}},dn=function(){return mt||(We=vo(L,u),mt=!0),We},Oe=a,Be=Oe.implementation,dt=Oe.createNodeIterator,hn=Oe.createDocumentFragment,gn=Oe.getElementsByTagName,yn=l.importNode;let p=an();r.isSupported=typeof ln=="function"&&typeof S=="function"&&Be&&Be.createHTMLDocument!==void 0;const bn=so,Tn=uo,wn=fo,An=mo,En=po,Sn=ho,ht=go,vn=bo;let gt=nn,d=null;const Ye=m({},[...Jt,...it,...at,...lt,...Qt]);let h=null;const Ge=m({},[...en,...ct,...tn,...He]);let H=Object.seal(ge(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),we=null,yt=null;const V=Object.seal(ge(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let bt=!0,qe=!0,Tt=!1,wt=!0,X=!1,te=!0,ne=!1,Ve=!1,xe=null,De=null,Xe=!1,ue=!1,ke=!1,Re=!1,At=!0,Et=!1;const St="user-content-";let $e=!0,Ke=!1,fe={},me=null;const vt=m({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let _t=null;const Nt=m({},["audio","video","img","source","image","track"]);let Ot=null;const xt=m({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ce="http://www.w3.org/1998/Math/MathML",Le="http://www.w3.org/2000/svg",j="http://www.w3.org/1999/xhtml";let pe=j,Ze=!1,Je=null;const _n=m({},[Ce,Le,j],rt),Dt=w(["mi","mo","mn","ms","mtext"]);let Qe=m({},Dt);const kt=w(["annotation-xml"]);let et=m({},kt);const Nn=m({},["title","style","font","a","script"]);let Ae=null;const On=["application/xhtml+xml","text/html"],xn="text/html";let y=null,de=null;const Dn=a.createElement("form"),Rt=function(e){return e instanceof RegExp||e instanceof Function},tt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(de&&de===e)return;(!e||typeof e!="object")&&(e={}),e=R(e),Ae=On.indexOf(e.PARSER_MEDIA_TYPE)===-1?xn:e.PARSER_MEDIA_TYPE,y=Ae==="application/xhtml+xml"?rt:Ne,d=K(e,"ALLOWED_TAGS",Ye,{transform:y}),h=K(e,"ALLOWED_ATTR",Ge,{transform:y}),Je=K(e,"ALLOWED_NAMESPACES",_n,{transform:rt}),Ot=K(e,"ADD_URI_SAFE_ATTR",xt,{transform:y,base:xt}),_t=K(e,"ADD_DATA_URI_TAGS",Nt,{transform:y,base:Nt}),me=K(e,"FORBID_CONTENTS",vt,{transform:y}),we=K(e,"FORBID_TAGS",R({}),{transform:y}),yt=K(e,"FORBID_ATTR",R({}),{transform:y}),fe=D(e,"USE_PROFILES")?e.USE_PROFILES&&typeof e.USE_PROFILES=="object"?R(e.USE_PROFILES):e.USE_PROFILES:!1,bt=e.ALLOW_ARIA_ATTR!==!1,qe=e.ALLOW_DATA_ATTR!==!1,Tt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,wt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,X=e.SAFE_FOR_TEMPLATES||!1,te=e.SAFE_FOR_XML!==!1,ne=e.WHOLE_DOCUMENT||!1,ue=e.RETURN_DOM||!1,ke=e.RETURN_DOM_FRAGMENT||!1,Re=e.RETURN_TRUSTED_TYPE||!1,Xe=e.FORCE_BODY||!1,At=e.SANITIZE_DOM!==!1,Et=e.SANITIZE_NAMED_PROPS||!1,$e=e.KEEP_CONTENT!==!1,Ke=e.IN_PLACE||!1,gt=ao(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:nn,pe=typeof e.NAMESPACE=="string"?e.NAMESPACE:j,Qe=st(e,"MATHML_TEXT_INTEGRATION_POINTS",()=>m({},Dt)),et=st(e,"HTML_INTEGRATION_POINTS",()=>m({},kt));const n=st(e,"CUSTOM_ELEMENT_HANDLING",()=>ge(null));if(H=ge(null),D(n,"tagNameCheck")&&Rt(n.tagNameCheck)&&(H.tagNameCheck=n.tagNameCheck),D(n,"attributeNameCheck")&&Rt(n.attributeNameCheck)&&(H.attributeNameCheck=n.attributeNameCheck),D(n,"allowCustomizedBuiltInElements")&&typeof n.allowCustomizedBuiltInElements=="boolean"&&(H.allowCustomizedBuiltInElements=n.allowCustomizedBuiltInElements),A(H),X&&(qe=!1),ke&&(ue=!0),fe&&(d=m({},Qt),h=ge(null),fe.html===!0&&(m(d,Jt),m(h,en)),fe.svg===!0&&(m(d,it),m(h,ct),m(h,He)),fe.svgFilters===!0&&(m(d,at),m(h,ct),m(h,He)),fe.mathMl===!0&&(m(d,lt),m(h,tn),m(h,He))),V.tagCheck=null,V.attributeCheck=null,D(e,"ADD_TAGS")&&(typeof e.ADD_TAGS=="function"?V.tagCheck=e.ADD_TAGS:ye(e.ADD_TAGS)&&(d===Ye&&(d=R(d)),m(d,e.ADD_TAGS,y))),D(e,"ADD_ATTR")&&(typeof e.ADD_ATTR=="function"?V.attributeCheck=e.ADD_ATTR:ye(e.ADD_ATTR)&&(h===Ge&&(h=R(h)),m(h,e.ADD_ATTR,y))),D(e,"ADD_FORBID_CONTENTS")&&ye(e.ADD_FORBID_CONTENTS)&&(me===vt&&(me=R(me)),m(me,e.ADD_FORBID_CONTENTS,y)),$e&&(d["#text"]=!0),ne&&m(d,["html","head","body"]),d.table&&(m(d,["tbody"]),delete we.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!="function")throw ie('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ie('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const o=v;v=e.TRUSTED_TYPES_POLICY;try{z=se("")}catch(i){throw v=o,i}}else e.TRUSTED_TYPES_POLICY===null?(v=void 0,z=""):(v===void 0&&(v=dn()),v&&typeof z=="string"&&(z=se("")));w&&w(e),de=e},Ct=m({},[...it,...at,...lo]),Lt=m({},[...lt,...co]),kn=function(e,n,o){return n.namespaceURI===j?e==="svg":n.namespaceURI===Ce?e==="svg"&&(o==="annotation-xml"||Qe[o]):!!Ct[e]},Rn=function(e,n,o){return n.namespaceURI===j?e==="math":n.namespaceURI===Le?e==="math"&&et[o]:!!Lt[e]},Cn=function(e,n,o){return n.namespaceURI===Le&&!et[o]||n.namespaceURI===Ce&&!Qe[o]?!1:!Lt[e]&&(Nn[e]||!Ct[e])},Ln=function(e){let n=S(e);(!n||!n.tagName)&&(n={namespaceURI:pe,tagName:"template"});const o=Ne(e.tagName),i=Ne(n.tagName);return Je[e.namespaceURI]?e.namespaceURI===Le?kn(o,n,i):e.namespaceURI===Ce?Rn(o,n,i):e.namespaceURI===j?Cn(o,n,i):!!(Ae==="application/xhtml+xml"&&Je[e.namespaceURI]):!1},oe=function(e){Se(r.removed,{element:e});try{S(e).removeChild(e)}catch{if(Z(e),!S(e))throw ie("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},It=function(e,n,o){try{be(e,n)}catch{try{e.removeAttribute(o)}catch{}}},Ie=function(e){Me(e);const n=I(e);if(n){const i=[];ae(n,c=>{Se(i,c)}),ae(i,c=>{try{Z(c)}catch{}})}const o=J(e);if(o)for(let i=o.length-1;i>=0;--i){const c=o[i],s=c&&c.name;typeof s=="string"&&It(e,c,s)}},re=function(e,n,o){if(!o)try{o=n.getAttributeNode(e)}catch{o=null}Se(r.removed,{attribute:o||null,from:n});try{o?be(n,o):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e==="is")if(ue||ke)try{oe(n)}catch{}else try{n.setAttribute(e,"")}catch{}},In=function(e){const n=J(e);if(n)for(let o=n.length-1;o>=0;--o){const i=n[o],c=i&&i.name;typeof c!="string"||h[y(c)]||It(e,i,c)}},Me=function(e){const n=[e];for(;n.length>0;){const o=n.pop();Q(o)===k.element&&In(o);const i=I(o);if(i)for(let c=i.length-1;c>=0;--c)n.push(i[c])}},Mt=function(e,n){return te?e==="patchsrc"?!0:e==="for"&&n!=="label"&&n!=="output":!1},Mn=function(e){if(!te)return;const n=[e];for(;n.length>0;){const o=n.pop(),i=Q(o);if(i===k.processingInstruction||i===k.comment&&N(rn,o.data)){try{Z(o)}catch{}continue}if(i===k.element){const s=o,f=y(ee(o));try{s.hasAttribute&&s.hasAttribute("patchsrc")&&s.removeAttribute("patchsrc"),s.hasAttribute&&s.hasAttribute("for")&&Mt("for",f)&&s.removeAttribute("for")}catch{}}const c=I(o);if(c)for(let s=c.length-1;s>=0;--s)n.push(c[s])}},zt=function(e){let n=null,o=null;if(Xe)e=""+e;else{const s=Xt(e,/^[\r\n\t ]+/);o=s&&s[0]}Ae==="application/xhtml+xml"&&pe===j&&(e=''+e+"");const i=v?se(e):e;if(pe===j)try{n=new q().parseFromString(i,Ae)}catch{}if(!n||!n.documentElement){n=Be.createDocument(pe,"template",null);try{n.documentElement.innerHTML=Ze?z:i}catch{}}const c=n.body||n.documentElement;return e&&o&&c.insertBefore(a.createTextNode(o),c.childNodes[0]||null),pe===j?gn.call(n,ne?"html":"body")[0]:ne?n.documentElement:c},Pt=function(e){const n=ce?ce(e):e.ownerDocument;return dt.call(n||e,e,E.SHOW_ELEMENT|E.SHOW_COMMENT|E.SHOW_TEXT|E.SHOW_PROCESSING_INSTRUCTION|E.SHOW_CDATA_SECTION,null)},ze=function(e){return e=ve(e,bn," "),e=ve(e,Tn," "),e=ve(e,wn," "),e},nt=function(e){var n;e.normalize();const o=ce?ce(e):e.ownerDocument,i=dt.call(o||e,e,E.SHOW_TEXT|E.SHOW_COMMENT|E.SHOW_CDATA_SECTION|E.SHOW_PROCESSING_INSTRUCTION,null);let c=i.nextNode();for(;c;)c.data=ze(c.data),c=i.nextNode();const s=(n=e.querySelectorAll)===null||n===void 0?void 0:n.call(e,"template");s&&ae(s,f=>{he(f.content)&&nt(f.content)})},Pe=function(e){const n=F?F(e):null;return typeof n!="string"||y(n)!=="form"?!1:typeof e.nodeName!="string"||typeof e.textContent!="string"||typeof e.removeChild!="function"||e.attributes!==J(e)||typeof e.removeAttribute!="function"||typeof e.removeAttributeNode!="function"||typeof e.getAttributeNode!="function"||typeof e.setAttribute!="function"||typeof e.namespaceURI!="string"||typeof e.insertBefore!="function"||typeof e.hasChildNodes!="function"||e.nodeType!==U(e)||e.childNodes!==I(e)},he=function(e){if(!U||typeof e!="object"||e===null)return!1;try{return U(e)===k.documentFragment}catch{return!1}},Ee=function(e){if(!U||typeof e!="object"||e===null)return!1;try{return typeof U(e)=="number"}catch{return!1}};function W(e,n,o){e.length!==0&&ae(e,i=>{i.call(r,n,o,de)})}const zn=function(e,n){return!!(te&&e.hasChildNodes()&&!Ee(e.firstElementChild)&&N(on,e.textContent)&&N(on,e.innerHTML)||te&&e.namespaceURI===j&&Ao[n]&&(Ee(e.firstElementChild)||typeof e.textContent=="string"&&N(Eo[n],e.textContent))||e.nodeType===k.processingInstruction||te&&e.nodeType===k.comment&&N(rn,e.data))},Ue=function(e,n){if(e instanceof RegExp)return N(e,n);if(e instanceof Function){for(var o=arguments.length,i=new Array(o>2?o-2:0),c=2;c=0;--f){const B=e===o?je(c[f],!0):c[f];i.insertBefore(B,le(e))}}}return oe(e),!0},Ut=function(e,n,o,i){return e.length===0?n:n===o||n===i?R(n):n},Ft=function(e,n){return e===n||S(e)!==null?!1:(Ke&&Me(e),!0)},Ht=function(e,n){if(W(p.beforeSanitizeElements,e,null),Ft(e,n))return!0;if(Pe(e))return oe(e),!0;const o=y(ee(e));if(d=Ut(p.uponSanitizeElement,d,Ye,xe),W(p.uponSanitizeElement,e,{tagName:o,allowedTags:d}),Ft(e,n))return!0;if(zn(e,o))return oe(e),!0;if(we[o]||!(V.tagCheck instanceof Function&&V.tagCheck(o))&&!d[o]){const i=Pn(e,o,n);return i===!1&&W(p.afterSanitizeElements,e,null),i}if(Q(e)===k.element&&!Ln(e)||(o==="noscript"||o==="noembed"||o==="noframes")&&N(To,e.innerHTML))return oe(e),!0;if(X&&e.nodeType===k.text){const i=ze(e.textContent);e.textContent!==i&&(Se(r.removed,{element:e.cloneNode()}),e.textContent=i)}return W(p.afterSanitizeElements,e,null),!1},jt=function(e,n,o){if(yt[n]||Mt(n,e)||At&&(n==="id"||n==="name")&&(o in a||o in Dn))return!1;const i=h[n]||V.attributeCheck instanceof Function&&V.attributeCheck(n,e);return qe&&N(An,n)||bt&&N(En,n)?!0:i?Ot[n]||N(gt,ve(o,ht,""))||(n==="src"||n==="xlink:href"||n==="href")&&e!=="script"&&$t(o,"data:")===0&&_t[e]||Tt&&!N(Sn,ve(o,ht,""))?!0:!o:Wt(e)&&Ue(H.tagNameCheck,e)&&Ue(H.attributeNameCheck,n,e)||n==="is"&&H.allowCustomizedBuiltInElements&&Ue(H.tagNameCheck,o)},Un=m({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Wt=function(e){return!Un[Ne(e)]&&N(vn,e)},Fn=function(e,n,o,i){if(v&&typeof L=="object"&&typeof L.getAttributeType=="function"&&!o)switch(L.getAttributeType(e,n)){case"TrustedHTML":return se(i);case"TrustedScriptURL":return pn(i)}return i},Hn=function(e,n,o,i){try{return o?e.setAttributeNS(o,n,i):e.setAttribute(n,i),Pe(e)?(oe(e),!1):!0}catch{return re(n,e),!1}},Bt=function(e){W(p.beforeSanitizeAttributes,e,null);const n=e.attributes;if(!n||Pe(e))return;h=Ut(p.uponSanitizeAttribute,h,Ge,De);const o={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:h,forceKeepAttr:void 0};let i=n.length;const c=y(e.nodeName);for(;i--;){const s=n[i],f=s.name,B=s.namespaceURI,$=s.value,_=y(f),P=$;let x=f==="value"?P:eo(P),Yt=!1;if(o.attrName=_,o.attrValue=x,o.keepAttr=!0,o.forceKeepAttr=void 0,W(p.uponSanitizeAttribute,e,o),x=o.attrValue,Et&&(_==="id"||_==="name")&&$t(x,St)!==0&&(re(f,e,s),x=St+x,Yt=!0),te&&N(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,x)){re(f,e,s);continue}if(_==="attributename"&&Xt(x,"href")){re(f,e,s);continue}if(!o.forceKeepAttr){if(!o.keepAttr){re(f,e,s);continue}if(!wt&&N(wo,x)){re(f,e,s);continue}if(X&&(x=ze(x)),!jt(c,_,x)){re(f,e,s);continue}x=Fn(c,_,B,x),x!==P&&Hn(e,f,B,x)&&Yt&&Vt(r.removed)}}W(p.afterSanitizeAttributes,e,null)},Fe=function(e){let n=null;const o=Pt(e);for(W(p.beforeSanitizeShadowDOM,e,null);n=o.nextNode();)if(W(p.uponSanitizeShadowNode,n,null),Ht(n,e),Bt(n),he(n.content)&&Fe(n.content),Q(n)===k.element){const i=M(n);he(i)&&(ot(i),Fe(i))}W(p.afterSanitizeShadowDOM,e,null)},ot=function(e){const n=[{node:e,shadow:null}];for(;n.length>0;){const o=n.pop();if(o.shadow){Fe(o.shadow);continue}const i=o.node,c=Q(i)===k.element,s=I(i);if(s)for(let f=s.length-1;f>=0;--f)n.push({node:s[f],shadow:null});if(c){const f=F?F(i):null;if(typeof f=="string"&&y(f)==="template"){const B=i.content;he(B)&&n.push({node:B,shadow:null})}}if(c){const f=M(i);he(f)&&n.push({node:null,shadow:f},{node:f,shadow:null})}}};return r.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=null,i=null,c=null,s=null;if(Ze=!e,Ze&&(e=""),typeof e!="string"&&!Ee(e)&&(e=io(e),typeof e!="string"))throw ie("dirty is not a string, aborting");if(!r.isSupported)return e;Ve?(d=xe,h=De):tt(n),(p.uponSanitizeElement.length>0||p.uponSanitizeAttribute.length>0)&&(d=R(d)),p.uponSanitizeAttribute.length>0&&(h=R(h)),r.removed=[];const f=Ke&&typeof e!="string"&&Ee(e);if(f){Mn(e);const _=ee(e);if(typeof _=="string"){const P=y(_);if(!d[P]||we[P])throw Ie(e),ie("root node is forbidden and cannot be sanitized in-place")}if(Pe(e))throw Ie(e),ie("root node is clobbered and cannot be sanitized in-place");try{ot(e)}catch(P){throw Ie(e),P}}else if(Ee(e))o=zt(""),i=o.ownerDocument.importNode(e,!0),i.nodeType===k.element&&i.nodeName==="BODY"||i.nodeName==="HTML"?o=i:o.appendChild(i),ot(o);else{if(!ue&&!X&&!ne&&e.indexOf("<")===-1)return v&&Re?se(e):e;if(o=zt(e),!o)return ue?null:Re?z:""}o&&Xe&&oe(o.firstChild);const B=f?e:o;try{const _=Pt(B);for(;c=_.nextNode();)Ht(c,B),Bt(c),he(c.content)&&Fe(c.content)}catch(_){throw f&&(Ie(e),ae(r.removed,P=>{P.element&&Me(P.element)})),_}if(f)return ae(r.removed,_=>{_.element&&Me(_.element)}),X&&nt(e),e;if(ue){if(X&&nt(o),ke)for(s=hn.call(o.ownerDocument);o.firstChild;)s.appendChild(o.firstChild);else s=o;return(h.shadowroot||h.shadowrootmode)&&(s=yn.call(l,s,!0)),s}let $=ne?o.outerHTML:o.innerHTML;return ne&&d["!doctype"]&&o.ownerDocument&&o.ownerDocument.doctype&&o.ownerDocument.doctype.name&&N(yo,o.ownerDocument.doctype.name)&&($=" -`+$),X&&($=ze($)),v&&Re?se($):$},r.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};tt(e),Ve=!0,xe=d,De=h},r.clearConfig=function(){de=null,Ve=!1,xe=null,De=null,v=We,z=""},r.isValidAttribute=function(e,n,o){de||tt({});const i=y(e),c=y(n);return jt(i,c,o)},r.addHook=function(e,n){typeof n=="function"&&D(p,e)&&Se(p[e],n)},r.removeHook=function(e,n){if(D(p,e)){if(n!==void 0){const o=Jn(p[e],n);return o===-1?void 0:Qn(p[e],o,1)[0]}return Vt(p[e])}},r.removeHooks=function(e){D(p,e)&&(p[e]=[])},r.removeAllHooks=function(){p=an()},r}var fn=un();const _o=["p","br","ul","ol","li","h1","h2","h3","h4","h5","h6","strong","b","em","i","u","s","del","blockquote","pre","code","a"],No=/^(?:https?|mailto):/i;fn.addHook("afterSanitizeAttributes",t=>{if(t.tagName==="A"){if(!t.hasAttribute("href")){t.replaceWith(...t.childNodes);return}t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")}});function Oo(t){return fn.sanitize(String(t??""),{ALLOWED_TAGS:_o,ALLOWED_ATTR:["href"],ALLOWED_URI_REGEXP:No,ALLOW_DATA_ATTR:!1})}const xo=25e3,zo=async(t,{signal:r}={})=>{const a=await jn(t,{method:"GET",signal:r},{timeoutMs:xo,fallbackMessage:"Could not load the pad content."});if(!a||typeof a!="object"||typeof a.html!="string"||typeof a.is_empty!="boolean")throw new Error("Could not load the pad content.");const l=Oo(a.html);return{html:l,isEmpty:a.is_empty||l.trim()===""}},Do=5e3,ko=2147483647,Ro=12e4,Co=t=>!!t&&t.code==="missing_frontmatter",Po=t=>!!t&&t.code==="missing_binding",Uo=t=>!!t&&(t.retryable===!0||t.code==="pad_file_changed"||Wn(t)),Fo=t=>{if(!t||t.is_readonly_view!==!0&&mn(t)==="")throw new Error("Pad open API did not return a valid URL.");return t},mn=t=>t&&typeof t.url=="string"?t.url.trim():"",Ho=async({open:t,initialize:r,stillWanted:a=()=>!0})=>{try{return await t()}catch(l){if(!Co(l))throw l;return await r(),a()?await t():null}},jo=t=>{const r=Number(t&&t.sync_interval_seconds);return{syncUrl:t&&typeof t.sync_url=="string"?t.sync_url.trim():"",intervalMs:Number.isFinite(r)&&r>0?Math.min(ko,Math.max(Do,r*1e3)):Ro}},Wo=t=>t&&typeof t.content_url=="string"?t.content_url.trim():"",Bo=t=>{const r=!!(t&&t.is_readonly_view===!0),a=mn(t),l=!!(t&&t.is_external===!0)&&a!=="";return{isContentView:r||l,externalUrl:l&&!r?a:""}};export{Bo as a,Uo as b,Wo as c,Fo as d,Io as e,Mo as h,Po as i,zo as l,Ho as o,mn as p,jo as s}; -//# sourceMappingURL=pad-open-flow-By_FzSKk.chunk.mjs.map +import{f as Wn,a as jn}from"./fetch-helpers-BUxbvlK6.chunk.mjs";const Bn=12e4;function Io({requestToken:t,fetchImpl:r}={}){const a=typeof r=="function"?r:(...S)=>window.fetch(...S),l=typeof t=="function"?t:()=>"";let u="",g=Bn,b=null,Y=!1,E=!1,G=!1,q=null,L=null,O=null;const We=({syncUrl:S,intervalMs:M}={})=>{typeof S=="string"&&(u=S),Number.isFinite(M)&&M>0&&(g=M)},Z=()=>{q!==null&&(window.clearInterval(q),q=null)},be=()=>{!u||q!==null||(q=window.setInterval(()=>{document.visibilityState==="visible"&&le(!1,!1)},g))},le=(S,M)=>{I(S,M).catch(()=>{})},I=async(S,M)=>{if(!u)return{status:"disabled"};if(b)return S&&!Y?(E=!0,G=G||!!M,b.catch(()=>{}).then(()=>I(!0,G))):b;Y=!!S;const J=(async()=>{const ee=S?u+(u.includes("?")?"&":"?")+"force=1":u,v=await a(ee,{method:"POST",credentials:"same-origin",headers:{Accept:"application/json",requesttoken:l()},keepalive:!!M}),z=await v.json().catch(()=>({}));if(!v.ok)throw new Error(z&&z.message||"Sync request failed.");return z})();b=J;let U,F=null;try{U=await J}catch(ee){F=ee}finally{b===J&&(b=null),Y=!1}const ce=E,Q=G;if(E=!1,G=!1,ce)return I(!0,Q);if(F instanceof Error)throw F;return U};return{configure:We,start:be,stop:Z,sync:I,fireAndForget:le,installLifecycleHandlers:()=>{L||O||(L=()=>{if(document.visibilityState==="hidden"){le(!0,!0),Z();return}be()},O=()=>{le(!0,!0),Z()},document.addEventListener("visibilitychange",L),window.addEventListener("pagehide",O))},removeLifecycleHandlers:()=>{L&&(document.removeEventListener("visibilitychange",L),L=null),O&&(window.removeEventListener("pagehide",O),O=null)}}}const Mo=(t,r,{preventScroll:a=!1}={})=>{const l=(t instanceof HTMLElement?t.querySelector("a, button"):null)||r;l instanceof HTMLElement&&(l===r&&(l.tabIndex=-1),l.focus({preventScroll:a}))};function Gt(t,r){(r==null||r>t.length)&&(r=t.length);for(var a=0,l=Array(r);a2?a-2:0),u=2;u1?r-1:0),l=1;l"u"?null:T(BigInt.prototype.toString),Zt=typeof Symbol>"u"?null:T(Symbol.prototype.toString),D=T(Object.prototype.hasOwnProperty),_e=T(Object.prototype.toString),N=T(RegExp.prototype.test),ie=oo(TypeError);function T(t){return function(r){r instanceof RegExp&&(r.lastIndex=0);for(var a=arguments.length,l=new Array(a>1?a-1:0),u=1;u2&&arguments[2]!==void 0?arguments[2]:Ne;if(qt&&qt(t,null),!ye(r))return t;let l=r.length;for(;l--;){let u=r[l];if(typeof u=="string"){const g=a(u);g!==u&&($n(r)||(r[l]=g),u=g)}t[u]=!0}return t}function ro(t){for(let r=0;r/g),fo=A(/\${[\w\W]*/g),mo=A(/^data-[\-\w.\u00B7-\uFFFF]+$/),po=A(/^aria-[\-\w]+$/),nn=A(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ho=A(/^(?:\w+script|data):/i),go=A(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),yo=A(/^html$/i),bo=A(/^[a-z][.\w]*(-[.\w]+)+$/i),on=A(/<[/\w!]/g),rn=A(/<[/\w]/g),To=A(/<\/no(script|embed|frames)/i),wo=A(/\/>/i),k={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},sn=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],Ao=w(m({},sn)),Eo=(function(){const t={};return ae(sn,r=>{t[r]=A(new RegExp("])","i"))}),w(t)})(),So=function(){return typeof window>"u"?null:window},vo=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let a=null;const l="data-tt-policy-suffix";r&&r.hasAttribute(l)&&(a=r.getAttribute(l));const u="dompurify"+(a?"#"+a:"");try{return t.createPolicy(u,{createHTML(g){return g},createScriptURL(g){return g}})}catch{return console.warn("TrustedTypes policy "+u+" could not be created."),null}},an=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},K=function(t,r,a,l){return D(t,r)&&ye(t[r])?m(l.base?R(l.base):{},t[r],l.transform):a},st=function(t,r,a){const l=D(t,r)?t[r]:void 0;return l&&typeof l=="object"?R(l):a()};function un(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:So();const r=e=>un(e);if(r.version="3.4.15",r.removed=[],!t||!t.document||t.document.nodeType!==k.document||!t.Element)return r.isSupported=!1,r;let a=t.document;const l=a,u=l.currentScript;t.DocumentFragment;const g=t.HTMLTemplateElement,b=t.Node,Y=t.Element,E=t.NodeFilter;t.NamedNodeMap===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;const q=t.DOMParser,L=t.trustedTypes,O=Y.prototype,We=C(O,"cloneNode"),Z=C(O,"remove"),be=C(O,"removeAttributeNode"),le=C(O,"nextSibling"),I=C(O,"childNodes"),S=C(O,"parentNode"),M=C(O,"shadowRoot"),J=C(O,"attributes"),U=b&&b.prototype?C(b.prototype,"nodeType"):null,F=b&&b.prototype?C(b.prototype,"nodeName"):null,ce=b&&b.prototype?C(b.prototype,"ownerDocument"):null,Q=function(e){return U?U(e):e.nodeType},ee=function(e){return F?F(e):e.nodeName};if(typeof g=="function"){const e=a.createElement("template");e.content&&e.content.ownerDocument&&(a=e.content.ownerDocument)}let v,z="",je,mt=!1,Te=0;const pt=function(){if(Te>0)throw ie('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},se=function(e){pt(),Te++;try{return v.createHTML(e)}finally{Te--}},pn=function(e){pt(),Te++;try{return v.createScriptURL(e)}finally{Te--}},dn=function(){return mt||(je=vo(L,u),mt=!0),je},Oe=a,Be=Oe.implementation,dt=Oe.createNodeIterator,hn=Oe.createDocumentFragment,gn=Oe.getElementsByTagName,yn=l.importNode;let p=an();r.isSupported=typeof ln=="function"&&typeof S=="function"&&Be&&Be.createHTMLDocument!==void 0;const bn=so,Tn=uo,wn=fo,An=mo,En=po,Sn=ho,ht=go,vn=bo;let gt=nn,d=null;const Ye=m({},[...Jt,...it,...at,...lt,...Qt]);let h=null;const Ge=m({},[...en,...ct,...tn,...He]);let H=Object.seal(ge(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),we=null,yt=null;const X=Object.seal(ge(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let bt=!0,qe=!0,Tt=!1,wt=!0,V=!1,te=!0,ne=!1,Xe=!1,xe=null,De=null,Ve=!1,ue=!1,ke=!1,Re=!1,At=!0,Et=!1;const St="user-content-";let $e=!0,Ke=!1,fe={},me=null;const vt=m({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let _t=null;const Nt=m({},["audio","video","img","source","image","track"]);let Ot=null;const xt=m({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ce="http://www.w3.org/1998/Math/MathML",Le="http://www.w3.org/2000/svg",W="http://www.w3.org/1999/xhtml";let pe=W,Ze=!1,Je=null;const _n=m({},[Ce,Le,W],rt),Dt=w(["mi","mo","mn","ms","mtext"]);let Qe=m({},Dt);const kt=w(["annotation-xml"]);let et=m({},kt);const Nn=m({},["title","style","font","a","script"]);let Ae=null;const On=["application/xhtml+xml","text/html"],xn="text/html";let y=null,de=null;const Dn=a.createElement("form"),Rt=function(e){return e instanceof RegExp||e instanceof Function},tt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(de&&de===e)return;(!e||typeof e!="object")&&(e={}),e=R(e),Ae=On.indexOf(e.PARSER_MEDIA_TYPE)===-1?xn:e.PARSER_MEDIA_TYPE,y=Ae==="application/xhtml+xml"?rt:Ne,d=K(e,"ALLOWED_TAGS",Ye,{transform:y}),h=K(e,"ALLOWED_ATTR",Ge,{transform:y}),Je=K(e,"ALLOWED_NAMESPACES",_n,{transform:rt}),Ot=K(e,"ADD_URI_SAFE_ATTR",xt,{transform:y,base:xt}),_t=K(e,"ADD_DATA_URI_TAGS",Nt,{transform:y,base:Nt}),me=K(e,"FORBID_CONTENTS",vt,{transform:y}),we=K(e,"FORBID_TAGS",R({}),{transform:y}),yt=K(e,"FORBID_ATTR",R({}),{transform:y}),fe=D(e,"USE_PROFILES")?e.USE_PROFILES&&typeof e.USE_PROFILES=="object"?R(e.USE_PROFILES):e.USE_PROFILES:!1,bt=e.ALLOW_ARIA_ATTR!==!1,qe=e.ALLOW_DATA_ATTR!==!1,Tt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,wt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,te=e.SAFE_FOR_XML!==!1,ne=e.WHOLE_DOCUMENT||!1,ue=e.RETURN_DOM||!1,ke=e.RETURN_DOM_FRAGMENT||!1,Re=e.RETURN_TRUSTED_TYPE||!1,Ve=e.FORCE_BODY||!1,At=e.SANITIZE_DOM!==!1,Et=e.SANITIZE_NAMED_PROPS||!1,$e=e.KEEP_CONTENT!==!1,Ke=e.IN_PLACE||!1,gt=ao(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:nn,pe=typeof e.NAMESPACE=="string"?e.NAMESPACE:W,Qe=st(e,"MATHML_TEXT_INTEGRATION_POINTS",()=>m({},Dt)),et=st(e,"HTML_INTEGRATION_POINTS",()=>m({},kt));const n=st(e,"CUSTOM_ELEMENT_HANDLING",()=>ge(null));if(H=ge(null),D(n,"tagNameCheck")&&Rt(n.tagNameCheck)&&(H.tagNameCheck=n.tagNameCheck),D(n,"attributeNameCheck")&&Rt(n.attributeNameCheck)&&(H.attributeNameCheck=n.attributeNameCheck),D(n,"allowCustomizedBuiltInElements")&&typeof n.allowCustomizedBuiltInElements=="boolean"&&(H.allowCustomizedBuiltInElements=n.allowCustomizedBuiltInElements),A(H),V&&(qe=!1),ke&&(ue=!0),fe&&(d=m({},Qt),h=ge(null),fe.html===!0&&(m(d,Jt),m(h,en)),fe.svg===!0&&(m(d,it),m(h,ct),m(h,He)),fe.svgFilters===!0&&(m(d,at),m(h,ct),m(h,He)),fe.mathMl===!0&&(m(d,lt),m(h,tn),m(h,He))),X.tagCheck=null,X.attributeCheck=null,D(e,"ADD_TAGS")&&(typeof e.ADD_TAGS=="function"?X.tagCheck=e.ADD_TAGS:ye(e.ADD_TAGS)&&(d===Ye&&(d=R(d)),m(d,e.ADD_TAGS,y))),D(e,"ADD_ATTR")&&(typeof e.ADD_ATTR=="function"?X.attributeCheck=e.ADD_ATTR:ye(e.ADD_ATTR)&&(h===Ge&&(h=R(h)),m(h,e.ADD_ATTR,y))),D(e,"ADD_FORBID_CONTENTS")&&ye(e.ADD_FORBID_CONTENTS)&&(me===vt&&(me=R(me)),m(me,e.ADD_FORBID_CONTENTS,y)),$e&&(d["#text"]=!0),ne&&m(d,["html","head","body"]),d.table&&(m(d,["tbody"]),delete we.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!="function")throw ie('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ie('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const o=v;v=e.TRUSTED_TYPES_POLICY;try{z=se("")}catch(i){throw v=o,i}}else e.TRUSTED_TYPES_POLICY===null?(v=void 0,z=""):(v===void 0&&(v=dn()),v&&typeof z=="string"&&(z=se("")));w&&w(e),de=e},Ct=m({},[...it,...at,...lo]),Lt=m({},[...lt,...co]),kn=function(e,n,o){return n.namespaceURI===W?e==="svg":n.namespaceURI===Ce?e==="svg"&&(o==="annotation-xml"||Qe[o]):!!Ct[e]},Rn=function(e,n,o){return n.namespaceURI===W?e==="math":n.namespaceURI===Le?e==="math"&&et[o]:!!Lt[e]},Cn=function(e,n,o){return n.namespaceURI===Le&&!et[o]||n.namespaceURI===Ce&&!Qe[o]?!1:!Lt[e]&&(Nn[e]||!Ct[e])},Ln=function(e){let n=S(e);(!n||!n.tagName)&&(n={namespaceURI:pe,tagName:"template"});const o=Ne(e.tagName),i=Ne(n.tagName);return Je[e.namespaceURI]?e.namespaceURI===Le?kn(o,n,i):e.namespaceURI===Ce?Rn(o,n,i):e.namespaceURI===W?Cn(o,n,i):!!(Ae==="application/xhtml+xml"&&Je[e.namespaceURI]):!1},oe=function(e){Se(r.removed,{element:e});try{S(e).removeChild(e)}catch{if(Z(e),!S(e))throw ie("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},It=function(e,n,o){try{be(e,n)}catch{try{e.removeAttribute(o)}catch{}}},Ie=function(e){Me(e);const n=I(e);if(n){const i=[];ae(n,c=>{Se(i,c)}),ae(i,c=>{try{Z(c)}catch{}})}const o=J(e);if(o)for(let i=o.length-1;i>=0;--i){const c=o[i],s=c&&c.name;typeof s=="string"&&It(e,c,s)}},re=function(e,n,o){if(!o)try{o=n.getAttributeNode(e)}catch{o=null}Se(r.removed,{attribute:o||null,from:n});try{o?be(n,o):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e==="is")if(ue||ke)try{oe(n)}catch{}else try{n.setAttribute(e,"")}catch{}},In=function(e){const n=J(e);if(n)for(let o=n.length-1;o>=0;--o){const i=n[o],c=i&&i.name;typeof c!="string"||h[y(c)]||It(e,i,c)}},Me=function(e){const n=[e];for(;n.length>0;){const o=n.pop();Q(o)===k.element&&In(o);const i=I(o);if(i)for(let c=i.length-1;c>=0;--c)n.push(i[c])}},Mt=function(e,n){return te?e==="patchsrc"?!0:e==="for"&&n!=="label"&&n!=="output":!1},Mn=function(e){if(!te)return;const n=[e];for(;n.length>0;){const o=n.pop(),i=Q(o);if(i===k.processingInstruction||i===k.comment&&N(rn,o.data)){try{Z(o)}catch{}continue}if(i===k.element){const s=o,f=y(ee(o));try{s.hasAttribute&&s.hasAttribute("patchsrc")&&s.removeAttribute("patchsrc"),s.hasAttribute&&s.hasAttribute("for")&&Mt("for",f)&&s.removeAttribute("for")}catch{}}const c=I(o);if(c)for(let s=c.length-1;s>=0;--s)n.push(c[s])}},zt=function(e){let n=null,o=null;if(Ve)e=""+e;else{const s=Vt(e,/^[\r\n\t ]+/);o=s&&s[0]}Ae==="application/xhtml+xml"&&pe===W&&(e=''+e+"");const i=v?se(e):e;if(pe===W)try{n=new q().parseFromString(i,Ae)}catch{}if(!n||!n.documentElement){n=Be.createDocument(pe,"template",null);try{n.documentElement.innerHTML=Ze?z:i}catch{}}const c=n.body||n.documentElement;return e&&o&&c.insertBefore(a.createTextNode(o),c.childNodes[0]||null),pe===W?gn.call(n,ne?"html":"body")[0]:ne?n.documentElement:c},Pt=function(e){const n=ce?ce(e):e.ownerDocument;return dt.call(n||e,e,E.SHOW_ELEMENT|E.SHOW_COMMENT|E.SHOW_TEXT|E.SHOW_PROCESSING_INSTRUCTION|E.SHOW_CDATA_SECTION,null)},ze=function(e){return e=ve(e,bn," "),e=ve(e,Tn," "),e=ve(e,wn," "),e},nt=function(e){var n;e.normalize();const o=ce?ce(e):e.ownerDocument,i=dt.call(o||e,e,E.SHOW_TEXT|E.SHOW_COMMENT|E.SHOW_CDATA_SECTION|E.SHOW_PROCESSING_INSTRUCTION,null);let c=i.nextNode();for(;c;)c.data=ze(c.data),c=i.nextNode();const s=(n=e.querySelectorAll)===null||n===void 0?void 0:n.call(e,"template");s&&ae(s,f=>{he(f.content)&&nt(f.content)})},Pe=function(e){const n=F?F(e):null;return typeof n!="string"||y(n)!=="form"?!1:typeof e.nodeName!="string"||typeof e.textContent!="string"||typeof e.removeChild!="function"||e.attributes!==J(e)||typeof e.removeAttribute!="function"||typeof e.removeAttributeNode!="function"||typeof e.getAttributeNode!="function"||typeof e.setAttribute!="function"||typeof e.namespaceURI!="string"||typeof e.insertBefore!="function"||typeof e.hasChildNodes!="function"||e.nodeType!==U(e)||e.childNodes!==I(e)},he=function(e){if(!U||typeof e!="object"||e===null)return!1;try{return U(e)===k.documentFragment}catch{return!1}},Ee=function(e){if(!U||typeof e!="object"||e===null)return!1;try{return typeof U(e)=="number"}catch{return!1}};function j(e,n,o){e.length!==0&&ae(e,i=>{i.call(r,n,o,de)})}const zn=function(e,n){return!!(te&&e.hasChildNodes()&&!Ee(e.firstElementChild)&&N(on,e.textContent)&&N(on,e.innerHTML)||te&&e.namespaceURI===W&&Ao[n]&&(Ee(e.firstElementChild)||typeof e.textContent=="string"&&N(Eo[n],e.textContent))||e.nodeType===k.processingInstruction||te&&e.nodeType===k.comment&&N(rn,e.data))},Ue=function(e,n){if(e instanceof RegExp)return N(e,n);if(e instanceof Function){for(var o=arguments.length,i=new Array(o>2?o-2:0),c=2;c=0;--f){const B=e===o?We(c[f],!0):c[f];i.insertBefore(B,le(e))}}}return oe(e),!0},Ut=function(e,n,o,i){return e.length===0?n:n===o||n===i?R(n):n},Ft=function(e,n){return e===n||S(e)!==null?!1:(Ke&&Me(e),!0)},Ht=function(e,n){if(j(p.beforeSanitizeElements,e,null),Ft(e,n))return!0;if(Pe(e))return oe(e),!0;const o=y(ee(e));if(d=Ut(p.uponSanitizeElement,d,Ye,xe),j(p.uponSanitizeElement,e,{tagName:o,allowedTags:d}),Ft(e,n))return!0;if(zn(e,o))return oe(e),!0;if(we[o]||!(X.tagCheck instanceof Function&&X.tagCheck(o))&&!d[o]){const i=Pn(e,o,n);return i===!1&&j(p.afterSanitizeElements,e,null),i}if(Q(e)===k.element&&!Ln(e)||(o==="noscript"||o==="noembed"||o==="noframes")&&N(To,e.innerHTML))return oe(e),!0;if(V&&e.nodeType===k.text){const i=ze(e.textContent);e.textContent!==i&&(Se(r.removed,{element:e.cloneNode()}),e.textContent=i)}return j(p.afterSanitizeElements,e,null),!1},Wt=function(e,n,o){if(yt[n]||Mt(n,e)||At&&(n==="id"||n==="name")&&(o in a||o in Dn))return!1;const i=h[n]||X.attributeCheck instanceof Function&&X.attributeCheck(n,e);return qe&&N(An,n)||bt&&N(En,n)?!0:i?Ot[n]||N(gt,ve(o,ht,""))||(n==="src"||n==="xlink:href"||n==="href")&&e!=="script"&&$t(o,"data:")===0&&_t[e]||Tt&&!N(Sn,ve(o,ht,""))?!0:!o:jt(e)&&Ue(H.tagNameCheck,e)&&Ue(H.attributeNameCheck,n,e)||n==="is"&&H.allowCustomizedBuiltInElements&&Ue(H.tagNameCheck,o)},Un=m({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),jt=function(e){return!Un[Ne(e)]&&N(vn,e)},Fn=function(e,n,o,i){if(v&&typeof L=="object"&&typeof L.getAttributeType=="function"&&!o)switch(L.getAttributeType(e,n)){case"TrustedHTML":return se(i);case"TrustedScriptURL":return pn(i)}return i},Hn=function(e,n,o,i){try{return o?e.setAttributeNS(o,n,i):e.setAttribute(n,i),Pe(e)?(oe(e),!1):!0}catch{return re(n,e),!1}},Bt=function(e){j(p.beforeSanitizeAttributes,e,null);const n=e.attributes;if(!n||Pe(e))return;h=Ut(p.uponSanitizeAttribute,h,Ge,De);const o={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:h,forceKeepAttr:void 0};let i=n.length;const c=y(e.nodeName);for(;i--;){const s=n[i],f=s.name,B=s.namespaceURI,$=s.value,_=y(f),P=$;let x=f==="value"?P:eo(P),Yt=!1;if(o.attrName=_,o.attrValue=x,o.keepAttr=!0,o.forceKeepAttr=void 0,j(p.uponSanitizeAttribute,e,o),x=o.attrValue,Et&&(_==="id"||_==="name")&&$t(x,St)!==0&&(re(f,e,s),x=St+x,Yt=!0),te&&N(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,x)){re(f,e,s);continue}if(_==="attributename"&&Vt(x,"href")){re(f,e,s);continue}if(!o.forceKeepAttr){if(!o.keepAttr){re(f,e,s);continue}if(!wt&&N(wo,x)){re(f,e,s);continue}if(V&&(x=ze(x)),!Wt(c,_,x)){re(f,e,s);continue}x=Fn(c,_,B,x),x!==P&&Hn(e,f,B,x)&&Yt&&Xt(r.removed)}}j(p.afterSanitizeAttributes,e,null)},Fe=function(e){let n=null;const o=Pt(e);for(j(p.beforeSanitizeShadowDOM,e,null);n=o.nextNode();)if(j(p.uponSanitizeShadowNode,n,null),Ht(n,e),Bt(n),he(n.content)&&Fe(n.content),Q(n)===k.element){const i=M(n);he(i)&&(ot(i),Fe(i))}j(p.afterSanitizeShadowDOM,e,null)},ot=function(e){const n=[{node:e,shadow:null}];for(;n.length>0;){const o=n.pop();if(o.shadow){Fe(o.shadow);continue}const i=o.node,c=Q(i)===k.element,s=I(i);if(s)for(let f=s.length-1;f>=0;--f)n.push({node:s[f],shadow:null});if(c){const f=F?F(i):null;if(typeof f=="string"&&y(f)==="template"){const B=i.content;he(B)&&n.push({node:B,shadow:null})}}if(c){const f=M(i);he(f)&&n.push({node:null,shadow:f},{node:f,shadow:null})}}};return r.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=null,i=null,c=null,s=null;if(Ze=!e,Ze&&(e=""),typeof e!="string"&&!Ee(e)&&(e=io(e),typeof e!="string"))throw ie("dirty is not a string, aborting");if(!r.isSupported)return e;Xe?(d=xe,h=De):tt(n),(p.uponSanitizeElement.length>0||p.uponSanitizeAttribute.length>0)&&(d=R(d)),p.uponSanitizeAttribute.length>0&&(h=R(h)),r.removed=[];const f=Ke&&typeof e!="string"&&Ee(e);if(f){Mn(e);const _=ee(e);if(typeof _=="string"){const P=y(_);if(!d[P]||we[P])throw Ie(e),ie("root node is forbidden and cannot be sanitized in-place")}if(Pe(e))throw Ie(e),ie("root node is clobbered and cannot be sanitized in-place");try{ot(e)}catch(P){throw Ie(e),P}}else if(Ee(e))o=zt(""),i=o.ownerDocument.importNode(e,!0),i.nodeType===k.element&&i.nodeName==="BODY"||i.nodeName==="HTML"?o=i:o.appendChild(i),ot(o);else{if(!ue&&!V&&!ne&&e.indexOf("<")===-1)return v&&Re?se(e):e;if(o=zt(e),!o)return ue?null:Re?z:""}o&&Ve&&oe(o.firstChild);const B=f?e:o;try{const _=Pt(B);for(;c=_.nextNode();)Ht(c,B),Bt(c),he(c.content)&&Fe(c.content)}catch(_){throw f&&(Ie(e),ae(r.removed,P=>{P.element&&Me(P.element)})),_}if(f)return ae(r.removed,_=>{_.element&&Me(_.element)}),V&&nt(e),e;if(ue){if(V&&nt(o),ke)for(s=hn.call(o.ownerDocument);o.firstChild;)s.appendChild(o.firstChild);else s=o;return(h.shadowroot||h.shadowrootmode)&&(s=yn.call(l,s,!0)),s}let $=ne?o.outerHTML:o.innerHTML;return ne&&d["!doctype"]&&o.ownerDocument&&o.ownerDocument.doctype&&o.ownerDocument.doctype.name&&N(yo,o.ownerDocument.doctype.name)&&($=" +`+$),V&&($=ze($)),v&&Re?se($):$},r.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};tt(e),Xe=!0,xe=d,De=h},r.clearConfig=function(){de=null,Xe=!1,xe=null,De=null,v=je,z=""},r.isValidAttribute=function(e,n,o){de||tt({});const i=y(e),c=y(n);return Wt(i,c,o)},r.addHook=function(e,n){typeof n=="function"&&D(p,e)&&Se(p[e],n)},r.removeHook=function(e,n){if(D(p,e)){if(n!==void 0){const o=Jn(p[e],n);return o===-1?void 0:Qn(p[e],o,1)[0]}return Xt(p[e])}},r.removeHooks=function(e){D(p,e)&&(p[e]=[])},r.removeAllHooks=function(){p=an()},r}var fn=un();const _o=["p","br","ul","ol","li","h1","h2","h3","h4","h5","h6","strong","b","em","i","u","s","del","blockquote","pre","code","a"],No=/^(?:https?|mailto):/i;fn.addHook("afterSanitizeAttributes",t=>{if(t.tagName==="A"){if(!t.hasAttribute("href")){t.replaceWith(...t.childNodes);return}t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")}});function Oo(t){return fn.sanitize(String(t??""),{ALLOWED_TAGS:_o,ALLOWED_ATTR:["href"],ALLOWED_URI_REGEXP:No,ALLOW_DATA_ATTR:!1})}const xo=25e3,zo=async(t,{signal:r}={})=>{const a=await Wn(t,{method:"GET",signal:r},{timeoutMs:xo,fallbackMessage:"Could not load the pad content."});if(!a||typeof a!="object"||typeof a.html!="string"||typeof a.is_empty!="boolean")throw new Error("Could not load the pad content.");const l=Oo(a.html);return{html:l,isEmpty:a.is_empty||l.trim()===""}},Do=5e3,ko=2147483647,Ro=12e4,Co=t=>!!t&&t.code==="missing_frontmatter",Po=t=>!!t&&t.code==="missing_binding",Uo=t=>!!t&&t.code==="pad_missing",Fo=t=>!!t&&(t.retryable===!0||t.code==="pad_file_changed"||jn(t)),Ho=t=>{if(!t||t.is_readonly_view!==!0&&mn(t)==="")throw new Error("Pad open API did not return a valid URL.");return t},mn=t=>t&&typeof t.url=="string"?t.url.trim():"",Wo=async({open:t,initialize:r,stillWanted:a=()=>!0})=>{try{return await t()}catch(l){if(!Co(l))throw l;return await r(),a()?await t():null}},jo=t=>{const r=Number(t&&t.sync_interval_seconds);return{syncUrl:t&&typeof t.sync_url=="string"?t.sync_url.trim():"",intervalMs:Number.isFinite(r)&&r>0?Math.min(ko,Math.max(Do,r*1e3)):Ro}},Bo=t=>t&&typeof t.content_url=="string"?t.content_url.trim():"",Yo=t=>{const r=!!(t&&t.is_readonly_view===!0),a=mn(t),l=!!(t&&t.is_external===!0)&&a!=="";return{isContentView:r||l,externalUrl:l&&!r?a:""}};export{Yo as a,Uo as b,Bo as c,Fo as d,Ho as e,Io as f,Mo as h,Po as i,zo as l,Wo as o,mn as p,jo as s}; +//# sourceMappingURL=pad-open-flow-_qELVjOV.chunk.mjs.map diff --git a/js/pad-open-flow-By_FzSKk.chunk.mjs.license b/js/pad-open-flow-_qELVjOV.chunk.mjs.license similarity index 100% rename from js/pad-open-flow-By_FzSKk.chunk.mjs.license rename to js/pad-open-flow-_qELVjOV.chunk.mjs.license diff --git a/js/pad-open-flow-By_FzSKk.chunk.mjs.map b/js/pad-open-flow-_qELVjOV.chunk.mjs.map similarity index 79% rename from js/pad-open-flow-By_FzSKk.chunk.mjs.map rename to js/pad-open-flow-_qELVjOV.chunk.mjs.map index aadf725a..6aec0512 100644 --- a/js/pad-open-flow-By_FzSKk.chunk.mjs.map +++ b/js/pad-open-flow-_qELVjOV.chunk.mjs.map @@ -1 +1 @@ -{"version":3,"file":"pad-open-flow-By_FzSKk.chunk.mjs","sources":["../src/lib/pad-sync.js","../src/lib/hand-focus.js","../node_modules/dompurify/dist/purify.es.mjs","../src/lib/sanitize-html.js","../src/lib/pad-content.js","../src/lib/pad-open-flow.js"],"sourcesContent":["/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/**\n * Shared pad-sync loop for the viewer and embed entrypoints.\n *\n * Owns the periodic background sync, forced/keepalive flushes, and the\n * visibility/pagehide lifecycle wiring. Forced syncs coalesce: while one\n * request is in flight a second forced flush is not started concurrently but\n * remembered and replayed once, so two forced flushes can never overlap (this\n * is the embed behavior, now shared — the viewer previously used a plain\n * in-flight boolean that allowed overlap).\n *\n * The caller supplies the request-token getter (the viewer and embed read it\n * from different places) and may inject a `fetchImpl` for tests.\n */\n\nexport const DEFAULT_SYNC_INTERVAL_MS = 120000\n\nexport function createPadSync({ requestToken, fetchImpl } = {}) {\n\tconst doFetch = typeof fetchImpl === 'function' ? fetchImpl : (...args) => window.fetch(...args)\n\tconst getToken = typeof requestToken === 'function' ? requestToken : () => ''\n\n\tlet syncUrl = ''\n\tlet intervalMs = DEFAULT_SYNC_INTERVAL_MS\n\tlet syncPromise = null\n\tlet activeSyncForce = false\n\tlet pendingForcedSync = false\n\tlet pendingForcedKeepalive = false\n\tlet timerId = null\n\tlet visibilityHandler = null\n\tlet pageHideHandler = null\n\n\tconst configure = ({ syncUrl: url, intervalMs: ms } = {}) => {\n\t\tif (typeof url === 'string') {\n\t\t\tsyncUrl = url\n\t\t}\n\t\tif (Number.isFinite(ms) && ms > 0) {\n\t\t\tintervalMs = ms\n\t\t}\n\t}\n\n\tconst stop = () => {\n\t\tif (timerId !== null) {\n\t\t\twindow.clearInterval(timerId)\n\t\t\ttimerId = null\n\t\t}\n\t}\n\n\tconst start = () => {\n\t\tif (!syncUrl || timerId !== null) {\n\t\t\treturn\n\t\t}\n\t\ttimerId = window.setInterval(() => {\n\t\t\tif (document.visibilityState === 'visible') {\n\t\t\t\tfireAndForget(false, false)\n\t\t\t}\n\t\t}, intervalMs)\n\t}\n\n\tconst fireAndForget = (force, keepalive) => {\n\t\tvoid sync(force, keepalive).catch(() => {})\n\t}\n\n\tconst sync = async (force, keepalive) => {\n\t\tif (!syncUrl) {\n\t\t\treturn { status: 'disabled' }\n\t\t}\n\t\tif (syncPromise) {\n\t\t\t// A request is already running. A forced flush that arrives while a\n\t\t\t// non-forced sync is in flight is coalesced into a single replay.\n\t\t\tif (force && !activeSyncForce) {\n\t\t\t\tpendingForcedSync = true\n\t\t\t\tpendingForcedKeepalive = pendingForcedKeepalive || Boolean(keepalive)\n\t\t\t\treturn syncPromise.catch(() => undefined).then(() => sync(true, pendingForcedKeepalive))\n\t\t\t}\n\t\t\treturn syncPromise\n\t\t}\n\t\tactiveSyncForce = Boolean(force)\n\t\tconst currentPromise = (async () => {\n\t\t\tconst url = force ? (syncUrl + (syncUrl.includes('?') ? '&' : '?') + 'force=1') : syncUrl\n\t\t\tconst response = await doFetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tcredentials: 'same-origin',\n\t\t\t\theaders: {\n\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\trequesttoken: getToken(),\n\t\t\t\t},\n\t\t\t\tkeepalive: Boolean(keepalive),\n\t\t\t})\n\t\t\tconst data = await response.json().catch(() => ({}))\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error((data && data.message) || 'Sync request failed.')\n\t\t\t}\n\t\t\treturn data\n\t\t})()\n\t\tsyncPromise = currentPromise\n\t\tlet result\n\t\tlet syncError = null\n\t\ttry {\n\t\t\tresult = await currentPromise\n\t\t} catch (error) {\n\t\t\tsyncError = error\n\t\t} finally {\n\t\t\tif (syncPromise === currentPromise) {\n\t\t\t\tsyncPromise = null\n\t\t\t}\n\t\t\tactiveSyncForce = false\n\t\t}\n\t\tconst rerunForcedSync = pendingForcedSync\n\t\tconst rerunKeepalive = pendingForcedKeepalive\n\t\tpendingForcedSync = false\n\t\tpendingForcedKeepalive = false\n\t\tif (rerunForcedSync) {\n\t\t\treturn sync(true, rerunKeepalive)\n\t\t}\n\t\tif (syncError instanceof Error) {\n\t\t\tthrow syncError\n\t\t}\n\t\treturn result\n\t}\n\n\tconst installLifecycleHandlers = () => {\n\t\tif (visibilityHandler || pageHideHandler) {\n\t\t\treturn\n\t\t}\n\t\tvisibilityHandler = () => {\n\t\t\tif (document.visibilityState === 'hidden') {\n\t\t\t\tfireAndForget(true, true)\n\t\t\t\tstop()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tstart()\n\t\t}\n\t\tpageHideHandler = () => {\n\t\t\tfireAndForget(true, true)\n\t\t\tstop()\n\t\t}\n\t\tdocument.addEventListener('visibilitychange', visibilityHandler)\n\t\twindow.addEventListener('pagehide', pageHideHandler)\n\t}\n\n\tconst removeLifecycleHandlers = () => {\n\t\tif (visibilityHandler) {\n\t\t\tdocument.removeEventListener('visibilitychange', visibilityHandler)\n\t\t\tvisibilityHandler = null\n\t\t}\n\t\tif (pageHideHandler) {\n\t\t\twindow.removeEventListener('pagehide', pageHideHandler)\n\t\t\tpageHideHandler = null\n\t\t}\n\t}\n\n\treturn {\n\t\tconfigure,\n\t\tstart,\n\t\tstop,\n\t\tsync,\n\t\tfireAndForget,\n\t\tinstallLifecycleHandlers,\n\t\tremoveLifecycleHandlers,\n\t}\n}\n","/**\n * SPDX-License-Identifier: AGPL-3.0-or-later\n * Copyright (c) 2026 Jacob Bühler\n */\n\n/**\n * After a click whose button went away with the focus on it - a second\n * try, a recovery - the first action in `actionsScope`, or else the\n * message, takes the focus, so a keyboard or screen reader keeps its\n * place (docs/architecture.md, \"Errors of the API\").\n *\n * @param {Element|null|undefined} actionsScope where the new actions are\n * @param {Element|null|undefined} messageNode what to focus without one\n * @param {{preventScroll?: boolean}} [options] the embed page sits in\n * another page, which must not scroll to it\n */\nexport const handFocusTo = (actionsScope, messageNode, { preventScroll = false } = {}) => {\n\tconst action = actionsScope instanceof HTMLElement ? actionsScope.querySelector('a, button') : null\n\tconst target = action || messageNode\n\tif (!(target instanceof HTMLElement)) {\n\t\treturn\n\t}\n\tif (target === messageNode) {\n\t\t// A paragraph takes the focus only with a tabindex.\n\t\ttarget.tabIndex = -1\n\t}\n\ttarget.focus({ preventScroll })\n}\n","/*! @license DOMPurify 3.4.15 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.15/LICENSE */\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nconst entries = Object.entries,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\nlet _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n if (!arrayIsArray(array)) {\n return set;\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const _ref2 of entries(object)) {\n var _ref3 = _slicedToArray(_ref2, 2);\n const property = _ref3[0];\n const value = _ref3[1];\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'string':\n {\n return value;\n }\n case 'number':\n {\n return numberToString(value);\n }\n case 'boolean':\n {\n return booleanToString(value);\n }\n case 'bigint':\n {\n return bigintToString ? bigintToString(value) : '0';\n }\n case 'symbol':\n {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n case 'undefined':\n {\n return objectToString(value);\n }\n case 'function':\n case 'object':\n {\n if (value === null) {\n return objectToString(value);\n }\n const valueAsRecord = value;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n return typeof stringified === 'string' ? stringified : objectToString(stringified);\n }\n return objectToString(value);\n }\n default:\n {\n return objectToString(value);\n }\n }\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\nfunction isRegex(value) {\n try {\n regExpTest(value, '');\n return true;\n } catch (_unused) {\n return false;\n }\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'pointer-events', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'vector-effect', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\n/* HTML-namespace elements whose child text nodes are serialized *literally*\n (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS\n shapes ride on that literal serialization:\n (a) an element child - a tree the HTML parser can never build, but the DOM\n API and an XML/XHTML parse can - after which a ``-bearing text\n sibling breaks the element open on reparse; and\n (b) text-only content that already carries the element's OWN end tag, e.g.\n `` built as a node, which the literal\n serializer emits verbatim for the HTML parser to re-open.\n Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape\n (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized\n form for these elements) rather than innerHTML, because an XML/XHTML working\n document serializes innerHTML with `<` escaped, which silently blinds the\n innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.\n `script` is never allow-listed, but is kept here so the guard matches the\n serializer's own literal-text list exactly. */\nconst LITERAL_TEXT_ELEMENT_NAMES = ['style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript'];\nconst LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));\n/* Per-element end-tag matcher. On an HTML reparse the ONLY token that\n terminates a literal-text element's raw content is its own end tag; a foreign\n literal-text close (e.g. `` sitting inside `` built as a node, which the literal\n serializer emits verbatim for the HTML parser to re-open.\n Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape\n (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized\n form for these elements) rather than innerHTML, because an XML/XHTML working\n document serializes innerHTML with `<` escaped, which silently blinds the\n innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.\n `script` is never allow-listed, but is kept here so the guard matches the\n serializer's own literal-text list exactly. */\nconst LITERAL_TEXT_ELEMENT_NAMES = ['style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript'];\nconst LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));\n/* Per-element end-tag matcher. On an HTML reparse the ONLY token that\n terminates a literal-text element's raw content is its own end tag; a foreign\n literal-text close (e.g. `` sitting inside `