diff --git a/.agents/bin/docker b/.agents/bin/docker index 1d64b5e1e690..a7dc7eb5726d 100755 --- a/.agents/bin/docker +++ b/.agents/bin/docker @@ -1,2 +1,2 @@ #!/bin/sh -exec sudo --preserve-env=PUBLIC_URL /usr/bin/docker "$@" +exec sudo --preserve-env=PUBLIC_URL,COMPOSE_PROFILES /usr/bin/docker "$@" diff --git a/.agents/skills/add-service/SKILL.md b/.agents/skills/add-service/SKILL.md new file mode 100644 index 000000000000..f1148bd4ba08 --- /dev/null +++ b/.agents/skills/add-service/SKILL.md @@ -0,0 +1,145 @@ +--- +name: add-service +description: Create a new Ghost Core service with gx generate service, then finish what the generator leaves to the author - dependency wiring, boot initialization, tests and checks. Use when adding a new boot-owned capability under ghost/core/server/services. To adopt defineService in an existing service, use migrate-service instead. +--- + +# Add a service + +The [services guide](../../../ghost/core/server/services/README.md) is the +authoring guide. This skill is the checklist that goes with it; follow the links +rather than copying a neighbouring service, which may still be legacy. + +## 1. Check it is a service + +Apply the guide's +[What belongs here](../../../ghost/core/server/services/README.md#what-belongs-here) +test first. A service root wires an instance that boot owns and callers share. +Name that instance, its callers and what must be ready before they use it. A +reusable constructor, an ordinary library or a helper used by one service is not +a service: put it where the guide says and stop here. + +For an existing service, use [migrate-service](../migrate-service/SKILL.md). + +Then read [creating a service](../../../ghost/core/server/services/README.md#creating-a-service), +[initialization](../../../ghost/core/server/services/README.md#initialization) +and the [kernel contract](../../../ghost/core/kernel/README.md#service-initialization). +[IndexNow](../../../ghost/core/server/services/indexnow-ping/index.ts) and its +[root test](../../../ghost/test/unit/server/services/indexnow-ping/index.test.ts) +are the worked example. + +## 2. Generate the service + +From the repository root: + +```sh +pnpm gx generate service +``` + +Use lowercase kebab-case beginning with a letter. Never write the root by hand. +The [generator](../../../tools/gx/README.md#service-generator) creates: + +- `ghost/core/server/services//index.ts`, the `defineService` root +- `ghost/core/server/services//-service.ts`, the implementation +- `ghost/test/unit/server/services//index.test.ts`, a starter root test + +It registers nothing. A service that is not in the +[legacy service inventory](../../../ghost/core/server/services/README.md#standard-and-legacy-services) +is standard, so every service check applies from the first commit. Do not add +the service to the inventory's `services` list or to any lint configuration. + +If the generator refuses a name because a path exists or the name is still +listed as legacy, read that code. Do not delete it to make generation succeed. + +## 3. Implement and wire dependencies + +Put behavior in the implementation and composition in the root's `create` +callback. The guide's +[dependency boundaries](../../../ghost/core/server/services/README.md#dependency-boundaries) +say what the root injects, what the implementation imports directly, and how to +handle live settings, deferred lookups and logging types. Apply them to every +implementation file, including nested helpers. + +Delete the generated example comments once the real dependencies are wired. +Consumers read the instance through the root's `.service`. If a check rejects an +import, fix the wiring; do not widen the allowlist to make lint pass. + +## 4. Initialize in boot + +The generator leaves [boot.js](../../../ghost/core/boot.js) to you. + +- **Phase.** Most roots belong in `initServices`. `initCore` and + `initServicesForFrontend` run earlier, for roots that the frontend or later + phases read. Do not initialize on the first request. +- **Order.** Initialize after everything `create` reads and before anything + reads `.service`. In `initServices`, a root that others read during their own + `create` is awaited on its own line before the `Promise.all`; independent + roots go inside it; a root that reads one of those goes after it. +- **Form.** Bind the root, then call `init()` on the binding, as the lines + around it do. Await it even when `create` is synchronous: + + ```js + const deliveryReceipts = require('./server/services/delivery-receipts').default; + await deliveryReceipts.init(); + ``` + + `pnpm lint:oxlint` and `gx services verify` find the call through that + binding. Lint fails until it is there, and neither recognises the inline + `await require(...).default.init()`. + +- **Comments.** Replace the generated comment above `defineService` with what + `create` needs ready. Where the order matters, say why beside the call in + boot, as the existing comments there do. +- **Boot test.** `ghost/test/unit/boot/standard-services.test.ts` already + checks that boot waits for the root's `init()` and that its failure fails + boot; do not write that test again. Add a boot test only where order + matters. The `initCore` and `initServicesForFrontend` tests fail on a root + they do not list, so add a stub there for a root in those phases. +- **Resources.** Finish startup work before returning the instance. Acquire + listeners, timers and work to drain in `start` and release them in `stop`, + following + [starting and stopping](../../../ghost/core/server/services/README.md#starting-and-stopping). + Register `root.stop()` with `ghostServer.registerCleanupTask` in boot. + +## 5. Test and check + +Extend the generated root test and add implementation tests for behavior, +dependency timing and readiness. If startup acquires resources, cover a failed +attempt followed by a successful retry. The +[testing guide](../../../docs/contributing/testing.md#run-focused-tests) +explains the focused commands. + +A new service has no inventory entry. The one exception: if the root declares +`extras`, catalogue each one in the `followUps` section of +`ghost/core/server/services/legacy-service-inventory.yaml`, as the +[standard root contract](../../../ghost/core/server/services/README.md#standard-root-contract) +describes. The inventory test compares the names. + +Run from the repository root: + +```sh +pnpm nx run ghost:test:unit test/unit/server/services//index.test.ts +pnpm nx run ghost:test:unit test/unit/boot/ +pnpm --filter ghost exec vitest run --config vitest.config.inventory.ts +pnpm lint:oxlint +pnpm lint:boundaries +pnpm check +``` + +`pnpm lint:oxlint` applies `ghost/service-root-shape` to the root and +`ghost/boot-awaits-service-init` to `boot.js`. +`pnpm lint:boundaries` checks the implementation's imports. The inventory test +checks the directory has an `index.ts` root and that extras match the catalogue. + +Commit with the repository commit skill, then run on the committed result: + +```sh +pnpm gx services verify +``` + +It needs a clean tree on a branch that contains the fetched `origin/main`. It +repeats the checks above, runs the full unit suite and confirms a boot test +fails when boot stops waiting for this root's `init()`. Run it again after +every rebase or fix. + +Fix failures in the service rather than disabling a check. Report the commands +you ran and anything still failing. diff --git a/.agents/skills/migrate-service/SKILL.md b/.agents/skills/migrate-service/SKILL.md index 3c4a0cf59733..4a20e0a7399f 100644 --- a/.agents/skills/migrate-service/SKILL.md +++ b/.agents/skills/migrate-service/SKILL.md @@ -10,6 +10,9 @@ an execution workflow, not permission to redesign a service's lifecycle. The [services guide](../../../ghost/core/server/services/README.md) is the authoring guide; read it rather than copying an earlier migration blindly. +For a new service, use [add-service](../add-service/SKILL.md) to generate and +complete the root instead. + ## 1. Establish the starting point - Read the root and nearest `AGENTS.md`, the @@ -20,9 +23,9 @@ guide; read it rather than copying an earlier migration blindly. - Inspect status, existing branches/worktrees and related PRs. Preserve unrelated work. Fetch `origin` and start from current `origin/main`; refresh dependencies with `pnpm bootstrap` in a fresh checkout or after dependency changes. -- Read this service's entry in - `ghost/core/server/services/service-inventory.yaml` and any existing migration - plan. If a plan-registry skill is available, use it to find/update that plan; +- Read this service's entry under `services` in + `ghost/core/server/services/legacy-service-inventory.yaml` and any existing + migration plan. If a plan-registry skill is available, use it to find/update that plan; do not create a competing plan in the repository. - Verify prerequisites are merged. An open tests or enforcement PR is not main. Preparation can proceed against a proposed policy, but record its exact head @@ -66,12 +69,14 @@ Do not inject stateless utilities to evade the policy or duplicate shared helper Inspect the source before adding a library allowance. Justify why the dependency is a library rather than an application-owned instance, and allow only its exact entry or file. Include the reason and a boundary regression in the migration PR -that needs the allowance. Assert each rejected target as well as its rule and -source in boundary regressions. Keep allowances out of standalone skill/tooling -PRs. +that needs the allowance. Write out each file the allowance admits in full, as +dependency-cruiser resolves it from source and from built output, in a boundary +regression; `gx services verify` looks for the literal path, not one built from +variables. Assert each rejected target as well as its rule and source. Keep +allowances out of standalone skill/tooling PRs. Seek review when that distinction is unclear or a broader policy change is -needed; do not widen the rule merely to make lint pass. Normal inventory and -root-shape opt-ins still belong in each migration. +needed; do not widen the rule merely to make lint pass. Deleting the service's +legacy entry still belongs in each migration. Preserve late acquisition with getters/factories when dependencies are unavailable at boot. Inspect `pnpm gx services report ` and the full @@ -146,23 +151,38 @@ preparation. The only new cases permitted in the migration commit are boundary regressions for new exact dependency allowances. Never weaken assertions, coverage gates, lint or types to make the refactor pass. -## 5. Update metadata and verify - -Update this service's inventory entry: `migrated`, entry points, evidence, -contracts, extras and remaining gaps. Repair affected file references and -startup-order descriptions in other entries mechanically, without changing -their unrelated assessments. -Preserve historical audit provenance; -record the inspected base and distinguish old evidence from new validation. -Do not restore manual totals or erase unrelated backlog items. - -Opt the root into `ghost/service-root-shape` in `.oxlintrc.json` as required by -the current configuration; the tooling scope check must agree with the inventory. -`migrated: true` also opts implementations into the boundary checks. Do not claim enforcement passed if that policy was +## 5. Update the inventory and verify + +A migrated service is no longer legacy: + +- Delete its entry under `services` in the legacy service inventory. Git + history keeps the audit record. +- Delete all its entries from `.dependency-cruiser-known-violations.json`. A + service that is not legacy cannot have any. +- If the root declares extras, move their catalogue to the service's entry in + the inventory's `followUps` section. A suggested future home, and + notes on what `defineService` does not do for the service yet, go there too. + That entry holds nothing else; leave it out when nothing is open. +- Repair affected file references and startup-order descriptions in other + legacy entries mechanically, without changing their unrelated assessments. + An audit SHA you add must be a commit on main: a branch commit disappears on + squash merge. + +There is no lint list to update. Deleting the entry applies +`ghost/service-root-shape` to the root and full boundary enforcement to the +implementation. It also applies `ghost/boot-awaits-service-init` and the +standard services boot test: boot must bind the root with `.default` and await +its `init()`, as +[creating a service](../../../ghost/core/server/services/README.md#creating-a-service) +shows. Never add a legacy entry or defer a service's dependency +checks: CI rejects both. Do not claim enforcement passed if that policy was only checked in a temporary integration or is still awaiting merge. -Run focused tests before/after, relevant real consumer/DB checks, root-shape and -inventory validation, lint/typechecks and the default `pnpm check`. Run one full +Run focused tests before/after, relevant real consumer/DB checks and the default +`pnpm check`, then `pnpm gx services verify ` on the committed result. Repeat +`gx services verify` after every rebase or fix: hooks do not run during a rebase. +Before a PR is opened or marked ready, an agent that did not write the change runs +the [verify-service-change skill](../verify-service-change/SKILL.md). Run one full local validation at a time. Investigate failures from fresh output; a passing retry or an unchanged file alone does not establish that a failure belongs to main. Keep unrelated fixes out of the migration. diff --git a/.agents/skills/verify-service-change/SKILL.md b/.agents/skills/verify-service-change/SKILL.md new file mode 100644 index 000000000000..74b3757dbacf --- /dev/null +++ b/.agents/skills/verify-service-change/SKILL.md @@ -0,0 +1,96 @@ +--- +name: verify-service-change +description: Independently verify a service characterization or defineService migration before its pull request is opened or marked ready. Use when checking tests-only characterization or a service migration that someone else wrote. +--- + +# Verify a service change + +Check another author's work from the code and its claims. An author's own results +show what they thought to test, so they cannot show what they missed. + +## Start here + +Use only: + +- the branch or pull request diff +- the PR description, commit messages and inventory changes +- the output of `pnpm gx services verify --json` +- the unchanged service source, its consumers and existing tests in your checkout + +Do not read the author's mutation list, a coordinator's summary or an earlier +review. Ignore them if the brief includes them. + +Work in your own checkout of the commit, and restore every mutation. Do not commit, +push or edit the branch: report findings to whoever owns it. Run database suites +one at a time. + +## Check every change + +1. `gx services verify` has no `fail` result. +2. For each `review` line, read the diff and decide whether it is still true. A + stale inventory sentence is a finding. +3. Map every claim to evidence: each inventory sentence added or changed, and each + statement in the PR description and commit messages. "Unchanged" is a claim. +4. Ask whether this is the simplest way. List anything the change does not need. + +## Characterization + +For each test and inventory sentence, ask: does it do what it says, is it the +simplest way, and is every claim asserted? + +Write your own mutations from the production code and run at least one per claim. +Each must fail the test named for that behaviour. Include these variants where +they apply: + +- a module loaded at import rather than on use, checked by a test that observes + the load before the module is first required +- every instance of a repeated dependency, not only the first +- a different error with the same message +- the success path as well as each failure path +- a fake clock away from the boundary it is set to +- a chained handler where the test only inspects the first call + +Say when fakes hide the risk, such as a test that fakes Express for code whose +regression would only show in a booted app. + +## Migration + +Fill in one row for each dependency, resource and consumer: + +| Item | Old: when and how often resolved | New: when and how often resolved | Read by consumers at | On failure | +| ---- | -------------------------------- | -------------------------------- | -------------------- | ---------- | + +Every difference needs a reason in the PR description. Look hardest at: + +- work the old root repeated on each boot in one process, now run once +- reads at module load, including route loaders and test harnesses +- fixtures and consumer tests that still use the old shape +- failures that moved between boot and the first request +- anything left half-started when init fails and is retried +- whether order between services has a boot test; the standard services boot + test only covers that boot waits for this root and fails when it fails + +Then check the shape of the change: + +- A stateless utility must be imported under an exact allowance, not injected. +- Injected logging is `GhostLogger` or a `Pick` of it, and class tests use + `createLoggingFake()`. +- A root that still builds itself in two steps is not finished. + +Note in the report if consumer files changed outnumber the service's own files, or +if the inventory disposition is not `migrate`. Both can mean the service should not +be migrated this way, so finish the review and raise them for the owner. + +## Report + +| Claim or row | Evidence | Mutation and result | Finding | Severity | +| ------------ | -------- | ------------------- | ------- | -------- | + +Use three severities: + +- **Blocker:** a regression, a broken consumer, or a claim that is false. +- **Should fix:** a claim the tests do not prove, or stale text. +- **Note:** a gap the change does not claim to close. + +Finish with a verdict. Say "ready" when no row is a blocker or an unresolved "should +fix", and list anything you did not run. diff --git a/.changeset/changelogs/@tryghost!adapter-base-scheduling@0.2.10.md b/.changeset/changelogs/@tryghost!adapter-base-scheduling@0.2.10.md new file mode 100644 index 000000000000..e2acf5921a64 --- /dev/null +++ b/.changeset/changelogs/@tryghost!adapter-base-scheduling@0.2.10.md @@ -0,0 +1,7 @@ +## 0.2.10 + +### Patch Changes + +- Bumped TryGhost framework dependencies to their latest versions + +- Bumped TryGhost framework dependencies to their latest versions diff --git a/.changeset/changelogs/@tryghost!adapter-base-sso@0.1.9.md b/.changeset/changelogs/@tryghost!adapter-base-sso@0.1.9.md new file mode 100644 index 000000000000..453702ecb03c --- /dev/null +++ b/.changeset/changelogs/@tryghost!adapter-base-sso@0.1.9.md @@ -0,0 +1,5 @@ +## 0.1.9 + +### Patch Changes + +- Bumped TryGhost framework dependencies to their latest versions diff --git a/.changeset/changelogs/@tryghost!kg-card-factory@5.2.10.md b/.changeset/changelogs/@tryghost!kg-card-factory@5.2.10.md new file mode 100644 index 000000000000..acbaeda3f9c8 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-card-factory@5.2.10.md @@ -0,0 +1,5 @@ +## 5.2.10 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-clean-basic-html@4.3.10.md b/.changeset/changelogs/@tryghost!kg-clean-basic-html@4.3.10.md new file mode 100644 index 000000000000..16cc7771c944 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-clean-basic-html@4.3.10.md @@ -0,0 +1,5 @@ +## 4.3.10 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-converters@1.2.10.md b/.changeset/changelogs/@tryghost!kg-converters@1.2.10.md new file mode 100644 index 000000000000..4da8e7942104 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-converters@1.2.10.md @@ -0,0 +1,5 @@ +## 1.2.10 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-default-cards@10.3.11.md b/.changeset/changelogs/@tryghost!kg-default-cards@10.3.11.md new file mode 100644 index 000000000000..97793a82fa4d --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-default-cards@10.3.11.md @@ -0,0 +1,7 @@ +## 10.3.11 + +### Patch Changes + +- Updated dependencies + +- Updated TryGhost SDK dependencies diff --git a/.changeset/changelogs/@tryghost!kg-default-nodes@2.3.1.md b/.changeset/changelogs/@tryghost!kg-default-nodes@2.3.1.md new file mode 100644 index 000000000000..9468421d2f23 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-default-nodes@2.3.1.md @@ -0,0 +1,11 @@ +## 2.3.1 + +### Patch Changes + +- Updated dependencies + +- Updated dependencies + +- Fixed links whose query strings look like HTML entities without a semicolon, such as `®ion=` or `¶=`, being corrupted in rendered cards. + +- Updated TryGhost SDK dependencies diff --git a/.changeset/changelogs/@tryghost!kg-default-transforms@1.3.10.md b/.changeset/changelogs/@tryghost!kg-default-transforms@1.3.10.md new file mode 100644 index 000000000000..3b1a9e994051 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-default-transforms@1.3.10.md @@ -0,0 +1,5 @@ +## 1.3.10 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-html-to-lexical@1.4.5.md b/.changeset/changelogs/@tryghost!kg-html-to-lexical@1.4.5.md new file mode 100644 index 000000000000..96013b27cc73 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-html-to-lexical@1.4.5.md @@ -0,0 +1,5 @@ +## 1.4.5 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-lexical-html-renderer@1.5.4.md b/.changeset/changelogs/@tryghost!kg-lexical-html-renderer@1.5.4.md new file mode 100644 index 000000000000..57d2230d7602 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-lexical-html-renderer@1.5.4.md @@ -0,0 +1,5 @@ +## 1.5.4 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-markdown-html-renderer@7.2.12.md b/.changeset/changelogs/@tryghost!kg-markdown-html-renderer@7.2.12.md new file mode 100644 index 000000000000..e70276ebec67 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-markdown-html-renderer@7.2.12.md @@ -0,0 +1,5 @@ +## 7.2.12 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-unsplash-selector@0.4.11.md b/.changeset/changelogs/@tryghost!kg-unsplash-selector@0.4.11.md deleted file mode 100644 index 1f8f704fd199..000000000000 --- a/.changeset/changelogs/@tryghost!kg-unsplash-selector@0.4.11.md +++ /dev/null @@ -1,5 +0,0 @@ -## 0.4.11 - -### Patch Changes - -- Bumped Playwright to 1.65.0 diff --git a/.changeset/changelogs/@tryghost!kg-unsplash-selector@0.4.12.md b/.changeset/changelogs/@tryghost!kg-unsplash-selector@0.4.12.md new file mode 100644 index 000000000000..53a8b31250c7 --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-unsplash-selector@0.4.12.md @@ -0,0 +1,7 @@ +## 0.4.12 + +### Patch Changes + +- Updated dependencies + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!kg-utils@1.1.10.md b/.changeset/changelogs/@tryghost!kg-utils@1.1.10.md new file mode 100644 index 000000000000..ee016e59bf5b --- /dev/null +++ b/.changeset/changelogs/@tryghost!kg-utils@1.1.10.md @@ -0,0 +1,5 @@ +## 1.1.10 + +### Patch Changes + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!koenig-lexical@2.3.0.md b/.changeset/changelogs/@tryghost!koenig-lexical@2.3.0.md deleted file mode 100644 index cab5a43e4b2f..000000000000 --- a/.changeset/changelogs/@tryghost!koenig-lexical@2.3.0.md +++ /dev/null @@ -1,13 +0,0 @@ -## 2.3.0 - -### Minor Changes - -- Added File card support in the email editor. - -### Patch Changes - -- Bumped Playwright to 1.65.0 - -- Tested email editor (de)serialization. No external impact. - -- Moved the video card acceptance tests from Firefox to Google Chrome diff --git a/.changeset/changelogs/@tryghost!koenig-lexical@2.3.1.md b/.changeset/changelogs/@tryghost!koenig-lexical@2.3.1.md new file mode 100644 index 000000000000..9be7cb8e50aa --- /dev/null +++ b/.changeset/changelogs/@tryghost!koenig-lexical@2.3.1.md @@ -0,0 +1,11 @@ +## 2.3.1 + +### Patch Changes + +- Updated dependencies + +- Updated dependencies + +- Updated dependencies + +- Updated dependencies diff --git a/.changeset/changelogs/@tryghost!metafield-types@0.5.0.md b/.changeset/changelogs/@tryghost!metafield-types@0.6.0.md similarity index 54% rename from .changeset/changelogs/@tryghost!metafield-types@0.5.0.md rename to .changeset/changelogs/@tryghost!metafield-types@0.6.0.md index f880df965b8e..5694c5d65479 100644 --- a/.changeset/changelogs/@tryghost!metafield-types@0.5.0.md +++ b/.changeset/changelogs/@tryghost!metafield-types@0.6.0.md @@ -1,9 +1,13 @@ -## 0.5.0 +## 0.6.0 ### Minor Changes - Added a way to build a new field type behind a Labs flag. `FIELD_TYPE_FLAGS` lists the types still in development with the Labs flag each is behind, and a type with no flag there is released. `isCreatableType(type, isFlagOn)` says whether a field of a type can be created given which flags are on. Every type is released today. +- Added `hasOnlyPhoneCharacters(text)` to the `./phone` entry point. It returns whether text contains only characters valid in a phone number (digits, +, spaces and the punctuation libphonenumber-js accepts), so a phone input can flag an invalid character while typing without loading the library. A number it flags is one the phone field's validation rejects too, except an RFC 3966 `tel:` URI, which the library accepts. + +- Added `phoneCountryOfTimeZone`, the country of a time zone such as Portugal for `Europe/Lisbon`, from the browser's own time zone data. `startPhoneEntry` takes an optional time zone and, for a field holding no number, starts from its country before the country of the reader's language, as many browsers speak `en-US` wherever they are. Safari names some zones newer than its own data does, such as `Asia/Kolkata`, and its readers there are given their language's country, as before. + - Added the `phone` field type, a text leaf in the new `phone` format, developed behind the `customFieldTypePhone` Labs flag. Its rule keeps a number in E.164 (`+442079460000`) however it was written, after a + or the 00 most countries dial abroad with. It accepts only a number its country has given out, as libphonenumber-js's full metadata has them, and refuses one without its country code, one with anything else around it, and one with an extension. `phoneNumberIn(text, country)` reads a phone number the same way, as it is dialled in a country unless it was written with a country code of its own, and gives it in E.164, or undefined when it isn't a number a phone field could keep. @@ -12,8 +16,18 @@ The `./phone` entry point, which a browser app can load without zod or libphonenumber-js, holds what a phone input beside a choice of country needs: what it starts from, shows and sends as someone types or picks a country (`startPhoneEntry`, `typeNumber`, `pickCountry`, `shownCountry`, `withCallingCode`), each country's calling code and way of dialling abroad (`CALLING_CODES`, `INTERNATIONAL_PREFIXES`), what tells apart the countries sharing a calling code (`SHARED_CODES`), `phoneCountryOptions`, `readCallingCode`, `phoneCountryOfLocales`, `isPhoneCountry` and `flagOf`. +- Removed `flagOf` from the `./phone` entry point. It drew a country's flag as an emoji, which Windows shows as two letters, and nothing uses it now that Portal's phone input shows the calling code alone. + - Renamed a text leaf's `size` to `format`, `TEXT_SIZES` to `TEXT_FORMATS` and `TextSize` to `TextFormat`. What sets a text leaf apart isn't always how much text it holds: a format can also be text in a particular shape, such as a phone number. ### Patch Changes +- In Node, libphonenumber-js now loads the first time a phone number is read rather than when the package is imported, so a server that never reads one doesn't hold its metadata. Bundles still load it up front. + - Changed the README to point contributors at the package's new docs folder. + +- Changed the package's repository directory to `contracts/metafield-types`, where its source now lives in the Ghost repository. + +- Changed `phoneCountryOptions` to put each calling code in parentheses, such as `United Kingdom (+44)`. + +- Changed phone number validation errors to be specific to the number's country. An invalid number now gets an example from its own country, such as `+55 11 96123 4567` for a +55 number, where every error used to show a British one. The error also says when the number is too short or too long, or when its country code doesn't exist. diff --git a/.changeset/chilly-dogs-collect.md b/.changeset/chilly-dogs-collect.md new file mode 100644 index 000000000000..c6de824c42c0 --- /dev/null +++ b/.changeset/chilly-dogs-collect.md @@ -0,0 +1,5 @@ +--- +"@tryghost/kg-default-nodes": patch +--- + +Updated dependencies diff --git a/.changeset/chilly-lions-walk.md b/.changeset/chilly-lions-walk.md deleted file mode 100644 index 8009f8db4ebf..000000000000 --- a/.changeset/chilly-lions-walk.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@tryghost/koenig-lexical": patch ---- - -Tested email editor (de)serialization. No external impact. diff --git a/.changeset/email-file-card.md b/.changeset/email-file-card.md deleted file mode 100644 index b8d45827f786..000000000000 --- a/.changeset/email-file-card.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@tryghost/koenig-lexical": minor ---- - -Added File card support in the email editor. diff --git a/.changeset/framework-errors-bump.md b/.changeset/framework-errors-bump.md new file mode 100644 index 000000000000..40a4c03a10bb --- /dev/null +++ b/.changeset/framework-errors-bump.md @@ -0,0 +1,5 @@ +--- +"@tryghost/adapter-base-sso": patch +--- + +Bumped TryGhost framework dependencies to their latest versions diff --git a/.changeset/framework-typings-bump.md b/.changeset/framework-typings-bump.md new file mode 100644 index 000000000000..6b79742f9556 --- /dev/null +++ b/.changeset/framework-typings-bump.md @@ -0,0 +1,5 @@ +--- +"@tryghost/adapter-base-scheduling": patch +--- + +Bumped TryGhost framework dependencies to their latest versions diff --git a/.changeset/koenig-video-tests-chrome.md b/.changeset/koenig-video-tests-chrome.md deleted file mode 100644 index c29cf4ca1cb7..000000000000 --- a/.changeset/koenig-video-tests-chrome.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@tryghost/koenig-lexical": patch ---- - -Moved the video card acceptance tests from Firefox to Google Chrome diff --git a/.changeset/bump-playwright-1-65.md b/.changeset/lazy-cows-sneeze.md similarity index 74% rename from .changeset/bump-playwright-1-65.md rename to .changeset/lazy-cows-sneeze.md index 90f49351b218..d9c67c828235 100644 --- a/.changeset/bump-playwright-1-65.md +++ b/.changeset/lazy-cows-sneeze.md @@ -3,4 +3,4 @@ "@tryghost/kg-unsplash-selector": patch --- -Bumped Playwright to 1.65.0 +Updated dependencies diff --git a/.changeset/lazy-phone-metadata.md b/.changeset/lazy-phone-metadata.md new file mode 100644 index 000000000000..c472a848e3b4 --- /dev/null +++ b/.changeset/lazy-phone-metadata.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": patch +--- + +In Node, libphonenumber-js now loads the first time a phone number is read rather than when the package is imported, so a server that never reads one doesn't hold its metadata. Bundles still load it up front. diff --git a/.changeset/ledger.yaml b/.changeset/ledger.yaml index dbdc3349e264..05ac65be272f 100644 --- a/.changeset/ledger.yaml +++ b/.changeset/ledger.yaml @@ -29,6 +29,11 @@ dir: packages/adapters/scheduling-base intents: - typed-logging-args +"@tryghost/adapter-base-scheduling@0.2.10": + dir: packages/adapters/scheduling-base + intents: + - framework-typings-bump + - weak-cats-add "@tryghost/adapter-base-scheduling@0.2.2": dir: packages/adapters/scheduling-base intents: @@ -103,6 +108,14 @@ dir: packages/adapters/sso-base intents: - framework-bump-errors-clone +"@tryghost/adapter-base-sso@0.1.9": + dir: packages/adapters/sso-base + intents: + - framework-errors-bump +"@tryghost/kg-card-factory@5.2.10": + dir: koenig/kg-card-factory + intents: + - olive-swans-teach "@tryghost/kg-card-factory@5.2.4": dir: koenig/kg-card-factory intents: @@ -124,6 +137,10 @@ intents: - breezy-owls-help - nice-boats-push +"@tryghost/kg-clean-basic-html@4.3.10": + dir: koenig/kg-clean-basic-html + intents: + - olive-swans-teach "@tryghost/kg-clean-basic-html@4.3.4": dir: koenig/kg-clean-basic-html intents: @@ -146,6 +163,10 @@ intents: - breezy-owls-help - nice-boats-push +"@tryghost/kg-converters@1.2.10": + dir: koenig/kg-converters + intents: + - olive-swans-teach "@tryghost/kg-converters@1.2.4": dir: koenig/kg-converters intents: @@ -176,6 +197,11 @@ intents: - breezy-owls-help - nice-boats-push +"@tryghost/kg-default-cards@10.3.11": + dir: koenig/kg-default-cards + intents: + - olive-swans-teach + - tryghost-sdk-deps "@tryghost/kg-default-cards@10.3.4": dir: koenig/kg-default-cards intents: @@ -257,6 +283,17 @@ - heavy-swans-dream - nice-boats-push - product-card-image-alt +"@tryghost/kg-default-nodes@2.3.1": + dir: koenig/kg-default-nodes + intents: + - chilly-dogs-collect + - olive-swans-teach + - strict-entity-decoding + - tryghost-sdk-deps +"@tryghost/kg-default-transforms@1.3.10": + dir: koenig/kg-default-transforms + intents: + - olive-swans-teach "@tryghost/kg-default-transforms@1.3.4": dir: koenig/kg-default-transforms intents: @@ -298,6 +335,10 @@ dir: koenig/kg-html-to-lexical intents: - breezy-owls-help +"@tryghost/kg-html-to-lexical@1.4.5": + dir: koenig/kg-html-to-lexical + intents: + - olive-swans-teach "@tryghost/kg-lexical-html-renderer@1.5.0": dir: koenig/kg-lexical-html-renderer intents: @@ -318,6 +359,10 @@ - breezy-owls-help - heavy-swans-dream - modern-rice-boil +"@tryghost/kg-lexical-html-renderer@1.5.4": + dir: koenig/kg-lexical-html-renderer + intents: + - olive-swans-teach "@tryghost/kg-markdown-html-renderer@7.2.10": dir: koenig/kg-markdown-html-renderer intents: @@ -327,6 +372,10 @@ intents: - breezy-owls-help - nice-boats-push +"@tryghost/kg-markdown-html-renderer@7.2.12": + dir: koenig/kg-markdown-html-renderer + intents: + - olive-swans-teach "@tryghost/kg-markdown-html-renderer@7.2.4": dir: koenig/kg-markdown-html-renderer intents: @@ -366,6 +415,11 @@ dir: koenig/kg-unsplash-selector intents: - bump-playwright-1-65 +"@tryghost/kg-unsplash-selector@0.4.12": + dir: koenig/kg-unsplash-selector + intents: + - lazy-cows-sneeze + - olive-swans-teach "@tryghost/kg-unsplash-selector@0.4.4": dir: koenig/kg-unsplash-selector intents: @@ -398,6 +452,10 @@ dir: koenig/kg-unsplash-selector intents: - modern-eagles-shout +"@tryghost/kg-utils@1.1.10": + dir: koenig/kg-utils + intents: + - olive-swans-teach "@tryghost/kg-utils@1.1.4": dir: koenig/kg-utils intents: @@ -532,6 +590,13 @@ - chilly-lions-walk - email-file-card - koenig-video-tests-chrome +"@tryghost/koenig-lexical@2.3.1": + dir: koenig/koenig-lexical + intents: + - lazy-cows-sneeze + - olive-swans-teach + - proud-pears-ring + - wicked-grapes-stand "@tryghost/metafield-types@0.1.1": dir: packages/metafield-types intents: @@ -570,6 +635,20 @@ - metafield-types-docs-moved - phone-custom-fields - text-leaf-format +"@tryghost/metafield-types@0.6.0": + dir: contracts/metafield-types + intents: + - field-types-behind-labs-flags + - lazy-phone-metadata + - metafield-types-docs-moved + - metafield-types-moved-to-contracts + - phone-character-check + - phone-codes-in-parentheses + - phone-country-from-time-zone + - phone-custom-fields + - phone-flag-removed + - phone-refusals-by-country + - text-leaf-format ghost-storage-base@3.0.0: dir: packages/adapters/storage-base intents: diff --git a/.changeset/metafield-types-moved-to-contracts.md b/.changeset/metafield-types-moved-to-contracts.md new file mode 100644 index 000000000000..62171b6f4b5c --- /dev/null +++ b/.changeset/metafield-types-moved-to-contracts.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": patch +--- + +Changed the package's repository directory to `contracts/metafield-types`, where its source now lives in the Ghost repository. diff --git a/.changeset/olive-swans-teach.md b/.changeset/olive-swans-teach.md new file mode 100644 index 000000000000..37386708590c --- /dev/null +++ b/.changeset/olive-swans-teach.md @@ -0,0 +1,16 @@ +--- +"@tryghost/koenig-lexical": patch +"@tryghost/kg-utils": patch +"@tryghost/kg-unsplash-selector": patch +"@tryghost/kg-markdown-html-renderer": patch +"@tryghost/kg-lexical-html-renderer": patch +"@tryghost/kg-html-to-lexical": patch +"@tryghost/kg-default-transforms": patch +"@tryghost/kg-default-nodes": patch +"@tryghost/kg-default-cards": patch +"@tryghost/kg-converters": patch +"@tryghost/kg-clean-basic-html": patch +"@tryghost/kg-card-factory": patch +--- + +Updated dependencies diff --git a/.changeset/phone-character-check.md b/.changeset/phone-character-check.md new file mode 100644 index 000000000000..fbe778e866d5 --- /dev/null +++ b/.changeset/phone-character-check.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": minor +--- + +Added `hasOnlyPhoneCharacters(text)` to the `./phone` entry point. It returns whether text contains only characters valid in a phone number (digits, +, spaces and the punctuation libphonenumber-js accepts), so a phone input can flag an invalid character while typing without loading the library. A number it flags is one the phone field's validation rejects too, except an RFC 3966 `tel:` URI, which the library accepts. diff --git a/.changeset/phone-codes-in-parentheses.md b/.changeset/phone-codes-in-parentheses.md new file mode 100644 index 000000000000..d34630d139f4 --- /dev/null +++ b/.changeset/phone-codes-in-parentheses.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": patch +--- + +Changed `phoneCountryOptions` to put each calling code in parentheses, such as `United Kingdom (+44)`. diff --git a/.changeset/phone-country-from-time-zone.md b/.changeset/phone-country-from-time-zone.md new file mode 100644 index 000000000000..bd4cff087f70 --- /dev/null +++ b/.changeset/phone-country-from-time-zone.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": minor +--- + +Added `phoneCountryOfTimeZone`, the country of a time zone such as Portugal for `Europe/Lisbon`, from the browser's own time zone data. `startPhoneEntry` takes an optional time zone and, for a field holding no number, starts from its country before the country of the reader's language, as many browsers speak `en-US` wherever they are. Safari names some zones newer than its own data does, such as `Asia/Kolkata`, and its readers there are given their language's country, as before. diff --git a/.changeset/phone-flag-removed.md b/.changeset/phone-flag-removed.md new file mode 100644 index 000000000000..a78f3b659f8c --- /dev/null +++ b/.changeset/phone-flag-removed.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": minor +--- + +Removed `flagOf` from the `./phone` entry point. It drew a country's flag as an emoji, which Windows shows as two letters, and nothing uses it now that Portal's phone input shows the calling code alone. diff --git a/.changeset/phone-refusals-by-country.md b/.changeset/phone-refusals-by-country.md new file mode 100644 index 000000000000..6eba6a0720ee --- /dev/null +++ b/.changeset/phone-refusals-by-country.md @@ -0,0 +1,5 @@ +--- +"@tryghost/metafield-types": patch +--- + +Changed phone number validation errors to be specific to the number's country. An invalid number now gets an example from its own country, such as `+55 11 96123 4567` for a +55 number, where every error used to show a British one. The error also says when the number is too short or too long, or when its country code doesn't exist. diff --git a/.changeset/proud-pears-ring.md b/.changeset/proud-pears-ring.md new file mode 100644 index 000000000000..2f762631c3a6 --- /dev/null +++ b/.changeset/proud-pears-ring.md @@ -0,0 +1,5 @@ +--- +"@tryghost/koenig-lexical": patch +--- + +Updated dependencies diff --git a/.changeset/strict-entity-decoding.md b/.changeset/strict-entity-decoding.md new file mode 100644 index 000000000000..4c90462a679e --- /dev/null +++ b/.changeset/strict-entity-decoding.md @@ -0,0 +1,5 @@ +--- +"@tryghost/kg-default-nodes": patch +--- + +Fixed links whose query strings look like HTML entities without a semicolon, such as `®ion=` or `¶=`, being corrupted in rendered cards. diff --git a/.changeset/tryghost-sdk-deps.md b/.changeset/tryghost-sdk-deps.md new file mode 100644 index 000000000000..5449c3aa3bd3 --- /dev/null +++ b/.changeset/tryghost-sdk-deps.md @@ -0,0 +1,7 @@ +--- +"@tryghost/kg-default-cards": patch +"@tryghost/kg-default-nodes": patch +"@tryghost/koenig-lexical": none +--- + +Updated TryGhost SDK dependencies diff --git a/.changeset/weak-cats-add.md b/.changeset/weak-cats-add.md new file mode 100644 index 000000000000..6b79742f9556 --- /dev/null +++ b/.changeset/weak-cats-add.md @@ -0,0 +1,5 @@ +--- +"@tryghost/adapter-base-scheduling": patch +--- + +Bumped TryGhost framework dependencies to their latest versions diff --git a/.changeset/wicked-grapes-stand.md b/.changeset/wicked-grapes-stand.md new file mode 100644 index 000000000000..2f762631c3a6 --- /dev/null +++ b/.changeset/wicked-grapes-stand.md @@ -0,0 +1,5 @@ +--- +"@tryghost/koenig-lexical": patch +--- + +Updated dependencies diff --git a/.claude/skills/add-service b/.claude/skills/add-service new file mode 120000 index 000000000000..fc664e042fa6 --- /dev/null +++ b/.claude/skills/add-service @@ -0,0 +1 @@ +../../.agents/skills/add-service \ No newline at end of file diff --git a/.claude/skills/verify-service-change b/.claude/skills/verify-service-change new file mode 120000 index 000000000000..f0eb24fabfa8 --- /dev/null +++ b/.claude/skills/verify-service-change @@ -0,0 +1 @@ +../../.agents/skills/verify-service-change \ No newline at end of file diff --git a/.coderabbit.yaml b/.coderabbit.yaml index ecc8c63e10e0..4b6cb0de971f 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -23,6 +23,7 @@ reviews: - '!ghost/**/build/**' - '!koenig/**/build/**' - '!packages/**/build/**' + - '!contracts/**/build/**' - '!e2e/build/**' - '!**/built/**' - '!**/umd/**' @@ -157,7 +158,7 @@ reviews: shape and volume, deploy/rollback compatibility, transaction and locking risk, idempotency, export/integrity updates, and preservation of constraints/defaults. Do not duplicate migration filename, loop, schema-field, or integrity-check CI. - - path: 'packages/**' + - path: '{packages,contracts}/**' instructions: | Review package boundaries and production consumption: minimal explicit exports, declared runtime dependencies, source-condition versus built-output parity, @@ -259,15 +260,19 @@ knowledge_base: - files: 'docs/contributing/testing.md' applyTo: '**/{test,tests}/**,**/*{.,-}{test,spec}.{js,jsx,ts,tsx}' - files: 'docs/codebase/monorepo-structure.md' - applyTo: 'package.json,pnpm-workspace.yaml,nx.json,apps/**,packages/**,ghost/**,koenig/**' + applyTo: 'package.json,pnpm-workspace.yaml,nx.json,apps/**,packages/**,contracts/**,ghost/**,koenig/**' - files: 'docs/codebase/configuration.md' applyTo: 'ghost/core/shared/config/**,ghost/config*.json*' - files: 'docs/codebase/internal-caching.md' applyTo: 'ghost/core/server/adapters/cache/**,ghost/core/server/adapters/lib/redis/**,ghost/core/server/**/*cache*.{js,ts},ghost/core/shared/config/**,packages/adapters/cache-base/**' - files: 'docs/codebase/jobs.md' applyTo: 'ghost/core/server/services/**' + - files: 'ghost/core/server/services/README.md' + applyTo: 'ghost/core/server/services/**' - files: 'packages/README.md' - applyTo: 'packages/**' + applyTo: 'packages/**,contracts/**' + - files: 'contracts/README.md' + applyTo: 'contracts/**' - files: 'apps/shade/AGENTS.md' applyTo: 'apps/admin/**,apps/activitypub/**,apps/admin-x-framework/**,apps/shade/**' - files: 'e2e/README.md,e2e/AGENTS.md' diff --git a/.dependency-cruiser-known-violations.json b/.dependency-cruiser-known-violations.json new file mode 100644 index 000000000000..273682d17e70 --- /dev/null +++ b/.dependency-cruiser-known-violations.json @@ -0,0 +1,1472 @@ +[ + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/activitypub/activity-pub-service-wrapper.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/activitypub/activity-pub-service-wrapper.js", + "to": "ghost/core/server/data/db/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/activitypub/activity-pub-service-wrapper.js", + "to": "ghost/core/server/lib/common/events.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/activitypub/activity-pub-service-wrapper.js", + "to": "ghost/core/server/services/identity-tokens/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/activitypub/activity-pub-service-wrapper.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/activitypub/activity-pub-service-wrapper.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/adapter-paths.ts", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/cache-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/jobs-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/redirects-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/route-settings-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/scheduling-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/sso-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/adapter-manager/base-classes.ts", + "to": "packages/adapters/storage-base/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/csv/parse.ts", + "to": "fs-extra" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/assets.ts", + "to": "ghost/core/server/data/importer/content-files.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/importer.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/importer.ts", + "to": "moment-timezone" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/media.ts", + "to": "ghost/core/server/services/media-inliner/origin-schemes.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/row.ts", + "to": "temporal-polyfill" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/source.ts", + "to": "fs-extra" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/source.ts", + "to": "ghost/core/server/data/importer/import-archive.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/content-import/import/source.ts", + "to": "glob" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/custom-redirects/redirects-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/custom-redirects/redirects-service.ts", + "to": "ghost/core/server/web/shared/dynamic-redirect-manager.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/custom-redirects/utils.ts", + "to": "moment-timezone" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/custom-redirects/validation.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-address/email-address-service-wrapper.js", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-address/email-address-service-wrapper.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-address/email-address-service-wrapper.js", + "to": "ghost/core/shared/labs.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-address/email-address-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/email-analytics-service-wrapper.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/email-analytics-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/fetch-mailgun-events.ts", + "to": "ghost/core/server/lib/mailgun/mailgun-client.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/jobs/email-analytics-job-scheduler.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/jobs/email-analytics-job-scheduler.ts", + "to": "ghost/core/server/services/jobs-service/cron.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/jobs/email-analytics-job-scheduler.ts", + "to": "moment" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/jobs/index.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/jobs/index.js", + "to": "ghost/core/server/services/jobs-service/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/jobs/index.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/lib/queries.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/lib/queries.ts", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-analytics/newsletter-email-analytics-batch-processor.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/batch-sending-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-event-processor.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-renderer.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-renderer.js", + "to": "fs" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-renderer.js", + "to": "ghost/core/server/services/members/content-gating.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-renderer.js", + "to": "luxon" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/adapters/storage/utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/api/endpoints/utils/serializers/output/utils/url.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/data/db/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/lib/common/events.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/lib/image/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/lib/lexical.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/lib/mailgun/mailgun-client.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/audience-feedback/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/email-address/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/email-analytics/jobs/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/limits.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/link-tracking/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/member-attribution/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/members/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/server/services/url/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/shared/labs.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/shared/sentry.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service-wrapper.js", + "to": "packages/i18n/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/email-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/mailgun-email-provider.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/newsletter-email-event-storage.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/newsletter-email-event-storage.js", + "to": "moment-timezone" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/recipient-accounting.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-service/sending-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/mailgun-email-suppression-list.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/mailgun-email-suppression-list.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/mailgun-email-suppression-list.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/mailgun-email-suppression-list.js", + "to": "ghost/core/server/services/email-service/events/email-bounced-event.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/mailgun-email-suppression-list.js", + "to": "ghost/core/server/services/email-service/events/spam-complaint-event.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/service.js", + "to": "ghost/core/server/lib/mailgun/mailgun-client.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/service.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/service.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/email-suppression-list/service.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift-checkout-adapter.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift-delivery-service.ts", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift-delivery-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift-email-renderer.ts", + "to": "fs" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift-service.ts", + "to": "luxon" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/gift.ts", + "to": "luxon" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/gifts/jobs/index.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/identity-tokens/identity-token-service-wrapper.js", + "to": "ghost/core/server/services/signing-keys/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/identity-tokens/identity-token-service-wrapper.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/data/importer/jobs/content-import-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/content-import/jobs/content-csv-import-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/email-analytics/jobs/email-analytics-automation-fetch-latest-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/email-analytics/jobs/email-analytics-fetch-latest-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/email-analytics/jobs/email-analytics-gift-fetch-latest-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/email-service/jobs/send-email-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/gifts/jobs/clean-gifts-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/gifts/jobs/send-gift-reminders-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/media-inliner/external-media-inliner-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/members/jobs/clean-expired-comped-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/members/jobs/clean-tokens-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/members/jobs/members-import-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/mentions/process-webmention-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/mentions/send-webmentions-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/signing-keys/check-signing-keys-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/tinybird-sync/jobs/tinybird-sync-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/jobs-service/register-job-handlers.ts", + "to": "ghost/core/server/services/update-check/jobs/update-check-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/limits.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/limits.ts", + "to": "ghost/core/server/data/db/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/limits.ts", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/link-click-repository.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/link-click-repository.js", + "to": "ghost/core/shared/sentry.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/link-click-repository.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/link-click-tracking-service.js", + "to": "ghost/core/server/services/link-redirection/redirect-event.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/link-click-tracking-service.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/link-click-tracking-service.js", + "to": "moment" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/link-tracking/post-link-repository.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/mpp-adapter.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/mpp-adapter.ts", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/mpp-adapter.ts", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/mpp-adapter.ts", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "specialist-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/mpp-adapter.ts", + "to": "stripe" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/x402-adapter.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/adapters/x402-adapter.ts", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/content-loader.ts", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/service.ts", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/service.ts", + "to": "ghost/core/shared/labs.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/service.ts", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/stripe/deposit-address-store.ts", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/stripe/deposit-address-store.ts", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/stripe/deposit-address-store.ts", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/stripe/payment-recorder.ts", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/machine-payments/stripe/stripe-client-options.ts", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/members-events/last-seen-at-cache.js", + "to": "moment-timezone" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/members-events/last-seen-at-updater.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/members-events/last-seen-at-updater.js", + "to": "ghost/core/server/services/email-service/events/email-opened-event.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/members-events/last-seen-at-updater.js", + "to": "ghost/core/shared/events/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/members-events/last-seen-at-updater.js", + "to": "moment-timezone" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/service.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/service.js", + "to": "ghost/core/server/data/db/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/service.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/service.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/service.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/slack-notifications/service.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/slack-notifications/service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/slack-notifications/service.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/slack-notifications/service.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/slack-notifications/slack-notifications.js", + "to": "ghost/core/server/lib/request-external.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/milestones/slack-notifications/slack-notifications.js", + "to": "moment" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/notifications/notifications.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/notifications/notifications.js", + "to": "moment-timezone" + }, + { + "rule": "specialist-dependencies", + "from": "ghost/core/server/services/oembed/oembed-service.js", + "to": "@extractus/oembed-extractor" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/oembed-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/oembed-service.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/oembed-service.js", + "to": "packages/image-transform/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/service.js", + "to": "ghost/core/server/lib/request-external.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/service.js", + "to": "ghost/core/server/services/adapter-manager/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/service.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/oembed/twitter-oembed-provider.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/application/offers-api.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/domain/models/shared/value-object.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/offer-bookshelf-repository.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/offer-bookshelf-repository.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/offer-bookshelf-repository.js", + "to": "ghost/core/shared/sentry.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/offer-bookshelf-repository.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/offers-module.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/service.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/service.js", + "to": "ghost/core/server/web/shared/dynamic-redirect-manager.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/service.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/offers/service.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/permissions/actions-map-cache.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/permissions/can-this.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/permissions/can-this.js", + "to": "ghost/core/server/models/role-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/permissions/can-this.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/permissions/providers.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/post-scheduling/post-scheduling.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/post-scheduling/post-scheduling.ts", + "to": "ghost/core/server/adapters/scheduling/build-signed-job.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/post-scheduling/post-scheduling.ts", + "to": "ghost/core/server/lib/common/events.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/post-scheduling/post-scheduling.ts", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/post-scheduling/post-scheduling.ts", + "to": "moment" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-email-handler.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-email-handler.js", + "to": "ghost/core/server/services/email-service/email-service.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-scheduling.js", + "to": "ghost/core/server/api/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-scheduling.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-scheduling.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-scheduling.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/post-scheduling.js", + "to": "moment" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-exporter.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/server/api/endpoints/utils/serializers/output/utils/url.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/server/services/email-service/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/shared/labs.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service-instance.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service.js", + "to": "ghost/core/server/api/endpoints/utils/api-filter-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/posts-service.js", + "to": "ghost/core/shared/events-ts/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/posts/stats/post-stats.js", + "to": "ghost/core/server/data/db/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/remote-flags/remote-flags-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/route-settings/dynamic-routing-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/route-settings/dynamic-routing-service.js", + "to": "ghost/core/bridge.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/route-settings/dynamic-routing-service.js", + "to": "ghost/core/server/services/url/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings-helpers/settings-helpers.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings-helpers/settings-helpers.js", + "to": "net" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-bread-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-bread-service.js", + "to": "ghost/core/server/services/stripe/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-bread-service.js", + "to": "ghost/core/shared/sentry.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-bread-service.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/lib/common/events.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/lib/mail/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/lib/tracing/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/services/adapter-manager/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/services/email-address/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/services/limits.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/services/members/single-use-token-provider.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/server/services/settings-helpers/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/shared/labs.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-service.js", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-utils.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/settings/settings-utils.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/activate.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/activation-bridge.js", + "to": "ghost/core/bridge.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/activation-bridge.js", + "to": "ghost/core/server/services/custom-theme-settings/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/installer.js", + "to": "@tryghost/request" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/installer.js", + "to": "fs-extra" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/installer.js", + "to": "ghost/core/server/services/limits.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/installer.js", + "to": "os" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/list.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/loader.js", + "to": "ghost/core/server/lib/package-json/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/loader.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/storage.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/storage.js", + "to": "fs-extra" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/storage.js", + "to": "ghost/core/server/services/custom-theme-settings/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/storage.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/theme-storage.js", + "to": "@tryghost/zip" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/theme-storage.js", + "to": "fs-extra" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/theme-storage.js", + "to": "ghost/core/server/adapters/storage/LocalStorageBase.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/theme-storage.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/theme-storage.js", + "to": "os" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/to-json.js", + "to": "ghost/core/bridge.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/to-json.js", + "to": "ghost/core/server/lib/package-json/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/to-json.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/to-json.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/upload-size-limit-reporter.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/upload-size-limit-reporter.js", + "to": "ghost/core/shared/sentry.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "fs-extra" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "ghost/core/server/services/adapter-manager/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "ghost/core/shared/labs.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "gscan" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/themes/validate.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/tinybird-sync/tinybird-sync-service.ts", + "to": "ghost/core/server/services/jobs-service/cron.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/tinybird/tinybird-service-wrapper.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/tinybird/tinybird-service-wrapper.js", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/tinybird/tinybird-service-wrapper.js", + "to": "ghost/core/shared/settings-cache/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/update-check/update-check-service.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/update-check/update-check-service.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/update-check/update-check-service.js", + "to": "moment" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/url/lazy-find-resource.ts", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/url/lazy-url-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/url/lazy-url-service.ts", + "to": "ghost/core/shared/url-utils.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/url/routable-resources.js", + "to": "ghost/core/server/data/schema/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/url/routable-resources.js", + "to": "ghost/core/server/models/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/url/router-filter.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/verification-trigger.js", + "to": "@tryghost/domain-events" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/verification-trigger.js", + "to": "ghost/core/shared/events/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/verification/verification-webhook-service.ts", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/verification/verification-webhook-service.ts", + "to": "@tryghost/request" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/verification/verification-webhook-service.ts", + "to": "ghost/core/shared/config/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/listen.js", + "to": "lodash" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/serialize.js", + "to": "ghost/core/server/api/index.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/serialize.js", + "to": "ghost/core/server/services/members/utils.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/serialize.js", + "to": "lodash" + }, + { + "rule": "specialist-dependencies", + "from": "ghost/core/server/services/webhooks/serialize.js", + "to": "packages/api-framework/src/index.ts" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/webhook-trigger.js", + "to": "@tryghost/logging" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/webhook-trigger.js", + "to": "@tryghost/request" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/webhook-trigger.js", + "to": "ghost/core/server/lib/request-external.js" + }, + { + "rule": "service-dependencies", + "from": "ghost/core/server/services/webhooks/webhook-trigger.js", + "to": "ghost/core/shared/config/index.ts" + } +] diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index e26c431f5675..185009a27c0c 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -1,26 +1,20 @@ 'use strict'; -const { readFileSync } = require('node:fs'); -const path = require('node:path'); -const yaml = require('js-yaml'); const { sourceExclusions } = require('./tools/scripts/ci/service-dependency-resolver.mjs'); -// Keep service policy here. The audit applies it to every service; normal lint -// applies it only to entries marked migrated in the inventory. +// Service policy applies independently of inventory and migration status. const servicesRoot = 'ghost/core/server/services'; -const auditServices = process.env.GHOST_SERVICE_DEPENDENCY_AUDIT === '1'; -const { services } = yaml.load( - readFileSync(path.join(__dirname, servicesRoot, 'service-inventory.yaml'), 'utf8'), -); -const migratedServices = Object.entries(services) - .filter(([, entry]) => entry.migrated === true) - .map(([name]) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - .join('|'); const serviceImplementations = { - path: `^${servicesRoot}/(${auditServices ? '[^/]+' : migratedServices || '(?!)'})(?:/|$)`, - pathNot: `^${servicesRoot}/[^/]+/index\\.${auditServices ? '(?:js|ts)' : 'ts'}$`, + path: `^${servicesRoot}/([^/]+)(?:/|$)`, + // Legacy JS roots remain wiring candidates; nested indexes are implementations. + pathNot: `^${servicesRoot}/[^/]+/index\\.(?:js|ts)$`, }; +// The service checks apply to the services directory only, so a defineService +// root anywhere else gets none of them. Each root listed here is a reviewed +// exception until the checks can follow a service to another home. +const serviceRootsElsewhere = ['^ghost/core/server/auth/better-auth/index\\.ts$']; + // Explicit code-library and contract allowances, not application instances. // Keep each package or file named individually and explain additions here. const serviceDependencyAllowlist = [ @@ -30,16 +24,17 @@ const serviceDependencyAllowlist = [ '(^|/)node_modules/@tryghost/security/|^@tryghost/security$', // Token, URL and password primitives; no application instances. '(^|/)node_modules/zod/|^zod$', // Schema construction and validation. '(^|/)node_modules/bson-objectid/|^bson-objectid$', // ObjectId generation and conversion. - '^@tryghost/app-contracts/manifest$|^packages/app-contracts/(src|build)/manifest/index\\.(ts|js)$', // Shared manifest schemas and validation. - '^@tryghost/app-contracts/identity$|^packages/app-contracts/(src|build)/identity/index\\.(ts|js)$', // Signed-manifest and challenge formats, signing and verification. '^@tryghost/adapter-base-upgrade$|^packages/adapters/upgrade-base/(src|build)/index\\.(ts|js)$', // Upgrade adapter contract schemas and error class. '^@tryghost/checkout$|^packages/checkout/(src|build)/index\\.(ts|js)$', // Measured Stripe Checkout countries, ports and fonts shared with Admin; no application instances. - '^@tryghost/parse-email-address/mailbox$|^packages/parse-email-address/(src|build)/mailbox\\.(ts|js)$', // Mailbox parsing and text formatting; no sender policy or application instances. - '^@tryghost/metafield-types/identity$|^packages/metafield-types/(src|build)/identity\\.(ts|js)$', // Metafield namespace, key and part schemas and the identity codec. + '^@tryghost/parse-email-address(/mailbox)?$|^packages/parse-email-address/(src|build)/(index|mailbox)\\.(ts|js)$', // Email address and mailbox parsing and formatting; no sender policy or application instances. + '^contracts/', // Contracts define the shape of data crossing a boundary and, like types, may be imported anywhere. '^@tryghost/string$|(^|/)node_modules/@tryghost/string/lib/index\\.js$', // String normalization, slugification and HTML escaping. + '^@tryghost/version$|(^|/)node_modules/@tryghost/version/index\\.js$', // Ghost's version, a process fact fixed when Ghost is built; reads its own package.json once. '^@tryghost/referrer-parser$|(^|/)node_modules/@tryghost/referrer-parser/dist/index\\.(cjs|js)$', // Referrer classification from supplied URLs and static lookup data. - '^lodash/isEmpty(?:\\.js)?$|(^|/)node_modules/lodash/isEmpty\\.js$', // Pure value/collection inspection; only the isEmpty helper. + '^lodash/(?!(?:index|lodash|core|fp)(?:\\.js)?$)[a-zA-Z]+(?:\\.js)?$|(^|/)node_modules/lodash/(?!(?:index|lodash|core|fp)\\.js$)[a-zA-Z]+\\.js$', // Individual Lodash functions; not the whole library, its builds or lodash/fp. '^@tryghost/nql$|(^|/)node_modules/@tryghost/nql/index\\.js$', // Caller-local query parsing and JSON matching; no application instances or I/O. + '^@tryghost/nql-string$|^packages/nql-string/(src/index\\.ts|build/index\\.js)$', // Builds NQL filter strings from supplied values. + '^@tryghost/validator$|(^|/)node_modules/@tryghost/validator/index\\.js$', // String validation and sanitising of supplied values. '^@tryghost/mongo-utils$|(^|/)node_modules/@tryghost/mongo-utils/index\\.js$', // Pure helpers over a parsed NQL tree; no application instances or I/O. '^@tryghost/html-to-plaintext$|(^|/)node_modules/@tryghost/html-to-plaintext/index\\.js$', // Stateless HTML to plain-text conversion of supplied markup. '^handlebars$|(^|/)node_modules/handlebars/lib/index\\.js$', // Template compilation on a caller-created instance; no application instances. @@ -49,14 +44,16 @@ const serviceDependencyAllowlist = [ '^(node:)?util$', // Node utilities, including promisify. '^(node:)?path$', // Path string parsing and joining. '^(node:)?vm$', // Bounded script execution for caller-owned regex matching with a timeout. + '^(node:)?(assert/strict|stream|stream/promises|buffer|timers/promises)$', // Node's in-memory primitives: assertions, streams, buffers and timers; no I/O of their own. '^ghost/core/kernel/clock\\.ts$', // Shared clock helpers and legacy date compatibility. '^ghost/core/server/lib/db-types/date\\.ts$', // Database date codec. '^ghost/core/server/lib/db-types/boolean\\.ts$', // Database boolean codec. '^ghost/core/server/lib/db-types/json\\.ts$', // Database JSON codec. '^ghost/core/server/lib/common/to-plain\\.ts$', // Bookshelf/plain-object normalization; no application instances or captured state. - '^ghost/core/server/lib/link-replacer\\.js$', // HTML link rewriting with caller-owned callbacks; no retained state or application dependencies. + '^ghost/core/server/lib/link-replacer\\.ts$', // HTML link rewriting with caller-owned callbacks; no retained state or application dependencies. '^ghost/core/server/lib/magic-link/magic-link\\.js$', // Magic-link constructor with caller-supplied transporter, token provider and content callbacks; no application instances. '^ghost/core/server/lib/case-keys\\.ts$', // camelCase and snake_case key conversion between models, rows and wire shapes. + '^ghost/core/server/lib/ensure-transaction\\.ts$', // Runs a callback in the caller's transaction or a new one on the supplied connection; no application instances. '^ghost/core/server/lib/parse-request\\.ts$', // Request body parsing into validation errors on the named property. '^ghost/core/server/lib/public-jwk\\.ts$', // Key conversion and thumbprints; includes memoization. '^ghost/core/server/lib/signed-webhook\\.ts$', // Request signing/formatting and URL sanitization; no running transport. @@ -65,12 +62,316 @@ const serviceDependencyAllowlist = [ '^ghost/core/server/lib/image/image-content\\.ts$', // Image extension and content predicates; no application instances. '^ghost/core/server/lib/image/svg-sanitizer\\.ts$', // SVG buffer sanitization; no application instances. '^ghost/core/server/services/jobs-service/job\\.ts$', // Job base class, not the running service. + '^ghost/core/server/lib/after-commit\\.ts$', // Runs a callback after the caller's transaction commits. + '^ghost/core/server/lib/db-types/count\\.ts$', // Database count codec. + '^ghost/core/server/lib/db-types/affected-rows\\.ts$', // Database affected-rows codec. + '^ghost/core/server/lib/db-types/object-id\\.ts$', // Database ObjectId codec. + '^ghost/core/server/lib/mailgun/mailgun-message-id\\.ts$', // Mailgun message ID normalisation; no client. + '^ghost/core/server/lib/mailgun/mailgun-error\\.ts$', // Mailgun error class; no client. + '^ghost/core/server/lib/promise-pool\\.ts$', // Runs caller-supplied tasks with a concurrency limit. + '^ghost/core/server/lib/soonest-timer\\.ts$', // Timer class the caller builds and owns. + '^ghost/core/server/lib/auto-filling-map\\.ts$', // Map that fills missing keys from a caller-supplied factory. + '^ghost/core/server/lib/member-signup-contexts\\.ts$', // Member signup context constants and one predicate. + '^ghost/core/shared/errify\\.ts$', // Turns any thrown value into an Error. + '^ghost/core/shared/timing-safe-string-equal\\.ts$', // Constant-time string comparison. + '^ghost/core/shared/one-at-a-time\\.ts$', // Wraps a caller's function so calls do not overlap. + '^ghost/core/shared/machine-payments\\.ts$', // Machine payment predicates over supplied data. + '^ghost/core/server/adapters/scheduling/get-scheduler-idempotency-key\\.ts$', // Derives a scheduler job's idempotency key from the values the caller passes. '^@tryghost/kg-default-nodes$|^koenig/kg-default-nodes/(src/index\\.ts|build/(cjs|esm)/index\\.js)$', // Whole Koenig default-nodes entry (node classes, renderers and the replacement-string helpers welcome emails use); the package has no narrower export and holds no application instances. '^ghost/core/server/lib/email-rendering/email-design\\.js$', // Email design token computation from supplied settings. '^ghost/core/server/lib/email-rendering/finalize\\.ts$', // Email CSS inlining and plaintext generation; no application instances. '^ghost/core/server/lib/mail/format-address-for-delivery\\.ts$', // Mailbox formatting for delivery; no sender policy or application instances. ]; +// Specialist dependencies serve one capability: a file format, a protocol or an +// outside system. Each is imported only by the files or folders listed as its +// owners; adding a consumer means changing this list, so it gets reviewed. A +// specialist dependency that does its own I/O has one owner, its provider +// client: the file that wraps it in the API Ghost needs. Everything else, +// including service roots, uses the provider client. See +// docs/practices/dependencies.md. +const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +// An installed package, by import specifier or by its location in node_modules. +const npm = (name) => `(^|/)node_modules/${escape(name)}/|^${escape(name)}(/|$)`; +// A workspace package, by specifier or by the source or build entry it resolves to. +const workspace = (name, directory) => + `^${escape(name)}$|^${escape(directory)}/(src/index\\.ts|build/((cjs|esm)/)?index\\.js)$`; +// A folder in Ghost Core when the path ends with a slash, or a file in either its +// JavaScript or TypeScript form, so converting an owner does not break the rule. +const core = (file) => + file.endsWith('/') + ? `^ghost/core/${escape(file)}` + : `^ghost/core/${escape(file.replace(/\.(js|ts)$/, ''))}\\.(js|ts)$`; +const service = (file) => core(`server/services/${file}`); + +const specialistDependencies = [ + // Provider clients. + { + // Machine Payments Protocol server. + dependency: npm('mppx'), + owners: [service('machine-payments/adapters/mpp-adapter.ts')], + }, + { + // x402 payment protocol and the Hono app its middleware runs on. + dependency: `${npm('hono')}|(^|/)node_modules/@x402/[^/]+/|^@x402/`, + owners: [service('machine-payments/adapters/x402-adapter.ts')], + }, + { + // Stripe API. Members and Stripe use the Stripe service's client; Machine + // Payments has its own for the API version it needs. + dependency: npm('stripe'), + owners: [service('stripe/stripe-api.js'), service('machine-payments/stripe/')], + }, + { + // oEmbed provider lookup and fetching, through a fetcher the caller passes. + dependency: npm('@extractus/oembed-extractor'), + owners: [service('oembed/extract-oembed.ts')], + }, + + // oEmbed and link metadata. + { + // Repairing JSON-LD, reading domains, decoding pages and parsing dates in + // fetched metadata. + dependency: [npm('jsonrepair'), npm('tldts'), npm('iconv-lite'), npm('chrono-node')].join('|'), + owners: [service('oembed/')], + }, + { + // HTML entity decoding for link rewriting and fetched metadata. + dependency: npm('entities'), + owners: [core('server/lib/link-replacer.ts'), service('oembed/')], + }, + + // File and token formats. + { + // CSV parsing and writing. + dependency: npm('papaparse'), + owners: [ + service('members/import-export/csv/'), + service('content-import/csv/'), + core('server/api/endpoints/utils/serializers/output/posts-csv-transform.ts'), + core('server/data/importer/importers/data/revue-subscriber-importer.js'), + core('server/data/importer/importers/importer-revue.js'), + core('server/data/seeders/importers/table-importer.ts'), + ], + }, + { + // Custom-field CSV columns for member import and export. + dependency: workspace('@tryghost/metafield-csv', 'packages/metafield-csv'), + owners: [service('members/import-export/')], + }, + { + // YAML redirects and routes files. + dependency: npm('js-yaml'), + owners: [ + service('custom-redirects/redirect-config-parser.ts'), + service('route-settings/route-settings-parser.ts'), + service('route-settings/yaml-parser.js'), + ], + }, + { + // Signing and verifying JSON Web Tokens. + dependency: npm('jsonwebtoken'), + owners: [ + core('server/auth/api-key/admin.js'), + core('server/adapters/scheduling/utils.ts'), + core('server/api/endpoints/featurebase.js'), + service('identity-tokens/identity-token-service.ts'), + service('members/members-api/services/token-service.js'), + service('tinybird/tinybird-service.js'), + ], + }, + { + // One-time codes for staff two-factor sign-in and member sign-in. + dependency: npm('otplib'), + owners: [core('server/auth/totp.ts'), service('members/single-use-token-provider.js')], + }, + + // HTTP. The web layer builds routers, parses bodies and handles cookies; + // services export handlers that take req, res and next. + { + // Express and its middleware packages. + dependency: ['express', 'body-parser', 'cookies', 'on-headers', 'cors', 'multer'] + .map(npm) + .join('|'), + owners: [core('server/web/'), core('frontend/'), core('shared/express.js')], + }, + + // The API layer. + { + // Ghost's API framework: pipelines, frames, serializers and the HTTP + // adapter that mounts controllers on routes. + dependency: workspace('@tryghost/api-framework', 'packages/api-framework'), + owners: [core('server/api/'), core('server/web/')], + }, + + // Content and rendering. + { + // Converting Mobiledoc and Lexical content. + dependency: workspace('@tryghost/kg-converters', 'koenig/kg-converters'), + owners: [ + core('server/models/post.js'), + core('server/data/migrations/'), + service('email-service/email-renderer.js'), + ], + }, + { + // Sanitising untrusted HTML. + dependency: npm('sanitize-html'), + owners: [ + core('server/models/comment.js'), + core('frontend/services/proxy.js'), + core('server/data/importer/importers/json-to-html.js'), + service('members/members-api/controllers/router-controller.js'), + service('notifications/sanitize-notification-html.ts'), + ], + }, + { + // Class names in email templates. + dependency: npm('clsx'), + owners: [service('email-service/email-renderer.js')], + }, + { + // Colour maths for email design and theme helpers. + dependency: npm('@tryghost/color-utils'), + owners: [ + core('server/lib/email-rendering/email-design.js'), + core('frontend/helpers/color_to_rgba.ts'), + core('frontend/helpers/contrast_text_color.js'), + service('gifts/gift-email-service.ts'), + ], + }, + { + // Matching URLs against route patterns. + dependency: npm('path-match'), + owners: [ + core('frontend/services/data/match-permalink-params.js'), + core('server/web/api/middleware/api-version-compatibility/legacy-api-path-match.js'), + service('url/permalink-matcher.ts'), + ], + }, + { + // Comparing Ghost and import versions. + dependency: npm('semver'), + owners: [ + core('server/data/importer/importers/data/data-importer.js'), + core('server/web/api/middleware/check-version-match.ts'), + service('notifications/notifications.js'), + ], + }, + + // Database. + { + // Telling SQLite from MySQL on a connection the caller passes. + dependency: npm('@tryghost/database-info'), + owners: [ + core('server/data/'), + core('server/models/label.js'), + service('jobs-service/index.ts'), + service('members/service.js'), + service('url/routable-resources.js'), + ], + }, + + // One service each. + { + // Custom field keys and filters. + dependency: `${npm('unidecode')}|${npm('@tryghost/mongo-knex')}`, + owners: [service('members-metafields/')], + }, + { + // Cron expressions for scheduled jobs. + dependency: npm('cron-validate'), + owners: [service('jobs-service/jobs-service.ts')], + }, + { + // Filtering member events in memory. + dependency: npm('mingo'), + owners: [service('members/members-api/repositories/event-repository.js')], + }, + { + // Pacing Stripe API requests. + dependency: npm('leaky-bucket'), + owners: [service('stripe/stripe-api.js')], + }, + { + // Plan limits. + dependency: workspace('@tryghost/limit-service', 'packages/limit-service'), + owners: [service('limits.ts'), service('invites/index.ts')], + }, +]; + +// What to do about a dependency the service rule rejects, read by +// `pnpm gx services report`. The services guide states the rule. A rejected +// dependency that matches nothing here has no decision yet. Patterns match the +// dependency as the report names it: the import specifier for an external +// package, the resolved source path for anything else. +const serviceDependencyDecisions = { + // Holds state of the running application or does its own I/O: the root wires + // it and passes it in. + inject: [ + '^@tryghost/logging$', // Logging. + '^ghost/core/shared/config/', // Config. + '^ghost/core/shared/settings-cache/', // Settings. + '^ghost/core/server/models/index\\.js$', // Models. + '^ghost/core/server/data/db/', // The database connection. + '^@tryghost/domain-events$|^ghost/core/server/lib/common/events\\.js$|^ghost/core/shared/events(-ts)?/index\\.(js|ts)$', // Event buses. + `^${servicesRoot}/`, // Other services, including the events and helpers they own. + '^ghost/core/shared/url-utils\\.ts$', // URL utils, built from config. + '^ghost/core/shared/labs\\.js$', // Labs flags, read from settings and config. + '^ghost/core/shared/sentry\\.js$', // Sentry client, set up from config. + '^ghost/core/shared/i18n/index\\.js$', // Translations for the site's locale; reads settings and locale files. + '^@tryghost/i18n$|^packages/i18n/(src|build)/index\\.(ts|js)$', // Loads locale files. + '^ghost/core/server/lib/tracing/index\\.ts$', // Tracing; logs. + '^ghost/core/server/lib/request-external\\.js$', // Outbound HTTP, limited by config. + '^got$|^@tryghost/request$', // Outbound HTTP. + '^(node:)?dns/promises$', // DNS lookups. + '^ghost/core/server/lib/mailgun/mailgun-client\\.js$', // Mailgun client; calls the Mailgun API and logs. + '^ghost/core/server/lib/mail/index\\.js$', // Mailer, built from config and settings. + '^ghost/core/server/lib/image/index\\.js$', // Image tools, built from config, storage and outbound HTTP. + '^ghost/core/server/lib/lexical\\.js$', // Lexical renderer, wired to config, labs, settings and services. + '^ghost/core/server/lib/get-inbox-links\\.ts$', // Logs. + '^ghost/core/server/lib/package-json/index\\.js$', // Reads package files. + '^@tryghost/image-transform$|^packages/image-transform/(src|build)/index\\.(ts|js)$', // Reads and writes image files. + '^glob$|^@tryghost/zip$|^gscan$', // Read or write files. + '^@tryghost/metrics$', // Process-wide metrics, set up from the logging config. + '^ghost/core/server/data/schema/index\\.js$', // Reaches the database through schema commands. + '^ghost/core/server/data/importer/(content-files|import-archive)\\.ts$', // Importer code; reads files and config. + '^ghost/core/server/adapters/scheduling/build-signed-job\\.ts$', // Uses URL utils. + '^ghost/core/server/adapters/storage/(utils|LocalStorageBase)\\.ts$', // Storage code; reads config, URL utils and files. + '^ghost/core/server/api/index\\.js$|^ghost/core/server/api/endpoints/utils/(api-filter-utils\\.ts|serializers/output/utils/url\\.js)$', // The API layer and its helpers. + '^ghost/core/server/web/shared/middleware/api/spam-prevention\\.ts$', // Rate limiting, built from config and the database. + '^ghost/core/bridge\\.js$', // The bridge to the frontend. + '^ghost/core/server/web/shared/dynamic-redirect-manager\\.js$', // Holds the site's redirects and an Express router shared with the web layer; roots build it. + ], + // Left as known violations until a planned refactor moves the importing file. + // Each names the file, its dependencies and the refactor. + deferred: [ + { + from: '^ghost/core/server/services/adapter-manager/base-classes\\.ts$', + to: '^packages/adapters/[^/]+-base/', + until: "PLA-541 moves Ghost's adapter registry into boot", + }, + { + from: '^ghost/core/server/services/jobs-service/register-job-handlers\\.ts$', + to: '-job\\.(ts|js)$', + until: 'PLA-543 moves job handler registration into boot', + }, + { + from: '^ghost/core/server/services/permissions/can-this\\.js$', + to: '^ghost/core/server/models/role-utils\\.ts$', + until: 'Permissions moves to server/auth/permissions and settles where role checks live', + }, + ], + // Allowed only in another form. A specialist dependency imported outside its + // owners is counted here too, without a pattern. + importForm: [ + '^lodash$', // Import individual functions, such as lodash/isEmpty. + '^(moment(-timezone)?|luxon|temporal-polyfill)$', // Dates and times go through the kernel clock, which exports moment for existing date logic. + '^(node:)?url$', // Use the global URL; url.parse is deprecated. + '^(node:)?(fs(/promises)?|os|net)$|^fs-extra$', // No file system, operating system or networking modules: the root passes a loader limited to what is needed. + ], +}; + /* * Architectural boundary rules for the monorepo, enforced on the resolved * module graph (require AND import). Two sections: @@ -102,10 +403,23 @@ module.exports = { from: serviceImplementations, to: { // $1 is the service name captured by from.path. - pathNot: [...serviceDependencyAllowlist, `^${servicesRoot}/$1/`], + // Specialist dependencies are checked by specialist-dependencies instead. + pathNot: [ + ...serviceDependencyAllowlist, + ...specialistDependencies.map(({ dependency }) => dependency), + `^${servicesRoot}/$1/`, + ], dependencyTypesNot: ['type-only', 'type-import'], }, }, + ...specialistDependencies.map(({ dependency, owners }) => ({ + name: 'specialist-dependencies', + comment: + 'Only the owners listed in specialistDependencies may import this. Use the owning code, or add the consumer to the list for review.', + severity: 'error', + from: { path: '^ghost/core/', pathNot: owners }, + to: { path: dependency, dependencyTypesNot: ['type-only', 'type-import'] }, + })), { name: 'service-own-root', comment: 'Service implementations must not retrieve dependencies from their own wiring root.', @@ -123,6 +437,24 @@ module.exports = { from: serviceImplementations, to: { couldNotResolve: true, dependencyTypesNot: ['type-only', 'type-import'] }, }, + { + name: 'service-roots-in-services', + comment: + 'A defineService root belongs in server/services//index.ts, where the service checks apply. A root elsewhere needs a reviewed entry in serviceRootsElsewhere.', + severity: 'error', + from: { + path: '^ghost/core/', + pathNot: [ + `^${servicesRoot}/[^/]+/index\\.ts$`, + '^ghost/core/kernel/', + ...serviceRootsElsewhere, + ], + }, + to: { + path: '^ghost/core/kernel/define-service\\.ts$', + dependencyTypesNot: ['type-only', 'type-import'], + }, + }, // Kernel primitives must be independent of the application they support. { name: 'kernel-not-application', @@ -141,6 +473,17 @@ module.exports = { from: { path: '^ghost/core/shared/' }, to: { path: '^ghost/core/(server|frontend)/' }, }, + // Config schema files describe shapes: they know feature names, not feature code. + { + name: 'config-schema-zod-only', + comment: + 'Files in core/shared/config/schema/ may import only zod and each other. See core/shared/config/SCHEMA.md.', + severity: 'error', + from: { path: '^ghost/core/shared/config/schema/' }, + to: { + pathNot: ['^ghost/core/shared/config/schema/', '(^|/)node_modules/zod/|^zod$'], + }, + }, // ============================================================ // Frontend must not require server/models directly // ============================================================ @@ -257,7 +600,7 @@ module.exports = { path: '^apps/(portal|comments-ui|signup-form|sodo-search|announcement-bar|admin-toolbar)/', }, to: { - path: '^@tryghost/metafield-types$|^packages/metafield-types/(src|build)/index\\.(ts|js)$|^libphonenumber-js($|/)|(^|/)node_modules/libphonenumber-js/', + path: '^@tryghost/metafield-types$|^contracts/metafield-types/(src|build)/index\\.(ts|js)$|^libphonenumber-js($|/)|(^|/)node_modules/libphonenumber-js/', dependencyTypesNot: ['type-only', 'type-import'], }, }, @@ -351,9 +694,17 @@ module.exports = { ], options: { // Resolve public package exports to authored workspace source when available. + // `pnpm gx services verify` also resolves them to built output, the files Ghost + // loads at runtime, so an allowance must hold for both. enhancedResolveOptions: { exportsFields: ['exports'], - conditionNames: ['source', 'import', 'require', 'node', 'default'], + conditionNames: [ + ...(process.env.GHOST_DEPENDENCY_RESOLUTION === 'built' ? [] : ['source']), + 'import', + 'require', + 'node', + 'default', + ], }, reporterOptions: { err: { showExternalModulesUnresolved: true }, @@ -364,20 +715,26 @@ module.exports = { webpackConfig: { fileName: './tools/scripts/ci/service-dependency-resolver.mjs' }, // Keep incoming edges to built packages visible without scanning their output. doNotFollow: { - path: auditServices - ? `^(?!${servicesRoot}/)` - : [ - 'node_modules', - '^(?!ghost/core/server/services/)(apps|ghost|packages|koenig)/.*/(build|built|dist)/', - ], + path: [ + 'node_modules', + '^(?!ghost/core/server/services/)(apps|ghost|packages|contracts|koenig)/.*/(build|built|dist)/', + ], }, // Skip our own tests and emitted companions. All source inside services stays visible: // a nested directory name must not hide a production dependency. exclude: { path: [ - '^(?!ghost/core/server/services/)(apps|ghost|packages)/.*/(coverage|coverage-next|test)/', + '^(?!ghost/core/server/services/)(apps|ghost|packages|contracts)/.*/(coverage|coverage-next|test)/', ...sourceExclusions(__dirname), ], }, }, }; + +// dependency-cruiser rejects configuration keys it does not know, so the lists +// other tools read are properties its validation does not see. +Object.defineProperties(module.exports, { + serviceDependencyAllowlist: { value: serviceDependencyAllowlist }, + specialistDependencies: { value: specialistDependencies }, + serviceDependencyDecisions: { value: serviceDependencyDecisions }, +}); diff --git a/.dockerignore b/.dockerignore index 769c028cb48a..f8cd342aa6fe 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,6 +13,7 @@ apps/**/build ghost/**/build koenig/**/build packages/**/build +contracts/*/build e2e/build dist diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b38b9c6bef15..ff319432af98 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -16,6 +16,13 @@ # Kernel /ghost/core/kernel/ @ErisDS +# Service policy: dependency rules, legacy services and their reviewed violations +/.dependency-cruiser.cjs @ErisDS +/.dependency-cruiser-known-violations.json @ErisDS +/tools/scripts/lib/dependency-boundaries.ts @ErisDS +/tools/configs/oxlint/legacy-services.ts @ErisDS +/tools/scripts/ci/legacy-services-base.ts @ErisDS + # Inbox Links ghost/core/server/lib/get-inbox-links.ts @EvanHahn ghost/test/unit/server/lib/get-inbox-links.test.ts @EvanHahn diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a72ae49920dd..a17fe58f6451 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -78,7 +78,7 @@ the message should explain what changed because of them. See this ## Changesets -Ghost publishes several workspace packages to npm — the `@tryghost/*` editor and adapter packages under `koenig/` and `packages/`. When your change affects one of these publishable packages, including by changing a catalog entry it consumes, add a **changeset** so it gets a version bump and a changelog entry: +Ghost publishes several workspace packages to npm — the `@tryghost/*` editor, adapter and contract packages under `koenig/`, `packages/` and `contracts/`. When your change affects one of these publishable packages, including by changing a catalog entry it consumes, add a **changeset** so it gets a version bump and a changelog entry: ```bash pnpm change diff --git a/.github/hooks/pre-commit.bash b/.github/hooks/pre-commit.bash index 661c99cf9158..8ef2bacb5506 100755 --- a/.github/hooks/pre-commit.bash +++ b/.github/hooks/pre-commit.bash @@ -16,6 +16,19 @@ if [ $lintStatus -ne 0 ]; then exit 1 fi +# lint-staged is only given added and modified files, so it cannot tell that a +# removed or renamed file is still the target of a link in a document. +if [ -n "$(git diff --cached --name-only --no-renames --diff-filter=D)" ]; then + echo -e "Checking documentation links ${grey}(pre-commit hook)${no_color} " + + # git sets GIT_DIR for hooks in a worktree, which stops remark-validate-links + # from finding the repository root to resolve its own GitHub URLs + if ! (unset GIT_DIR && pnpm --silent lint:doc-links); then + echo -e "${red}❌ Documentation link check failed${no_color}" + exit 1 + fi +fi + ## ## 1) Scan staged text files for secrets ## diff --git a/.github/renovate.json5 b/.github/renovate.json5 index 16216ad38f68..cfa11b150aa3 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -153,7 +153,7 @@ packageRules: [ // Auto-generate a changeset when an npm/package.json update (or a pnpm // catalog bump — the npm manager handles both) touches a publishable - // package (koenig/*, packages/*), directly or via a catalog entry it + // package (koenig/*, packages/*, contracts/*), directly or via a catalog entry it // references, so the PR clears the "Check app version bump" gate without // a human authoring one. Scoped to `npm` so Docker/GitHub-Actions updates // never run it. Runs once per branch after the update is applied (working @@ -492,9 +492,11 @@ // change runtime behavior. Frequently-rotating upstream tags // (notably `tinybird-local:latest`) were opening ~5 individual PRs // per week, each running the full E2E lane (~70-150 job-min) for a - // tweak with no runtime impact. Saturday-only `schedule` batches the + // tweak with no runtime impact. A weekend-only `schedule` batches the // week's churn into one PR + one CI run; the global automergeSchedule - // (all weekend, weekday evenings) lands it without human review. + // (all weekend, weekday evenings) lands it without human review. Sunday + // stays in the window because updateNotScheduled: false skips + // off-schedule branches before the automerge check. // Digests for images not in this list (e.g. the pinned `redis` in // ci.yml services) still open individually — they're rare and // intentionally human-reviewed. @@ -512,11 +514,22 @@ ], matchUpdateTypes: ['digest'], groupName: 'Docker image digests', - schedule: ['* * * * 6'], + schedule: ['* * * * 0,6'], automerge: true, automergeType: 'pr', }, + // better-auth publishes several releases a week, so every soak-cleared + // version was opening its own PR + full CI run. Weekend-only takes the + // newest soaked release once a week. Sunday stays in the window because + // updateNotScheduled: false skips off-schedule branches before the + // automerge check, so a PR going green late Saturday would wait a week. + { + description: 'Weekly schedule for better-auth monorepo updates', + matchPackageNames: ['better-auth', '@better-auth/**'], + schedule: ['* * * * 0,6'], + }, + // Digest and pin updates (Docker image digests, action SHAs) usually // have no release timestamp — Docker Hub library images skip label // lookup entirely — so the 72h soak can never be satisfied. Worse, diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 36ee2a02777f..6fd3dd7e42d0 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -104,17 +104,31 @@ deployments record the commit that was actually deployed. ## Documentation changes -CI treats `ghost/core/server/services/service-inventory.yaml` as documentation -for runtime checks. Inventory edits still run the required **Validate service -inventory** job, which runs the existing metadata tests without Ghost runtime -setup or workspace builds. The same job runs when its test or configuration changes. +Changes confined to documentation skip the full code and E2E jobs. Mixed runtime +changes retain their normal checks. -Changes confined to inventory and documentation skip the full code and E2E jobs. -Validator changes still run code checks, and mixed runtime changes retain their -normal checks. +## Legacy service inventory changes -Run the focused validation locally with: +Boot never reads `ghost/core/server/services/legacy-service-inventory.yaml`, so a +change confined to it skips the acceptance, legacy and E2E jobs. Lint decides +which services to check from it, so it still runs lint and the affected unit +tests and type checks. + +It also runs two required jobs: + +- **Validate service inventory** runs the metadata tests without Ghost runtime + setup or workspace builds. It also runs when its test or configuration changes. +- **Check legacy services** runs on pull requests. It fails when the branch adds + a legacy service, or defers dependency checks for one, compared with the + commit it forked from. + +Run both locally with: ```sh pnpm --filter ghost exec vitest run --config vitest.config.inventory.ts +pnpm lint:legacy-services ``` + +`pnpm lint:legacy-services` compares with `origin/main` and fails if that branch +has not been fetched. `pnpm lint` does not run it, because a checkout does not +always have its base branch. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index caba9bdfacb7..3af540ee67f8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -168,25 +168,17 @@ jobs: - '.github/actions/**' - '.github/scripts/**' - 'tools/scripts/**' - docs: - - 'ghost/core/server/services/service-inventory.yaml' - - '**/*.md' - - '**/*.mdx' - - '.agents/**' - - '.claude/**' - - '.github/workflows/ci.yml' - - 'package.json' - - 'tools/scripts/ci/check-agent-skill-links.ts' - - 'tools/scripts/test/check-agent-skill-links.test.ts' - - 'tools/scripts/ci/check-agent-guidance.ts' - - 'tools/scripts/test/check-agent-guidance.test.ts' service-inventory: - - 'ghost/core/server/services/service-inventory.yaml' - - 'ghost/test/unit/server/services/service-inventory.test.ts' + - 'ghost/core/server/services/legacy-service-inventory.yaml' + - 'ghost/test/unit/server/services/legacy-service-inventory.test.ts' - 'ghost/vitest.config.inventory.ts' + - 'tools/scripts/ci/check-legacy-services.ts' + - 'tools/scripts/ci/legacy-services-base.ts' + - 'tools/configs/oxlint/legacy-services.ts' - '.github/workflows/ci.yml' package-standards: - 'packages/**' + - 'contracts/**' - 'package.json' - 'pnpm-workspace.yaml' - 'tools/scripts/ci/check-internal-packages.ts' @@ -217,8 +209,9 @@ jobs: # positive pattern so micromatch cannot add docs files back. - '!**/*.md' - '!**/*.mdx' - # Migration metadata is documentation; boot never reads it. - - '!ghost/core/server/services/service-inventory.yaml' + # Boot never reads the legacy service inventory. Lint does, so it + # still counts as code in any-code below. + - '!ghost/core/server/services/legacy-service-inventory.yaml' - '!ghost/vitest.config.inventory.ts' unit-test-globals: - 'vitest.config.mjs' @@ -226,7 +219,6 @@ jobs: - 'ghost/vitest.config.ts' - 'ghost/test/utils/vitest-*.ts' any-code: - - '!ghost/core/server/services/service-inventory.yaml' - '!**/*.md' - '!**/*.mdx' - '!.github/CODEOWNERS' @@ -240,7 +232,7 @@ jobs: # React Admin tests still run through the affected unit, acceptance, # lint and typecheck targets; only the build + E2E lane is skipped. e2e: - - '!ghost/core/server/services/service-inventory.yaml' + - '!ghost/core/server/services/legacy-service-inventory.yaml' - '!**/*.md' - '!**/*.mdx' - '!.github/CODEOWNERS' @@ -383,7 +375,6 @@ jobs: changed_i18n_apps: ${{ steps.affected.outputs.affected_i18n_projects != '' }} changed_core: ${{ steps.changed.outputs.core }} changed_any_code: ${{ steps.changed.outputs.any-code }} - changed_docs: ${{ steps.changed.outputs.docs }} changed_service_inventory: ${{ steps.changed.outputs.service-inventory }} changed_package_standards: ${{ steps.changed.outputs.package-standards }} changed_tb_cli: ${{ steps.changed.outputs.tb-cli }} @@ -444,8 +435,7 @@ jobs: run: node tools/scripts/ci/check-app-version-bump.ts # Fail the PR if a publishable package changed (source or a catalog entry - # it consumes) but the branch adds no changeset covering it. Prototype of - # pnpm's forthcoming `pnpm change check`. + # it consumes) but the branch adds no changeset covering it. - name: Check for missing changesets env: PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -453,6 +443,11 @@ jobs: PR_COMPARE_SHA: ${{ github.event.pull_request.head.sha }} run: node tools/scripts/ci/change-check.ts + # Validate every pending changeset with pnpm's own parser: known + # packages, valid bump types, and versions within the versioning config. + - name: Check changesets are valid + run: pnpm change check + - name: Check private packages are excluded from versioning run: node tools/scripts/ci/check-versioning-ignore.ts @@ -516,6 +511,9 @@ jobs: - name: Lint boundaries run: pnpm nx run ghost-monorepo:lint:boundaries + - name: Lint dependencies + run: pnpm lint:dependencies + - name: Check formatting run: pnpm format:check @@ -530,19 +528,24 @@ jobs: name: Lint docs runs-on: ubuntu-slim needs: [job_setup] - if: needs.job_setup.outputs.changed_docs == 'true' + # No path filter: a link breaks when its target is removed or renamed, and + # the target can be any file in the repository. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + - uses: ./.github/actions/setup-node-pnpm with: node-version: ${{ env.NODE_VERSION }} + trust-lockfile: 'true' + # The Markdown and link checkers are dependencies of the root package. + install-args: --filter ghost-monorepo --ignore-scripts + store-cache: 'false' - - name: Lint documentation guidance - run: | - node --test tools/scripts/test/check-agent-guidance.test.ts - node tools/scripts/ci/check-agent-skill-links.ts - node tools/scripts/ci/check-agent-guidance.ts + - name: Test documentation guidance checker + run: node --test tools/scripts/test/check-agent-guidance.test.ts + + - name: Lint documentation + run: pnpm lint:docs job_service_inventory: name: Validate service inventory @@ -563,6 +566,44 @@ jobs: - name: Validate service inventory run: pnpm --filter ghost exec vitest run --config vitest.config.inventory.ts + # The legacy services only shrink. A pull request is the only place a name can + # be added, so this compares the branch with the commit it forked from. + job_legacy_services: + name: Check legacy services + runs-on: ubuntu-latest + timeout-minutes: 10 + needs: [job_setup] + if: github.event_name == 'pull_request' && needs.job_setup.outputs.changed_service_inventory == 'true' + steps: + - name: Checkout PR head commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + + - name: Fetch PR base branch + # Through env, never interpolated into the script: a branch name can + # carry shell metacharacters, and template expansion happens before the + # shell parses the command. + env: + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + run: git fetch --no-tags origin "+refs/heads/${PR_BASE_REF}:refs/remotes/origin/${PR_BASE_REF}" + + - uses: ./.github/actions/setup-node-pnpm + with: + node-version: ${{ env.NODE_VERSION }} + trust-lockfile: 'true' + # The check and the inventory reader each read YAML with their own + # workspace's parser. + install-args: --filter @internal/scripts --filter @internal/cfg-oxlint --ignore-scripts + store-cache: 'false' + + - name: Check legacy services only shrink + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + run: node tools/scripts/ci/check-legacy-services.ts + job_lint_packages: name: Lint packages runs-on: ubuntu-slim @@ -812,6 +853,13 @@ jobs: # # Non-primary Node legs skip browser-only projects (see # unit_test_node_projects_str in job_setup). + # + # ghost's unit suite runs in a shuffled order seeded by + # GHOST_UNIT_TEST_SEED (see ghost/vitest.config.ts), so a test that + # only passes after another one fails here. Every attempt reuses the + # run's seed, so a retry can't hide that behind a different order. + # Vitest prints it as `Running tests with seed ""`; + # docs/contributing/testing.md covers rerunning that order locally. run: | if [ "${{ matrix.node }}" = "${{ needs.job_setup.outputs.node_version }}" ]; then PROJECTS="${{ needs.job_setup.outputs.unit_test_projects_str }}" @@ -846,6 +894,7 @@ jobs: FORCE_COLOR: 0 NX_SKIP_LOG_GROUPING: true logging__level: fatal + GHOST_UNIT_TEST_SEED: ${{ github.run_id }} - name: Check for unexpected file changes run: | @@ -2600,6 +2649,7 @@ jobs: job_lint, job_lint_docs, job_service_inventory, + job_legacy_services, job_lint_packages, job_stripe_fixtures, job_i18n, @@ -2633,7 +2683,7 @@ jobs: # (public apps, and anything else that ships on every change) to npm via OIDC # trusted publishing. Runs only on push-to-main — never on pull_request — so # the `id-token: write` permission is never exposed to PR-controlled code - # (ref: ONC-1677). The changeset lane (koenig/*, packages/*) is the separate + # (ref: ONC-1677). The changeset lane (koenig/*, packages/*, contracts/*) is the separate # publish-packages.yml, which runs off release tags. publish_continuous: needs: [job_setup, job_lint, job_typecheck, job_unit-tests, job_build_e2e_public_apps] @@ -2863,7 +2913,7 @@ jobs: - name: Publish to npm run: npm publish ghost-*-npm.tgz --access public --provenance - # NOTE: Publishing the other workspace packages (koenig/*, packages/*, ...) is + # NOTE: Publishing the other workspace packages (koenig/*, packages/*, contracts/*, ...) is # NOT a job here. The release tag triggers publish-packages.yml directly, in # parallel with this workflow — npm trusted publishing validates the # entry-point workflow, so that publish must be its own entry point rather than diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml index 87cd7971ab62..ea1b39ae303a 100644 --- a/.github/workflows/publish-packages.yml +++ b/.github/workflows/publish-packages.yml @@ -1,7 +1,7 @@ name: Publish Packages # Single trusted publisher for the workspace's public packages (koenig/*, -# packages/*, ...). npm trusted publishing (OIDC) validates the ENTRY-POINT +# packages/*, contracts/*, ...). npm trusted publishing (OIDC) validates the ENTRY-POINT # workflow — the one the run was triggered from, not any reusable workflow it # calls — so this workflow must be triggered directly on both paths and is the # only workflow npm needs to trust for these packages: diff --git a/.gitignore b/.gitignore index 2a810ad87fbf..d82a94f42f6b 100644 --- a/.gitignore +++ b/.gitignore @@ -184,6 +184,7 @@ Caddyfile /ghost/*/build /koenig/*/build /packages/**/build +/contracts/*/build /packages/app-sdk/dist # Typescript build artifacts tsconfig.tsbuildinfo diff --git a/.lintstagedrc.cjs b/.lintstagedrc.cjs index cdded369f078..5c148fe64742 100644 --- a/.lintstagedrc.cjs +++ b/.lintstagedrc.cjs @@ -97,7 +97,10 @@ function buildOxfmtCommand(files) { function buildBoundaryCommand(files) { const relativeFiles = files.map((file) => normalize(path.relative(ROOT, file))); - return `pnpm exec depcruise --config .dependency-cruiser.cjs -- ${shellQuote(relativeFiles)}`; + // Not depcruise directly: the checker applies the known violations, so a + // file in a legacy service can be committed without adding a new one. Run it + // through pnpm, as CI does, so the scan reads TypeScript the same way. + return `pnpm lint:boundaries -- ${shellQuote(relativeFiles)}`; } function buildMarkdownCommands(files) { @@ -143,6 +146,6 @@ module.exports = { '{**/AGENTS.md,tools/scripts/ci/check-agent-guidance.ts}': () => 'pnpm lint:agent-guidance', '{.agents/skills/**,.claude/skills/**,tools/scripts/ci/check-agent-skill-links.ts}': () => 'pnpm lint:agent-skills', - '{package.json,pnpm-workspace.yaml,packages/**/package.json,packages/_template/**,tools/scripts/ci/check-internal-packages.ts,tools/gx/**,tools/scripts/lib/constants.ts}': + '{package.json,pnpm-workspace.yaml,packages/**/package.json,contracts/*/package.json,packages/_template/**,tools/scripts/ci/check-internal-packages.ts,tools/gx/**,tools/scripts/lib/constants.ts}': () => 'pnpm lint:packages', }; diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 29224332db2b..1b53a2e1d340 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -12,6 +12,7 @@ "**/*.html", "**/test/**/fixtures/**", "**/__snapshots__/**", + "**/eslint-suppressions.json", "koenig/kg-default-nodes/**", "koenig/kg-lexical-html-renderer/**", "koenig/kg-simplemde/debug/**", diff --git a/.oxlintrc.json b/.oxlintrc.json index 750072dc9c3d..79b8969f0eb2 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -56,7 +56,7 @@ "excludeFiles": ["apps/admin/src/**/*.test.*"] }, { - "files": ["packages/app-sdk/**/*.ts", "packages/app-contracts/**/*.ts"], + "files": ["packages/app-sdk/**/*.ts", "contracts/app-contracts/**/*.ts"], "plugins": ["unicorn"], "rules": { "unicorn/prefer-node-protocol": "error" @@ -95,8 +95,8 @@ "packages/admin-api-schema/src/**/*.ts", "packages/admin-api-schema/test/**/*.ts", "packages/api-framework/src/**/*.ts", - "packages/app-contracts/src/**/*.ts", - "packages/app-contracts/test/**/*.ts", + "contracts/app-contracts/src/**/*.ts", + "contracts/app-contracts/test/**/*.ts", "packages/checkout/src/**/*.ts", "packages/checkout/test/**/*.ts", "packages/i18n/src/**/*.ts", @@ -106,8 +106,8 @@ "packages/limit-service/src/**/*.ts", "packages/metafield-csv/src/**/*.ts", "packages/metafield-csv/test/**/*.ts", - "packages/metafield-types/src/**/*.ts", - "packages/metafield-types/test/**/*.ts", + "contracts/metafield-types/src/**/*.ts", + "contracts/metafield-types/test/**/*.ts", "packages/nql-string/src/**/*.ts", "packages/nql-string/test/**/*.ts", "packages/parse-email-address/src/**/*.ts", @@ -229,50 +229,28 @@ } }, { - "files": [ - "ghost/core/server/services/app-installations/index.ts", - "ghost/core/server/services/audience-feedback/index.ts", - "ghost/core/server/services/comments/index.ts", - "ghost/core/server/services/custom-theme-settings/index.ts", - "ghost/core/server/services/donations/index.ts", - "ghost/core/server/services/explore-ping/index.ts", - "ghost/core/server/services/export-requests/index.ts", - "ghost/core/server/services/gift-links/index.ts", - "ghost/core/server/services/indexnow-ping/index.ts", - "ghost/core/server/services/integrations/index.ts", - "ghost/core/server/services/internal-keys/index.ts", - "ghost/core/server/services/invites/index.ts", - "ghost/core/server/services/link-redirection/index.ts", - "ghost/core/server/services/media-inliner/index.ts", - "ghost/core/server/services/member-attribution/index.ts", - "ghost/core/server/services/member-welcome-emails/index.ts", - "ghost/core/server/services/mentions/index.ts", - "ghost/core/server/services/newsletters/index.ts", - "ghost/core/server/services/posts-public/index.ts", - "ghost/core/server/services/recommendations/index.ts", - "ghost/core/server/services/signing-keys/index.ts", - "ghost/core/server/services/slack-ping/index.ts", - "ghost/core/server/services/staff/index.ts", - "ghost/core/server/services/stats/index.ts", - "ghost/core/server/services/stripe-checkout-config/index.ts", - "ghost/core/server/services/tags-public/index.ts", - "ghost/core/server/services/upgrades/index.ts", - "ghost/core/server/services/users/index.ts", - "ghost/core/server/services/tiers/index.ts" - ], + "files": ["ghost/core/server/services/*/index.ts"], "rules": { "ghost/service-root-shape": [ "error", { "helperImport": "../../../kernel/define-service" } - ] + ], + "ghost/no-injected-service-libraries": "error" } }, { - "files": ["ghost/core/server/services/*/index.ts"], + "files": ["ghost/core/boot.js"], "rules": { - "ghost/no-injected-service-libraries": "error" + "ghost/boot-awaits-service-init": "error" + } + }, + { + "files": ["ghost/core/server/services/**/*.{js,ts}"], + "plugins": ["import"], + "rules": { + "import/no-dynamic-require": ["error", { "esmodule": true }] } }, { @@ -348,13 +326,13 @@ "packages/adapters/storage-base/build/**/*", "packages/admin-api-schema/build/**/*", "packages/api-framework/build/**/*", - "packages/app-contracts/build/**/*", + "contracts/app-contracts/build/**/*", "packages/checkout/build/**/*", "packages/i18n/build/**/*", "packages/image-transform/build/**/*", "packages/limit-service/build/**/*", "packages/metafield-csv/build/**/*", - "packages/metafield-types/build/**/*", + "contracts/metafield-types/build/**/*", "packages/nql-string/build/**/*", "packages/parse-email-address/build/**/*", "packages/testing/test-data/build/**/*", diff --git a/AGENTS.md b/AGENTS.md index b663dc54b8dc..46eac55dda9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,8 @@ matching `.claude/skills/` symlink to `../../.agents/skills/`. Run `pnpm lint:agent-skills` to verify discovery. Use the relevant repository skill before adding an Admin API endpoint, database -migration, private feature flag, Shade component, or internal package. +migration, private feature flag, Shade component, internal package, or Core +service. ## Task routing and important warnings @@ -64,12 +65,18 @@ migration, private feature flag, Shade component, or internal package. - **Ghost Core:** use the [server map](docs/codebase/monorepo-structure.md#ghost-core) and read the [services guide](ghost/core/server/services/README.md) before adding or relocating a service root; apply its placement rules rather than - inferring ownership from existing directory names. New standalone services - use TypeScript; keep CommonJS only - at existing `require()` boundaries. Boot owns service initialization; do not - initialize on the first request. + inferring ownership from existing directory names. Use + [add-service](.agents/skills/add-service/SKILL.md) for a new service and + [migrate-service](.agents/skills/migrate-service/SKILL.md) to adopt `defineService` + in an existing service. New standalone services use TypeScript; keep CommonJS + only at existing `require()` boundaries. Boot owns service initialization; + do not initialize on the first request. Before writing a record's relations or link tables outside `Model.edit`, read [row locking](docs/codebase/database.md#row-locking). + Before adding an import, check the + [dependency rules](docs/practices/dependencies.md). +- **Background jobs:** read the [jobs guide](docs/codebase/jobs.md) before + adding a job. - **Repository tooling:** read the [tooling ownership guide](tools/README.md) and the owning folder README before adding or relocating scripts. - **ESLint:** use the shared factories and dependency rules in the diff --git a/CONTEXT-MAP.md b/CONTEXT-MAP.md index c2364ada9ae6..9bab7c2e1e14 100644 --- a/CONTEXT-MAP.md +++ b/CONTEXT-MAP.md @@ -28,7 +28,7 @@ Newsletter Email Sending covers the preparation and submission of newsletter ema ### App Contracts -Path: `packages/app-contracts/CONTEXT.md` +Path: `contracts/app-contracts/CONTEXT.md` App Contracts covers what Ghost and an app must agree on: how an app describes itself in its manifest, how two versions of that manifest differ, and how Admin and an app's page talk over the bridge while Admin shows it. diff --git a/Dockerfile.production b/Dockerfile.production index 48e6ddb96a7d..1013fa284090 100644 --- a/Dockerfile.production +++ b/Dockerfile.production @@ -57,10 +57,10 @@ COPY --exclude=ghost/core/built . . # Install only ghost and its dependency subgraph (`ghost...`), not the whole # monorepo (admin, apps, ...). Dev deps are included — tsc etc. are needed to build -# the closure. Scripts are NOT ignored: better-sqlite3's install script runs and -# prebuild-install fetches its prebuilt binary (permitted by allowBuilds in -# pnpm-workspace.yaml). No build-essential/python3 is installed, so a node-gyp -# source-compile fallback fails loudly instead of silently pulling a toolchain into +# the closure. Scripts are NOT ignored, for the dependencies allowBuilds in +# pnpm-workspace.yaml permits; better-sqlite3 ships its prebuilt binaries in the +# package and has no install script. No build-essential/python3 is installed, so a +# node-gyp source-compile fails loudly instead of silently pulling a toolchain into # a discarded layer. --no-runtime skips downloading the devEngines.runtime Node # from nodejs.org: the base image already runs NODE_VERSION. RUN --mount=type=cache,target=/root/.local/share/pnpm/store,id=pnpm-store \ diff --git a/apps/activitypub/eslint-suppressions.json b/apps/activitypub/eslint-suppressions.json new file mode 100644 index 000000000000..3e2b8bbd000e --- /dev/null +++ b/apps/activitypub/eslint-suppressions.json @@ -0,0 +1,76 @@ +{ + "src/components/feed/feed-item-stats.tsx": { + "react-hooks/immutability": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/components/global/ap-avatar.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/components/global/follow-button.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/components/layout/onboarding/onboarding.tsx": { + "react-hooks/preserve-manual-memoization": { + "count": 1 + } + }, + "src/components/modals/new-note-modal.tsx": { + "react-hooks/immutability": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/components/modals/search.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/hooks/use-activity-pub-queries.ts": { + "react-hooks/preserve-manual-memoization": { + "count": 2 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/hooks/use-sensitive-media-disclosure.ts": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/lib/feature-flags.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/views/inbox/components/inbox-list.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/views/preferences/components/bluesky-sharing.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/views/preferences/components/domain.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/views/profile/components/unblock-dialog.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + } +} \ No newline at end of file diff --git a/apps/admin-toolbar/eslint-suppressions.json b/apps/admin-toolbar/eslint-suppressions.json new file mode 100644 index 000000000000..78e18f0abe55 --- /dev/null +++ b/apps/admin-toolbar/eslint-suppressions.json @@ -0,0 +1,7 @@ +{ + "src/components.ts": { + "react-hooks/refs": { + "count": 2 + } + } +} \ No newline at end of file diff --git a/apps/admin-x-framework/eslint-suppressions.json b/apps/admin-x-framework/eslint-suppressions.json new file mode 100644 index 000000000000..3bd323850017 --- /dev/null +++ b/apps/admin-x-framework/eslint-suppressions.json @@ -0,0 +1,27 @@ +{ + "src/api/automations.ts": { + "react-hooks/immutability": { + "count": 1 + } + }, + "src/hooks/use-active-visitors.ts": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/hooks/use-tinybird-token.ts": { + "react-hooks/globals": { + "count": 1 + } + }, + "src/providers/navigation-stack-provider.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/providers/router-provider.tsx": { + "react-hooks/refs": { + "count": 1 + } + } +} \ No newline at end of file diff --git a/apps/admin-x-framework/src/api/app-installations.ts b/apps/admin-x-framework/src/api/app-installations.ts index 82ddd4a28140..a3e732764235 100644 --- a/apps/admin-x-framework/src/api/app-installations.ts +++ b/apps/admin-x-framework/src/api/app-installations.ts @@ -11,11 +11,8 @@ export interface AppInstallation { id: string; app_id: string; status: AppInstallationStatus; - /** - * Increments with every change to the installation, so a session can tell it has ended. Missing - * on Ghost versions from before app sessions. - */ - revision?: number; + /** Increments with every change to the installation, so a session can tell it has ended. */ + revision: number; manifest_url: string; manifest: AppManifest; icon_data_url: string | null; @@ -59,8 +56,7 @@ export interface AppInstallationPreview { * The app's origin, if the site's configuration trusts it, so Ghost didn't ask it to prove it * holds the app's key. Empty when it proved it. An app is one origin, so there's at most one. */ - /** Missing from a Ghost from before the identity check, which trusted no origin. */ - trusted_origins?: string[]; + trusted_origins: string[]; /** * The site's installation of the same app, if it has one: the manifest it was approved * with and where that was read from, and what would change. @@ -114,16 +110,13 @@ export const useBrowseAppInstallations = createQuery `/apps/installations/${id}/`; - /** * Unlike `useBrowseAppInstallations`, this also returns uninstalled apps. * That way their details page still loads. */ export const useReadAppInstallation = createQueryWithId({ dataType, - path: appInstallationPath, + path: (id) => `/apps/installations/${id}/`, defaultSearchParams: { include: 'history' }, }); @@ -133,7 +126,6 @@ export const useReadAppInstallation = createQueryWithId({ method: 'POST', diff --git a/apps/admin-x-framework/src/api/automations.ts b/apps/admin-x-framework/src/api/automations.ts index 659e96f13d32..b99e06f163bb 100644 --- a/apps/admin-x-framework/src/api/automations.ts +++ b/apps/admin-x-framework/src/api/automations.ts @@ -94,6 +94,13 @@ export type AutomationTriggerRule = scope: 'specific_paid_tier'; product_id: string; direction: 'from' | 'to'; + } + | { + trigger_type: 'label_added'; + label_id: string; + scope: null; + product_id: null; + direction: null; }; export type AutomationTrigger = { trigger_rules: readonly AutomationTriggerRule[] }; diff --git a/apps/admin-x-framework/src/api/labels.ts b/apps/admin-x-framework/src/api/labels.ts index 24f611b25c2c..7085aab24fe1 100644 --- a/apps/admin-x-framework/src/api/labels.ts +++ b/apps/admin-x-framework/src/api/labels.ts @@ -1,25 +1,65 @@ import { InfiniteData } from '@tanstack/react-query'; -import { Meta, createInfiniteQuery, createMutation } from '../utils/api/hooks'; +import { createInfiniteQuery, createMutation, createQueryWithId } from '../utils/api/hooks'; import { apiUrl, useFetchApi } from '../utils/api/fetch-api'; import { escapeNqlString } from '@tryghost/nql-string'; import { useCallback } from 'react'; import { useQueryClient } from '@tanstack/react-query'; +import { z } from 'zod'; -export type Label = { - id: string; - name: string; - slug: string; - created_at: string; - updated_at: string; -}; +const LabelSchema = z.object({ + id: z.string(), + name: z.string(), + slug: z.string(), + created_at: z.string(), + updated_at: z.string(), +}); + +const LabelsResponseSchema = z.object({ + labels: z.array(LabelSchema), + meta: z + .object({ + capabilities: z.object({ dislikes: z.boolean().optional() }).optional(), + pagination: z.object({ + page: z.number(), + limit: z.union([z.number(), z.literal('all')]), + pages: z.number(), + total: z.number(), + next: z.number().nullable(), + prev: z.number().nullable(), + }), + }) + .optional(), +}); -export interface LabelsResponseType { - meta?: Meta; - labels: Label[]; -} +export type Label = z.infer; +export type LabelsResponseType = z.infer; + +const ReadLabelResponseSchema = LabelsResponseSchema.extend({ + labels: z.array(LabelSchema).length(1), +}); const dataType = 'LabelsResponseType'; +export const useReadLabel = createQueryWithId({ + dataType, + path: (id) => `/labels/${id}/`, + parseResponse: (data) => ReadLabelResponseSchema.parse(data), +}); + +export const useCacheLabel = () => { + const queryClient = useQueryClient(); + return useCallback( + (label: Label) => { + const data = ReadLabelResponseSchema.parse({ labels: [label] }); + queryClient.setQueryData( + [dataType, apiUrl(`/labels/${label.id}/`)], + data, + ); + }, + [queryClient], + ); +}; + export const useBrowseLabelsInfinite = createInfiniteQuery( { dataType, diff --git a/apps/admin/README.md b/apps/admin/README.md index 128321734ec5..9e21f3073274 100644 --- a/apps/admin/README.md +++ b/apps/admin/README.md @@ -50,6 +50,10 @@ Add an acceptance test for the older-backend case. The social accounts settings and membership tiers tests contain current examples of hiding controls until their supporting settings are present. +Ghost Apps is the exception while `apps` is a private Labs flag: its Admin code +assumes a matching Core, with no older-backend fallbacks or tests. Origin, +framing, identity and allowlist checks still apply. + ### Code that fails to load Screens, the editor and the search modal load their code when first needed. A diff --git a/apps/admin/eslint-suppressions.json b/apps/admin/eslint-suppressions.json new file mode 100644 index 000000000000..b4772bc084e2 --- /dev/null +++ b/apps/admin/eslint-suppressions.json @@ -0,0 +1,652 @@ +{ + "src/analytics/views/stats/growth/components/growth-kpis.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/analytics/views/stats/growth/components/paid-subscription-change-chart.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/analytics/views/stats/growth/growth.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/analytics/views/stats/newsletters/components/newsletters-kpis.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/apps/app-page.tsx": { + "react-hooks/refs": { + "count": 3 + } + }, + "src/apps/components/app-icon.tsx": { + "react-hooks/static-components": { + "count": 1 + } + }, + "src/automations/components/canvas/automation-canvas.tsx": { + "react-hooks/refs": { + "count": 4 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/automations/components/canvas/editable-email-card.tsx": { + "react-hooks/refs": { + "count": 3 + } + }, + "src/automations/components/canvas/run-list.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/automations/components/canvas/tier-scope-picker.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/automations/components/canvas/use-sticky-run-summary.ts": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/automations/components/email-modal/email-editor.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/automations/components/email-modal/preview-frame.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/automations/components/email-modal/test-email-dropdown.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/automations/editor.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/billing/billing-frame.tsx": { + "react-hooks/refs": { + "count": 5 + } + }, + "src/comments/components/comments-list.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/editor/editor-header-actions.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/editor/preview/browser-preview.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/editor/preview/post-preview-modal.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/editor/publish/update-flow-modal.tsx": { + "react-hooks/refs": { + "count": 7 + } + }, + "src/editor/publish/use-draft-newsletter.ts": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/editor/publish/use-publish-flow.ts": { + "react-hooks/refs": { + "count": 13 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/editor/publish/use-publish-limits.ts": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/editor/session/feature-image-binding.ts": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/editor/session/use-editor-session.ts": { + "react-hooks/refs": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/editor/session/use-leave-guard.ts": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/editor/settings/meta-data-tabs-section.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/editor/settings/post-settings-sidebar.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/editor/settings/publish-date-section.tsx": { + "react-hooks/purity": { + "count": 1 + } + }, + "src/editor/unsplash-picker.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/editor/use-editor-shortcuts.ts": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/editor/use-post-card-config.ts": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/editor/use-save-feedback.tsx": { + "react-hooks/refs": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/global-search/global-search-provider.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/hooks/use-hash-link-navigation-guard.ts": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/hooks/use-history-pop-navigation-guard.ts": { + "react-hooks/refs": { + "count": 3 + } + }, + "src/hooks/use-pintura-editor.ts": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/hooks/use-theme.ts": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/hooks/use-unsaved-changes-guard.test.tsx": { + "react-hooks/globals": { + "count": 4 + }, + "react-hooks/immutability": { + "count": 1 + } + }, + "src/hooks/use-unsaved-changes-guard.ts": { + "react-hooks/refs": { + "count": 24 + } + }, + "src/layout/admin-layout.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/layout/app-sidebar/hooks/use-navigation-preferences.ts": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/layout/app-sidebar/hooks/use-upgrade-status.ts": { + "react-hooks/purity": { + "count": 1 + } + }, + "src/layout/floating-sidebar-content-sync.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/layout/screen-transition-provider.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/layout/skip-link.tsx": { + "react-hooks/immutability": { + "count": 1 + } + }, + "src/members/components/bulk-action-modals/import-members/import-members-modal.tsx": { + "react-hooks/immutability": { + "count": 2 + } + }, + "src/members/components/bulk-action-modals/unsubscribe-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/members/detail/member-add-comp-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/members/detail/member-delete-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/members/detail/member-detail.tsx": { + "react-hooks/refs": { + "count": 3 + }, + "react-hooks/set-state-in-effect": { + "count": 3 + } + }, + "src/members/detail/member-disable-commenting-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/members/detail/member-impersonate-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/members/detail/member-labels-field.tsx": { + "react-hooks/refs": { + "count": 3 + } + }, + "src/members/hooks/use-label-picker.ts": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/members/hooks/use-multiple-active-subscriptions-banner.ts": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/members/label-picker/label-picker.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/members/members.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/onboarding/onboarding-route.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/posts/analytics/email-sending-status/email-sending-status-provider.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/posts/analytics/modals/gift-link-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/posts/analytics/overview/overview.tsx": { + "react-hooks/preserve-manual-memoization": { + "count": 1 + } + }, + "src/posts/list/components/post-list-row-email-status.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/posts/list/hooks/use-post-selection.ts": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/posts/list/posts-list-screen.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/settings/advanced/history-modal.tsx": { + "react-hooks/refs": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/advanced/integrations/first-promoter-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/advanced/integrations/pintura-modal.tsx": { + "react-hooks/immutability": { + "count": 1 + } + }, + "src/settings/advanced/integrations/transistor-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/advanced/integrations/unsplash-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/components/color-picker-field.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/components/top-level-group.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/email/default-recipients.tsx": { + "react-hooks/refs": { + "count": 2 + }, + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/email/emails.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/email/newsletters/add-newsletter-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/email/newsletters/newsletter-detail-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/email/use-newsletter-reorder.ts": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/general/ghost-updates/ghost-updates.tsx": { + "react-hooks/purity": { + "count": 2 + } + }, + "src/settings/general/publication-language.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/general/social-accounts.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/general/user-detail-modal.tsx": { + "react-hooks/refs": { + "count": 3 + } + }, + "src/settings/general/users.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/growth/embed-signup/embed-signup-form-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/growth/embed-signup/embed-signup-preview.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/settings/growth/embed-signup/embed-signup-sidebar.tsx": { + "react-hooks/refs": { + "count": 2 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/growth/offers/add-offer-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/growth/offers/edit-offer-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/growth/offers/edit-retention-offer-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 4 + } + }, + "src/settings/growth/offers/offer-success.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/growth/recommendations/add-recommendation-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/growth/tips-and-donations.tsx": { + "react-hooks/immutability": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/hooks/scroll-section-provider.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/settings/hooks/use-pintura-editor.ts": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/layout/app.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + }, + "react-hooks/static-components": { + "count": 1 + } + }, + "src/settings/membership/analytics.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/membership/member-emails/member-email-editor.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/settings/membership/member-emails/test-email-dropdown.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/membership/member-emails/welcome-email-customize-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/membership/member-emails/welcome-email-preview-frame.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/membership/portal/account-page.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/membership/portal/portal-links.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/membership/portal/signup-options.tsx": { + "react-hooks/preserve-manual-memoization": { + "count": 1 + } + }, + "src/settings/membership/tiers.tsx": { + "react-hooks/immutability": { + "count": 1 + } + }, + "src/settings/membership/tiers/tier-detail-modal.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/settings/providers/global-data-provider.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/settings-route.tsx": { + "react-hooks/static-components": { + "count": 1 + } + }, + "src/settings/site/announcement-bar/announcement-bar-preview.tsx": { + "react-hooks/use-memo": { + "count": 1 + } + }, + "src/settings/site/design-and-branding/theme-preview.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/settings/site/design-and-branding/theme-setting.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/site/design-and-theme-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 2 + } + }, + "src/settings/site/design-panel.tsx": { + "react-hooks/refs": { + "count": 2 + } + }, + "src/settings/site/theme-modal.tsx": { + "react-hooks/immutability": { + "count": 1 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/site/theme/theme-code-editor-modal.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/settings/utils/iframe-buffering.tsx": { + "react-hooks/refs": { + "count": 1 + } + }, + "src/settings/utils/search.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/shared/fading-text.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/shared/filters/relative-date-filter.tsx": { + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/shared/pickers/chip-picker.tsx": { + "react-hooks/refs": { + "count": 2 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/tags/detail/tag-detail.tsx": { + "react-hooks/refs": { + "count": 5 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + }, + "src/tags/detail/tag-image-field.tsx": { + "react-hooks/refs": { + "count": 2 + }, + "react-hooks/set-state-in-effect": { + "count": 1 + } + } +} \ No newline at end of file diff --git a/apps/admin/src/analytics/hooks/use-growth-stats.test.tsx b/apps/admin/src/analytics/hooks/use-growth-stats.test.tsx index 635c0faa2c0f..b2d529210063 100644 --- a/apps/admin/src/analytics/hooks/use-growth-stats.test.tsx +++ b/apps/admin/src/analytics/hooks/use-growth-stats.test.tsx @@ -1,5 +1,5 @@ import moment from 'moment'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mockLoading, mockNull, @@ -19,14 +19,6 @@ vi.mock('@tryghost/admin-x-framework', () => ({ getSymbol: vi.fn(), })); -vi.mock('@tryghost/shade/utils', async () => { - const actual = await vi.importActual('@tryghost/shade/utils'); - return { - ...actual, - formatPercentage: vi.fn(), - }; -}); - vi.mock('@/shared/analytics/chart-helpers', async () => { const actual = await vi.importActual('@/shared/analytics/chart-helpers'); return { @@ -35,9 +27,9 @@ vi.mock('@/shared/analytics/chart-helpers', async () => { }; }); -import { formatPercentage } from '@tryghost/shade/utils'; import { getRangeDates } from '@/shared/analytics/chart-helpers'; import { getSymbol } from '@tryghost/admin-x-framework'; +import { STATS_RANGES } from '@/shared/analytics/constants'; import { useMemberCountHistory, useMrrHistory, @@ -48,7 +40,6 @@ const mockedUseMemberCountHistory = useMemberCountHistory as ReturnType; const mockedUseSubscriptionStats = useSubscriptionStats as ReturnType; const mockedGetSymbol = getSymbol as ReturnType; -const mockedFormatPercentage = formatPercentage as ReturnType; const mockedGetRangeDates = getRangeDates as ReturnType; // Mock data for testing @@ -97,11 +88,7 @@ const mockSubscriptionData = [ describe('useGrowthStats', () => { beforeEach(() => { vi.clearAllMocks(); - - // Mock formatPercentage to return a consistent format - mockedFormatPercentage.mockImplementation( - (value: number) => `${Math.abs(value * 100).toFixed(1)}%`, - ); + vi.setSystemTime(new Date(2024, 5, 27, 12)); // Mock getRangeDates with realistic behavior mockedGetRangeDates.mockImplementation((range: number) => { @@ -133,6 +120,61 @@ describe('useGrowthStats', () => { mockedGetSymbol.mockReturnValue('$'); }); + afterEach(() => { + vi.useRealTimers(); + }); + + it.each([ + STATS_RANGES.last7Days, + STATS_RANGES.last30Days, + STATS_RANGES.last3Months, + STATS_RANGES.last12Months, + STATS_RANGES.yearToDate, + ])('includes first-day growth in $name', ({ value }) => { + const { startDate, endDate } = getRangeDates(value); + const firstDay = startDate.format('YYYY-MM-DD'); + const previousDay = startDate.clone().subtract(1, 'day').format('YYYY-MM-DD'); + const lastDay = endDate.format('YYYY-MM-DD'); + const before = { ...mockMemberData[0], date: previousDay, free: 130 }; + const first = { ...mockMemberData[2], date: firstDay, free: 139 }; + const last = { ...first, date: lastDay, paid_subscribed: 0, paid_canceled: 0 }; + + // Member history starts on the requested date. MRR history also includes + // the closing balance immediately before its first change. + mockedUseMemberCountHistory.mockImplementation( + ({ searchParams }: { searchParams: { date_from: string } }) => ({ + data: { + stats: [before, first, last].filter(({ date }) => date >= searchParams.date_from), + }, + isLoading: false, + }), + ); + mockSuccess(mockedUseMrrHistory, { + stats: [ + { date: previousDay, mrr: 5000, currency: 'usd' }, + { date: firstDay, mrr: 5500, currency: 'usd' }, + ], + meta: { totals: [{ mrr: 5500, currency: 'usd' }] }, + }); + + const { result } = renderHook(() => useGrowthStats(value)); + + expect(result.current.totals.percentChanges).toEqual({ + total: '8%', + free: '7%', + paid: '11%', + mrr: '10%', + }); + expect(result.current.totals.directions).toEqual({ + total: 'up', + free: 'up', + paid: 'up', + mrr: 'up', + }); + expect(result.current.chartData.map(({ date }) => date)).toEqual([firstDay, lastDay]); + expect(result.current.chartData[0]).toMatchObject({ free: 139, mrr: 5500, paid_subscribed: 4 }); + }); + describe('hook basic functionality', () => { it('returns initial loading state', () => { mockLoading(mockedUseMemberCountHistory); @@ -300,6 +342,21 @@ describe('useGrowthStats', () => { }); describe('MRR data processing', () => { + it('uses the opening balance when the first MRR change is later in the range', () => { + mockSuccess(mockedUseMrrHistory, { + stats: [ + { date: '2024-06-25', mrr: 5000, currency: 'usd' }, + { date: '2024-06-26', mrr: 5500, currency: 'usd' }, + ], + meta: { totals: [{ mrr: 5500, currency: 'usd' }] }, + }); + + const { result } = renderHook(() => useGrowthStats(STATS_RANGES.last7Days.value)); + + expect(result.current.totals.percentChanges.mrr).toBe('10%'); + expect(result.current.totals.directions.mrr).toBe('up'); + }); + it('adds start point when missing', async () => { const earlierMrrData = [ { date: '2024-06-20', mrr: 5000, currency: 'usd' }, @@ -365,15 +422,21 @@ describe('useGrowthStats', () => { expect(result.current.mrrData[0].mrr).toBe(17286); }); - it('handles range=1 correctly', async () => { - const { result } = renderHook(() => useGrowthStats(1)); - - await waitFor(() => { - expect(result.current.isLoading).toBe(false); + it('retains the date-based MRR request and trend for Today', () => { + const today = { date: '2024-06-27', mrr: 9500, currency: 'usd' }; + mockSuccess(mockedUseMrrHistory, { + stats: [{ ...today, date: '2024-06-26', mrr: 10000 }, today], + meta: { totals: [{ mrr: 9500, currency: 'usd' }] }, }); - // For range=1, should use appropriate date logic - expect(result.current.mrrData).toBeDefined(); + const { result } = renderHook(() => useGrowthStats(STATS_RANGES.today.value)); + + expect(mockedUseMrrHistory).toHaveBeenCalledWith({ + searchParams: { date_from: '2024-06-26' }, + }); + expect(result.current.mrrData).toEqual([today]); + expect(result.current.totals.percentChanges.mrr).toBe('0%'); + expect(result.current.totals.directions.mrr).toBe('same'); }); }); diff --git a/apps/admin/src/analytics/hooks/use-growth-stats.ts b/apps/admin/src/analytics/hooks/use-growth-stats.ts index 216725c29314..0c0406873a57 100644 --- a/apps/admin/src/analytics/hooks/use-growth-stats.ts +++ b/apps/admin/src/analytics/hooks/use-growth-stats.ts @@ -15,12 +15,19 @@ import { useMemo } from 'react'; export type DiffDirection = 'up' | 'down' | 'same'; // Calculate totals from member data -const calculateTotals = ( - memberData: MemberStatusItem[], - mrrData: MrrHistoryItem[], - dateFrom: string, - memberCountTotals?: { paid: number; free: number; comped: number; gift: number }, -) => { +const calculateTotals = ({ + memberData, + mrrData, + openingMember, + openingMrr, + memberCountTotals, +}: { + memberData: MemberStatusItem[]; + mrrData: MrrHistoryItem[]; + openingMember?: MemberStatusItem; + openingMrr?: number; + memberCountTotals?: { paid: number; free: number; comped: number; gift: number }; +}) => { if (!memberData.length) { return { totalMembers: 0, @@ -43,11 +50,8 @@ const calculateTotals = ( } // Use current totals from API meta if available, otherwise use latest time series data - const currentTotals = memberCountTotals || memberData[memberData.length - 1]; - const latest = - memberData.length > 0 - ? memberData[memberData.length - 1] - : { free: 0, paid: 0, comped: 0, gift: 0 }; + const latest = memberData[memberData.length - 1]; + const currentTotals = memberCountTotals ?? latest; const latestMrr = mrrData.length > 0 ? mrrData[mrrData.length - 1] : { mrr: 0 }; @@ -72,82 +76,36 @@ const calculateTotals = ( mrr: 'same' as DiffDirection, }; - if (memberData.length > 1) { - // Get first day in range - const first = memberData[0]; - const firstTotal = first.free + first.paid + first.comped + (first.gift ?? 0); + if (openingMember) { + const openingPaid = openingMember.paid + openingMember.comped + (openingMember.gift ?? 0); + const openingTotal = openingMember.free + openingPaid; - if (firstTotal > 0) { - const totalChange = ((totalMembers - firstTotal) / firstTotal) * 100; + if (openingTotal > 0) { + const totalChange = ((totalMembers - openingTotal) / openingTotal) * 100; percentChanges.total = formatPercentage(totalChange / 100); directions.total = totalChange > 0 ? 'up' : totalChange < 0 ? 'down' : 'same'; } - if (first.free > 0) { - const freeChange = ((latest.free - first.free) / first.free) * 100; + if (openingMember.free > 0) { + const freeChange = ((latest.free - openingMember.free) / openingMember.free) * 100; percentChanges.free = formatPercentage(freeChange / 100); directions.free = freeChange > 0 ? 'up' : freeChange < 0 ? 'down' : 'same'; } - const firstPaidTotal = first.paid + first.comped + (first.gift ?? 0); const latestPaidTotal = latest.paid + latest.comped + (latest.gift ?? 0); - if (firstPaidTotal > 0) { - const paidChange = ((latestPaidTotal - firstPaidTotal) / firstPaidTotal) * 100; + if (openingPaid > 0) { + const paidChange = ((latestPaidTotal - openingPaid) / openingPaid) * 100; percentChanges.paid = formatPercentage(paidChange / 100); directions.paid = paidChange > 0 ? 'up' : paidChange < 0 ? 'down' : 'same'; } } - if (mrrData.length > 1) { - // Find the first ACTUAL data point within the selected date range (not synthetic boundary points) - const actualStartDate = moment(dateFrom).format('YYYY-MM-DD'); - const firstActualPoint = mrrData.find((point) => - moment(point.date).isSameOrAfter(actualStartDate), - ); - - // Check if this is a "from beginning" range (like YTD) vs a recent range - const isFromBeginningRange = - moment(dateFrom).isSame(moment().startOf('year'), 'day') || - moment(dateFrom).year() < moment().year(); - - let firstMrr = 0; - - if (firstActualPoint) { - // Check if the first actual point is exactly at the start date - if (moment(firstActualPoint.date).isSame(actualStartDate, 'day')) { - firstMrr = firstActualPoint.mrr; - } else { - // First actual point is later than start date - if (isFromBeginningRange) { - // For YTD/beginning ranges, assume started from 0 - firstMrr = 0; - } else { - // For recent ranges, use the most recent MRR before the range - // This should be the same as current MRR (flat line scenario) - firstMrr = totalMrr; - } - } - } else if (isFromBeginningRange) { - // No data points in range, and it's a from-beginning range - firstMrr = 0; - } else { - // No data points in recent range, carry forward current MRR - firstMrr = totalMrr; - } - - if (firstMrr >= 0) { - // Allow 0 as a valid starting point - const mrrChange = - firstMrr === 0 - ? totalMrr > 0 - ? 100 - : 0 // If starting from 0, any positive value is 100% increase - : ((totalMrr - firstMrr) / firstMrr) * 100; - - percentChanges.mrr = formatPercentage(mrrChange / 100); - directions.mrr = mrrChange > 0 ? 'up' : mrrChange < 0 ? 'down' : 'same'; - } + if (openingMrr !== undefined && openingMrr >= 0) { + const mrrChange = + openingMrr === 0 ? (totalMrr > 0 ? 1 : 0) : (totalMrr - openingMrr) / openingMrr; + percentChanges.mrr = formatPercentage(mrrChange); + directions.mrr = mrrChange > 0 ? 'up' : mrrChange < 0 ? 'down' : 'same'; } return { @@ -221,24 +179,20 @@ const formatChartData = (memberData: MemberStatusItem[], mrrData: MrrHistoryItem }; export const useGrowthStats = (range: number) => { - // Calculate date range using Shade's timezone-aware getRangeDates const { startDate, endDate } = useMemo(() => getRangeDates(range), [range]); const dateFrom = formatQueryDate(startDate); + const openingBalanceDate = formatQueryDate(startDate.clone().subtract(1, 'day')); - // Fetch member count history from API - // For single day ranges, we need at least 2 days of data to show a proper delta - const memberDataStartDate = - range === 1 ? moment(dateFrom).subtract(1, 'day').format('YYYY-MM-DD') : dateFrom; - + // Member history starts at date_from and each row contains closing balances. const { data: memberCountResponse, isLoading: isMemberCountLoading } = useMemberCountHistory({ searchParams: { - date_from: memberDataStartDate, + date_from: openingBalanceDate, }, }); const { data: mrrHistoryResponse, isLoading: isMrrLoading } = useMrrHistory({ searchParams: { - date_from: memberDataStartDate, + date_from: range === 1 ? openingBalanceDate : dateFrom, }, }); @@ -246,47 +200,38 @@ export const useGrowthStats = (range: number) => { const { data: subscriptionStatsResponse, isLoading: isSubscriptionLoading } = useSubscriptionStats(); - // Process member data with stable reference - const memberData = useMemo(() => { - let rawData: MemberStatusItem[] = []; - - // Check the structure of the response and extract data + const rawMemberData = useMemo(() => { if (memberCountResponse?.stats) { - rawData = memberCountResponse.stats; - } else if (Array.isArray(memberCountResponse)) { - // If response is directly an array - rawData = memberCountResponse; + return memberCountResponse.stats; } + return Array.isArray(memberCountResponse) ? memberCountResponse : []; + }, [memberCountResponse]); - // For single day (Today), ensure we have two data points for a proper line - if (range === 1 && rawData.length >= 2) { - // We should have yesterday's data and today's data - const yesterdayData = rawData[rawData.length - 2]; // Yesterday's EOD counts - const todayData = rawData[rawData.length - 1]; // Today's EOD counts - - const startOfToday = moment(dateFrom).format('YYYY-MM-DD'); // 6/26 - const startOfTomorrow = moment(dateFrom).add(1, 'day').format('YYYY-MM-DD'); // 6/27 - - // Create two data points: - // 1. Yesterday's EOD count attributed to start of today (6/26) - // 2. Today's EOD count attributed to start of tomorrow (6/27) - const startPoint = { - ...yesterdayData, - date: startOfToday, - }; + const { memberData, openingMember } = useMemo(() => { + if (range === 1) { + if (rawMemberData.length < 2) { + return { memberData: rawMemberData }; + } - const endPoint = { - ...todayData, - date: startOfTomorrow, + // Draw Today's line from its opening balance to its closing balance. + const [yesterdayData, todayData] = rawMemberData.slice(-2); + const tomorrow = moment(dateFrom).add(1, 'day').format('YYYY-MM-DD'); + return { + openingMember: yesterdayData, + memberData: [ + { ...yesterdayData, date: dateFrom }, + { ...todayData, date: tomorrow }, + ], }; - - return [startPoint, endPoint]; } - return rawData; - }, [memberCountResponse, range, dateFrom]); + return { + memberData: rawMemberData.filter((item) => item.date >= dateFrom), + openingMember: rawMemberData.find((item) => item.date === openingBalanceDate), + }; + }, [rawMemberData, range, dateFrom, openingBalanceDate]); - const { mrrData, selectedCurrency } = useMemo(() => { + const { mrrData, openingMrr, selectedCurrency } = useMemo(() => { const dateFromMoment = moment(dateFrom); // For "Today" range (1 day), use end of today to match visitor data behavior const dateToMoment = range === 1 ? moment().endOf('day') : moment().startOf('day'); @@ -319,31 +264,15 @@ export const useGrowthStats = (range: number) => { const allData = [...currencyFilteredData].sort( (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime(), ); + // The API dates its opening balance just before the first change. For + // sparse history that date can fall inside the selected range. + const openingPoint = allData.find((item) => item.date < dateFrom) ?? allData.at(-1); const result = [...filteredData]; // Always ensure we have a data point at the start of the range const hasStartPoint = result.some((item) => moment(item.date).isSame(dateFromMoment, 'day')); - if (!hasStartPoint) { - const mostRecentBeforeRange = allData.find((item) => { - return moment(item.date).isBefore(dateFromMoment); - }); - - if (mostRecentBeforeRange) { - result.unshift({ - ...mostRecentBeforeRange, - date: dateFromMoment.format('YYYY-MM-DD'), - }); - } else if (result.length > 0) { - // No data before range, use the earliest data point in the range - // to fill in the start date (representing MRR at range start) - const earliestInRange = [...result].sort( - (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(), - )[0]; - result.unshift({ - ...earliestInRange, - date: dateFromMoment.format('YYYY-MM-DD'), - }); - } + if (!hasStartPoint && openingPoint) { + result.unshift({ ...openingPoint, date: dateFrom }); } // Always ensure we have a data point at the end of the range @@ -366,15 +295,32 @@ export const useGrowthStats = (range: number) => { (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(), ); - return { mrrData: finalResult, selectedCurrency: useCurrency }; + return { + mrrData: finalResult, + // Today uses the displayed UTC-day series until Core can supply the local opening balance. + openingMrr: + range === 1 + ? finalResult.length > 1 + ? finalResult[0].mrr + : undefined + : openingPoint?.mrr, + selectedCurrency: useCurrency, + }; } return { mrrData: [], selectedCurrency: 'usd' }; }, [mrrHistoryResponse, dateFrom, range]); // Calculate totals const totalsData = useMemo( - () => calculateTotals(memberData, mrrData, dateFrom, memberCountResponse?.meta?.totals), - [memberData, mrrData, dateFrom, memberCountResponse?.meta?.totals], + () => + calculateTotals({ + memberData, + mrrData, + openingMember, + openingMrr, + memberCountTotals: memberCountResponse?.meta?.totals, + }), + [memberData, mrrData, openingMember, openingMrr, memberCountResponse?.meta?.totals], ); // Format chart data @@ -439,6 +385,8 @@ export const useGrowthStats = (range: number) => { endDate, totals: totalsData, chartData, + // Today’s event counts belong to the API dates, before shifting the line chart points. + memberChangeData: range === 1 ? rawMemberData : chartData, subscriptionData, selectedCurrency, currencySymbol, diff --git a/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.test.tsx b/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.test.tsx index 4c853e7c526a..77243fc1d3a9 100644 --- a/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.test.tsx +++ b/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.test.tsx @@ -1,8 +1,22 @@ import moment from 'moment'; -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; +import { + useMemberCountHistory, + useMrrHistory, + useSubscriptionStats, +} from '@tryghost/admin-x-framework/api/stats'; import PaidMembersChangeChart from '@/analytics/views/stats/growth/components/paid-subscription-change-chart'; +import { getRangeDates } from '@/shared/analytics/chart-helpers'; +import { mockSuccess } from '@tryghost/admin-x-framework/test/hook-testing-utils'; +import { useGrowthStats } from '@/analytics/hooks/use-growth-stats'; + +vi.mock('@tryghost/admin-x-framework/api/stats', () => ({ + useMemberCountHistory: vi.fn(), + useMrrHistory: vi.fn(), + useSubscriptionStats: vi.fn(), +})); // Mock the date-range helper the chart derives its window from vi.mock('@/shared/analytics/chart-helpers', async () => { @@ -27,6 +41,10 @@ vi.mock('@tryghost/shade/utils', async () => { }); describe('PaidMembersChangeChart Component', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + // Helper to generate mock data with dates within the mocked range (2024-01-01 to 2024-01-31) const getMockMemberData = () => { return [ @@ -50,6 +68,7 @@ describe('PaidMembersChangeChart Component', () => { render( { render( { render( { expect(dropdown).toBeInTheDocument(); expect(dropdown).toHaveTextContent('Weekly'); }); + + const previousDay = { date: '2024-01-14', paid_subscribed: 4, paid_canceled: 1 }; + const quietDay = { date: '2024-01-15', paid_subscribed: 0, paid_canceled: 0 }; + const activeDay = { date: '2024-01-15', paid_subscribed: 2, paid_canceled: 1 }; + const nextUtcDay = { date: '2024-01-16', paid_subscribed: 7, paid_canceled: 3 }; + + it.each([ + { scenario: 'a quiet UTC day', rows: [previousDay, quietDay], expected: [0, 0] }, + { scenario: 'an active UTC day', rows: [previousDay, activeDay], expected: [2, 1] }, + { scenario: 'Tokyo before UTC midnight', rows: [previousDay], expected: [0, 0] }, + { + scenario: 'New York after UTC midnight', + rows: [previousDay, activeDay, nextUtcDay], + expected: [2, 1], + }, + ])('shows the selected date’s member changes for $scenario', ({ rows, expected }) => { + vi.mocked(getRangeDates).mockReturnValueOnce({ + startDate: moment('2024-01-15').startOf('day'), + endDate: moment('2024-01-15').endOf('day'), + timezone: 'UTC', + }); + mockSuccess(vi.mocked(useMemberCountHistory), { + stats: rows.map((row) => ({ ...row, paid: 10, free: 0, comped: 0, gift: 0 })), + }); + mockSuccess(vi.mocked(useMrrHistory), { stats: [], meta: { totals: [] } }); + mockSuccess(vi.mocked(useSubscriptionStats), { stats: [] }); + + function TodayChart() { + const { dateFrom, isLoading, memberChangeData, subscriptionData } = useGrowthStats(1); + return ( + + ); + } + + render(); + + const [signups, cancellations] = expected; + if (signups === 0 && cancellations === 0) { + expect(screen.getByText('No paid member changes')).toBeInTheDocument(); + } else { + expect(screen.getByText('New').parentElement).toHaveTextContent(`New${signups}`); + expect(screen.getByText('Cancelled').parentElement).toHaveTextContent( + `Cancelled${cancellations}`, + ); + } + }); }); diff --git a/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.tsx b/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.tsx index 7a05c8970898..714bac91eab8 100644 --- a/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.tsx +++ b/apps/admin/src/analytics/views/stats/growth/components/paid-subscription-change-chart.tsx @@ -34,6 +34,7 @@ import { import { useShade } from '@tryghost/shade/app'; type PaidMembersChangeChartProps = { + dateFrom: string; subscriptionData?: { date: string; signups: number; cancellations: number }[]; memberData: { date: string; @@ -158,7 +159,7 @@ const getAvailableResolutions = (range: number): ResolutionOption[] => { if (actualSpan < 30) { return ['daily']; // No dropdown for < 30 days - } else if (actualSpan >= 91) { + } else if (actualSpan >= 90) { return ['weekly', 'monthly']; } else { return ['daily', 'weekly']; @@ -171,7 +172,7 @@ const getDefaultResolution = (range: number): ResolutionOption => { if (actualSpan < 30) { return 'daily'; - } else if (actualSpan >= 91) { + } else if (actualSpan >= 90) { return 'monthly'; } else { return 'weekly'; @@ -179,6 +180,7 @@ const getDefaultResolution = (range: number): ResolutionOption => { }; const PaidMembersChangeChart: React.FC = ({ + dateFrom, subscriptionData, memberData, range, @@ -222,13 +224,12 @@ const PaidMembersChangeChart: React.FC = ({ if (subscriptionData && subscriptionData.length > 0) { // For "Today" range, show just the change for today if (range === 1) { - const today = moment().format('YYYY-MM-DD'); - const todayData = subscriptionData.find((item) => item.date === today); + const todayData = subscriptionData.find((item) => item.date === dateFrom); return [ { - date: formatDisplayDateWithRange(today, range), - rawDate: today, // Keep raw date for dynamic tooltip formatting + date: formatDisplayDateWithRange(dateFrom, range), + rawDate: dateFrom, // Keep raw date for dynamic tooltip formatting new: todayData?.signups || 0, cancelled: -(todayData?.cancellations || 0), // Negative for the stacked bar chart }, @@ -294,15 +295,14 @@ const PaidMembersChangeChart: React.FC = ({ return []; } - // For "Today" range, show just today's change + // For Today, memberData contains the original daily history rows. if (range === 1) { - const today = moment().format('YYYY-MM-DD'); - const todayData = memberData.find((item) => item.date === today); + const todayData = memberData.find((item) => item.date === dateFrom); return [ { - date: formatDisplayDateWithRange(today, range), - rawDate: today, // Keep raw date for dynamic tooltip formatting + date: formatDisplayDateWithRange(dateFrom, range), + rawDate: dateFrom, // Keep raw date for dynamic tooltip formatting new: todayData?.paid_subscribed || 0, cancelled: -(todayData?.paid_canceled || 0), // Negative for the stacked bar chart }, @@ -360,7 +360,7 @@ const PaidMembersChangeChart: React.FC = ({ }; }); } - }, [memberData, subscriptionData, range, aggregationStrategy, displayRange]); + }, [dateFrom, memberData, subscriptionData, range, aggregationStrategy, displayRange]); const paidChangeChartConfig = { new: { diff --git a/apps/admin/src/analytics/views/stats/growth/growth.tsx b/apps/admin/src/analytics/views/stats/growth/growth.tsx index d89d476268c1..c38c873cfd21 100644 --- a/apps/admin/src/analytics/views/stats/growth/growth.tsx +++ b/apps/admin/src/analytics/views/stats/growth/growth.tsx @@ -99,7 +99,15 @@ const Growth: React.FC = () => { }, [initialTab]); // Get stats from custom hook once - const { isLoading, chartData, totals, currencySymbol, subscriptionData } = useGrowthStats(range); + const { + isLoading, + chartData, + dateFrom, + memberChangeData, + totals, + currencySymbol, + subscriptionData, + } = useGrowthStats(range); // Get growth data with post_type filtering - only call when not on Sources tab const { data: topPostsData, isLoading: isTopPostsLoading } = useTopPostsStatsWithRange( @@ -209,8 +217,9 @@ const Growth: React.FC = () => { {paidMembersEnabled && currentKpiTab === 'paid-members' && (
diff --git a/apps/admin/src/apps/AGENTS.md b/apps/admin/src/apps/AGENTS.md new file mode 100644 index 000000000000..b524edbbf283 --- /dev/null +++ b/apps/admin/src/apps/AGENTS.md @@ -0,0 +1,12 @@ +# Ghost Apps agent guidance + +While `apps` is in `PRIVATE_FEATURES` (`ghost/core/shared/labs.js`), this code +and `admin-x-framework`'s app API hooks build against a matching Core only, +with no older-Core fallbacks or tests. Origin, framing, identity and allowlist +checks still apply. + +The bridge's Admin API allowlist (`ADMIN_API_ALLOWLIST` in +`contracts/app-contracts/src/bridge/allowlist.ts`) is a stopgap until +Permissions and auth replaces it with app-scoped tokens checked on the server. +Change its routes when an app needs them, and leave scopes, consent and per-app +permissions to that project. diff --git a/apps/admin/src/apps/app-details.tsx b/apps/admin/src/apps/app-details.tsx index 438f19ffa985..d2ea1432e4ae 100644 --- a/apps/admin/src/apps/app-details.tsx +++ b/apps/admin/src/apps/app-details.tsx @@ -9,12 +9,20 @@ import { BreadcrumbPage, BreadcrumbSeparator, Button, - LoadingIndicator, + Card, + CardContent, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, + Skeleton, } from '@tryghost/shade/components'; -import { Box, Container, Inline, Stack, Text } from '@tryghost/shade/primitives'; -import { DetailPage } from '@tryghost/shade/page-templates'; +import { Box, Container, H1, Inline, Stack, Text } from '@tryghost/shade/primitives'; +import { DetailPage, usePageChrome } from '@tryghost/shade/page-templates'; import { PageHeader } from '@tryghost/shade/patterns'; -import { formatDisplayDate } from '@tryghost/shade/utils'; +import { useShade } from '@tryghost/shade/app'; +import { LucideIcon, cn, formatDisplayDate } from '@tryghost/shade/utils'; import { Link, useNavigate, useParams } from '@tryghost/admin-x-framework'; import { type AppInstallation, @@ -27,133 +35,298 @@ import { getSiteTimezone } from '@tryghost/admin-x-framework/utils/get-site-time import { NotFound } from '@/shared/not-found'; import { AccessIndicator, OPENED_APP_ACCESS_INTRO } from './components/access-indicator'; import { AppIcon } from './components/app-icon'; -import { AppPinButton } from './components/app-pin-button'; import { AppsGate } from './components/apps-gate'; -import { CapabilitySummary } from './components/surface-icon'; -import { UninstallDialog } from './components/uninstall-dialog'; +import { SurfaceLine } from './components/surface-icon'; import { ACCOUNT_ACCESS } from './lib/access'; +import { servedFrom } from './lib/served-from'; +import { UninstallDialog } from './components/uninstall-dialog'; import { historyTitle, installedBy } from './lib/history'; import { isInstallationNotFound } from './lib/not-found'; import { appReviewRoute, appRoute } from './lib/routes'; import { useInstalledApps } from './lib/use-app-pins'; import { AppAuthor, UnverifiedDeveloperBadge } from './components/app-author'; -const Fact: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => ( -
- - {label} - - {children} -
+/** A fact in the sidebar, its label over its value, as on a member's details. */ +const InfoRow: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => ( + +

{label}

+
{children}
+
+); + +/** A titled section of the main column, as on a member's or a tag's details. */ +const Section: React.FC<{ + id: string; + title: string; + /** A line under the heading, kept close to it rather than spaced like the section's content. */ + description?: string; + children: React.ReactNode; +}> = ({ id, title, description, children }) => ( +
+ {/* Admin 7 spaces sections a little wider than the scale's md step */} + + +

+ {title} +

+ {description && ( + + {description} + + )} +
+ {children} +
+
+); + +const StatusBadges: React.FC<{ installation: AppInstallation }> = ({ installation }) => ( + <> + {installation.manifest.development && Development} + {installation.status === 'suspended' && Needs approval} + {installation.status === 'uninstalled' && Uninstalled} + ); const History: React.FC<{ entries: AppInstallationHistoryEntry[]; timezone: string }> = ({ entries, timezone, -}) => { - return ( -
    - {entries.map((entry) => ( -
  1. - +}) => ( +
      + {entries.map((entry) => ( +
    1. + + {historyTitle(entry)} {entry.actor?.name && ( - - {' '} - by {entry.actor.name} - + by {entry.actor.name} )} - + {formatDisplayDate(entry.created_at, timezone)} - -
    2. - ))} -
    - ); -}; +
    + +
  2. + ))} +
+); -const Details: React.FC<{ installation: AppInstallation; timezone: string }> = ({ +interface SidebarProps { + installation: AppInstallation; + timezone: string; + /** Where the header doesn't show the app's name large, the sidebar leads with it. */ + showIdentity: boolean; + admin7Design: boolean; +} + +const Sidebar: React.FC = ({ installation, timezone, + showIdentity, + admin7Design, }) => { - const { manifest, status, history = [] } = installation; + const { manifest, history = [] } = installation; const installer = installedBy(history); + // Several surfaces of one kind read as one line. + const surfaceTypes = [...new Set(manifest.surfaces.map((surface) => surface.type))]; + const uninstalled = + installation.status === 'uninstalled' + ? history.find((entry) => entry.event === 'uninstalled') + : undefined; return ( - - + + ); +}; - +const Details: React.FC<{ + installation: AppInstallation; + timezone: string; + showIdentity: boolean; + admin7Design: boolean; +}> = ({ installation, timezone, showIdentity, admin7Design }) => { + const { manifest, status, history = [] } = installation; + const sidebar = ( + + ); + // Lists in a section sit in a ruled card in Admin 7, and an outlined one before it. + const cardVariant = admin7Design ? 'ruled' : 'outline'; + + return ( + // Side by side on wide screens, at the member page's gaps, which go past the scale + + {!admin7Design && sidebar} + {status === 'suspended' && ( - - - {manifest.name} has been updated, and the changes need your approval. It won’t open - until you approve them. - - - + + {manifest.name} has been updated, and the changes need your approval. It won’t open + until you approve them. + )} {status !== 'uninstalled' && ( - +
+ + + + + +
)} - - - History - - - +
+ + + + + +
+ {/* Admin 7 shows the sidebar on the right, so it comes after the main column for the + keyboard too. */} + {admin7Design && sidebar}
); }; +interface ActionsProps { + installation: AppInstallation; + onUninstall: () => void; +} + +const Actions: React.FC = ({ installation, onUninstall }) => { + const { pins } = useInstalledApps(); + const pinned = pins.isPinned(installation.id); + + return ( + + + + + + + + + + {pins.isLoaded && ( + <> + {/* Disabled without a reason when no more apps fit, as in the Apps list. */} + pins.setPinned(installation.id, !pinned)} + > + {pinned ? : } + {pinned ? 'Unpin from sidebar' : 'Pin to sidebar'} + + + + )} + + + Uninstall + + + + {installation.status === 'active' && ( + + + Open + + + )} + {installation.status === 'suspended' && ( + + + Review changes + + + )} + + + ); +}; + export const AppDetails: React.FC = () => { + // Where list pages show their titles large (admin7Design), the app's name shows large under + // the breadcrumb, as a tag's and a member's do. + const { largeTitles } = usePageChrome(); + const { admin7Design } = useShade(); const { installationId = '' } = useParams(); const navigate = useNavigate(); const [uninstalling, setUninstalling] = useState(false); @@ -163,40 +336,21 @@ export const AppDetails: React.FC = () => { defaultErrorHandler: false, }); const installation = data?.app_installations[0]; - const { pins } = useInstalledApps(); - const pinned = installation ? pins.isPinned(installation.id) : false; if (isInstallationNotFound(error)) { return ; } - let body: React.ReactNode; - if (installation) { - body =
; - } else if (error) { - body = ( - - - {getErrorMessage(error, 'Couldn’t load this app. Please try again.')} - - - - ); - } else if (isLoading) { - body = ( - - - - ); - } - return ( - - + + @@ -208,37 +362,81 @@ export const AppDetails: React.FC = () => { - - {installation?.manifest.name} - + {isLoading ? ( + + ) : ( + + {installation?.manifest.name} + + )} {installation && installation.status !== 'uninstalled' && ( - - - {pins.isLoaded && ( - pins.setPinned(installation.id, pin)} - /> - )} - - {installation.status === 'active' && ( - - )} - - + setUninstalling(true)} /> )} + {/* The title wraps rather than truncates, and stops short of the actions above it + on wide screens */} + {largeTitles && (isLoading || installation) && ( + + {isLoading || !installation ? ( + + ) : ( + <> + + + {/* Badges sit on the title's baseline, as on a tag's details and the + list pages' titles */} + +

+ {installation.manifest.name} +

+ +
+
+ {installation.manifest.description} + + )} +
+ )}
- {body} + + + {installation && ( +
+ )} + {!installation && error && ( + +

+ {getErrorMessage(error, 'Couldn’t load this app. Please try again.')} +

+ +
+ )} + = ({
); +/** How a publisher reaches the developer from a screen where the app couldn't open. */ +const ContactSupport: React.FC<{ manifest: AppInstallation['manifest'] }> = ({ manifest }) => { + const support = supportLink(manifest); + return ( + + ); +}; + const NotResponding: React.FC<{ installation: AppInstallation; startedAt: Date; @@ -80,9 +90,7 @@ const NotResponding: React.FC<{ - + } @@ -105,15 +113,19 @@ const NotResponding: React.FC<{ * There's no Uninstall here. When Ghost couldn't confirm the app, uninstalling it and installing * it again from a link is the one way another developer's key gets pinned, so the screen sends the * publisher to the developer instead. Uninstall stays on the app's details page. + * + * Nor is there a Contact support link then. The developer's link often lives on the app's own + * origin, which is the one Ghost couldn't confirm, so the screen offers Back to Apps. */ const Unavailable: React.FC<{ installationId: string; failure: SessionFailure; onRetry: () => void; }> = ({ installationId, failure, onRetry }) => { - const { data } = useBrowseAppInstallations({ defaultErrorHandler: false }); + const { data, isLoading } = useBrowseAppInstallations({ defaultErrorHandler: false }); const installation = data?.app_installations.find(({ id }) => id === installationId); const name = installation?.manifest.name ?? 'This app'; + const offersSupport = !failure.unconfirmed; const at = installation ? ` at ${servedFrom(installation.manifest)}` : ''; const explanation = failure.unconfirmed ? `Ghost couldn’t confirm the app${at} is the one you installed. Contact its developer, and don’t install it again from a link until they’ve fixed it. Your site isn’t affected.` @@ -123,9 +135,18 @@ const Unavailable: React.FC<{ - + {/* Held in place until the list arrives, so no button changes or moves under the cursor. */} + {offersSupport && isLoading ? ( + + ) : offersSupport && installation ? ( + + ) : ( + + )} } @@ -173,15 +194,11 @@ const SESSION_END_SEARCH_PARAMS: Record = {}; * * This only sees changes this tab reads. Changes made in another tab, or by another staff user, are * left to the app token that comes with Permissions and auth. - * - * Ghost versions from before app sessions don't give installations a revision, so there's nothing - * to compare, and nothing is read. */ function useSessionEnd(session: AppSession, onEnded: () => void) { const [since] = useState(() => Date.now()); const started = session.installation.revision; const { data, dataUpdatedAt, isFetching } = useReadAppInstallation(session.installation.id, { - enabled: started !== undefined, defaultErrorHandler: false, // Without the history the details page shows; this one has no use for it. searchParams: SESSION_END_SEARCH_PARAMS, @@ -197,13 +214,7 @@ function useSessionEnd(session: AppSession, onEnded: () => void) { }); const revision = data?.app_installations[0]?.revision; useEffect(() => { - if ( - !isFetching && - dataUpdatedAt >= since && - started !== undefined && - revision !== undefined && - revision > started - ) { + if (!isFetching && dataUpdatedAt >= since && revision !== undefined && revision > started) { onEnded(); } }, [dataUpdatedAt, isFetching, onEnded, revision, started, since]); @@ -246,7 +257,7 @@ const AppFrame: React.FC<{ site: { url: site.url, title: site.title, timezone, locale: site.locale }, user: { id: user.id, role: user.roles[0]?.name ?? '' }, theme, - session: { revision: installation.revision ?? 0 }, + session: { revision: installation.revision }, path, }; // Read when the page connects, so the app starts with Admin's context at that moment. @@ -320,28 +331,30 @@ const AppFrame: React.FC<{ } return ( -
- {status === 'loading' && ( -
- -
- )} -