@ultimat3/cli 31.4.2 → 31.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CLAUDE.md +15 -7
  2. package/package.json +29 -29
  3. package/src/admin-catalog-keys.ts +17 -1
  4. package/src/app-boundaries.ts +3 -2
  5. package/src/app-transport.ts +7 -3
  6. package/src/asset-route-meta.ts +29 -0
  7. package/src/browser-barrel-cut.ts +109 -0
  8. package/src/browser-import-chain.ts +119 -0
  9. package/src/browser-transport.ts +85 -13
  10. package/src/cmd-dev.ts +15 -2
  11. package/src/cmd-drill.ts +39 -9
  12. package/src/cmd-fix.ts +14 -4
  13. package/src/cmd-i18n.ts +52 -10
  14. package/src/dev-boot.ts +6 -4
  15. package/src/dev-log.ts +95 -0
  16. package/src/dev-rebuild-remount.ts +152 -0
  17. package/src/dev-rebuild-schema.ts +30 -0
  18. package/src/dev-rebuild.ts +51 -14
  19. package/src/dev-supervisor.ts +5 -4
  20. package/src/error-codes.ts +2 -0
  21. package/src/error-contract.ts +29 -2
  22. package/src/favicon.ts +2 -1
  23. package/src/fix-sequence.ts +97 -0
  24. package/src/generate-grant-findings.ts +2 -2
  25. package/src/generate-grants.ts +50 -1
  26. package/src/generate-write.ts +16 -0
  27. package/src/i18n-registration.ts +8 -5
  28. package/src/island-routes.ts +2 -1
  29. package/src/load-findings.ts +29 -22
  30. package/src/mcp-errors.ts +11 -3
  31. package/src/mcp-host-shell.ts +128 -0
  32. package/src/mcp-host.ts +81 -55
  33. package/src/mcp-test-output.ts +5 -2
  34. package/src/messages-gate.ts +12 -0
  35. package/src/messages.ts +16 -0
  36. package/src/policy-append.ts +88 -0
  37. package/src/pwa-artifacts.ts +3 -3
  38. package/src/runtime-assets.ts +4 -1
  39. package/src/site-asset-routes.ts +2 -1
  40. package/src/style-routes.ts +2 -1
  41. package/src/templates/entity.ts +18 -3
  42. package/src/templates/guard-repo-raw-sql.ts +6 -3
  43. package/src/templates/policy.ts +5 -1
  44. package/src/templates/query.ts +4 -2
  45. package/src/templates/resource-service.ts +5 -2
  46. package/src/templates/scaffold-repo.ts +8 -2
  47. package/src/ts-scan.ts +86 -1
  48. package/src/verify-checks.ts +23 -51
  49. package/src/verify-contract-diff.ts +143 -0
  50. package/src/verify-seeds.ts +132 -0
  51. package/src/verify-tests.ts +12 -6
  52. package/src/worker-bundle.ts +2 -1
  53. package/wiki/CLI-Reference.md +2 -2
  54. package/wiki/Entities-And-Migrations.md +3 -3
  55. package/wiki/Interface-Rules.md +2 -2
  56. package/wiki/Project-Layout.md +3 -3
  57. package/wiki/Upgrading.md +7 -0
package/CLAUDE.md CHANGED
@@ -51,14 +51,17 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
51
51
  | `verify-floor.ts` | `x.verify.json`: a floor step that ran zero tests is `X_VERIFY_SUITE_VANISHED` |
52
52
  | `coverage-{floor,lcov,source}.ts` / `verify-coverage-run.ts` | an app's `unit` coverage floor; `coverage-lcov.ts` is the ONE lcov reader † |
53
53
  | `verify-deadline.ts` / `verify-stalled.ts` / `verify-progress.ts` | a step past its deadline is `X_VERIFY_STEP_TIMEOUT`; its children are killed by tag † |
54
- | `load-findings.ts` | module-load failures are reported once, by `manifest`; other steps point there |
54
+ | `load-findings.ts` | a module-load failure is reported once, by `manifest`; while red, each step that loads the app is wrapped in `blockedByLoad`: `skipped: load failed (see manifest)`. Under `--only` without `manifest` it carries the findings itself |
55
+ | `verify-contract-diff.ts` | `contract-diff`: baseline is `x.manifest.json` at HEAD; in CI, at the merge base with `origin/$GITHUB_BASE_REF`, or that ref itself when a shallow checkout reaches no merge base; HEAD plus a fetch notice when the ref is not fetched; outside git, the file on disk with a notice |
55
56
  | `verify-factories.ts` | `unit` lints `<app>/packages/db/factories.ts` (`X_TEST_FACTORY_INVALID`) |
57
+ | `verify-seeds.ts` | `unit` runs the seeds on one memory driver; a refused row keeps the entity's code and fix, an uncoded throw is `X_SEED_FAILED` |
56
58
  | `boundary-findings.ts` / `app-boundaries.ts` / `boundary-cuts.ts` / `package-boundaries.ts` | surface + layer rules, `X_BOUNDARY_PACKAGE_TO_APP`; a `fix:` is the concrete cut † |
57
59
  | `app-boundaries.ts` (workspaces) | `@<scope>/<app>/<rest>` resolves onto `apps/<app>/<rest>` when that is an app source, so the surface rules hold across app workspaces |
58
- | `app-transport.ts` / `browser-transport.ts` / `transport-calls.ts` / `transport-values.ts` / `binding-names.ts` / `import-closure.ts` / `server-barrels.ts` | `boundaries`, built in: one browser transport; never a `guards/` file † |
60
+ | `app-transport.ts` / `browser-transport.ts` / `transport-calls.ts` / `transport-values.ts` / `binding-names.ts` / `import-closure.ts` / `server-barrels.ts` / `browser-import-chain.ts` / `browser-barrel-cut.ts` | `boundaries`, built in: one browser transport; a server barrel below an island is cut at its first hop unless the browser entry exports every name taken (`meta.chain`; `x fix boundary` lists it, rule `browser-server-barrel`); never a `guards/` file † |
59
61
  | `guards.ts` / `guard-sources.ts` | an app's `guards/*.ts`, run on `boundaries`; ONE shared walk (`GuardSources`) † |
60
62
  | `templates/scaffold-guards.ts` | `SHIPPED`, the one list of shipped guards (`x new`, `x g guard`, `doctor-guards.ts`) † |
61
- | `error-contract.ts` / `ts-scan.ts` / `fix-scan.ts` / `fix-imports.ts` / `fix-command.ts` / `fix-path.ts` | the `errors` step: every `fix:` names a runnable command, call or existing file |
63
+ | `error-contract.ts` / `ts-scan.ts` / `fix-scan.ts` / `fix-imports.ts` / `fix-command.ts` / `fix-path.ts` | the `errors` step: every `fix:` names a runnable command, call or existing file; `*FIXES` tables are throw sites |
64
+ | `fix-sequence.ts` | `errors`: a `fix:` that defers its edit (`# after …`/`# once …`), only says re-run, or runs `x g … --force` is `X_ERROR_FIX_INVALID`; ratcheted per file (`FIX_SEQUENCE_BASELINE`) |
62
65
  | `workspace-checks.ts` / `test-only-shipped.ts` / `workspace-graph.ts` / `tsconfig-references.ts` / `publish-closure.ts` | `package-shape`, `filesize` ‡ |
63
66
  | `workspace-external-deps.ts` · `tsconfig-aliases.ts` · `error-codes-package.ts` | `package-shape`: a registry import neither the workspace nor the root declares (`X_WORKSPACE_EXTERNAL_DEP_UNDECLARED`); fix `bun add <pkg> --cwd <workspace>`. The step family's codes and titles, split out of `error-codes.ts` |
64
67
  | `app-permissions*.ts` / `permission-grants.ts` | `policy`: `X_PERMISSION_UNGRANTED`, `X_PERMISSION_BORROWED` † |
@@ -79,13 +82,13 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
79
82
  | `job-budget.ts` | `X_JOB_OUTLASTS_DRAIN` (`manifest`): `timeout` vs `workerBudgetMs(drain)`, from the registry † |
80
83
  | `output-findings.ts` | render layer only: `runnableFix` (`bunx x`, decided by `dispatch.ts`'s `readerFor`) and `collapseFindings`. Throw sites keep `x …` |
81
84
  | `app-load-unresolved.ts` | `X_APP_IMPORT_UNRESOLVED`, read by the scan, `findingFrom` and `x doctor`'s `snapshots` probe |
82
- | `fix-truth.test.ts` / `fix-truth-fixture.ts` / `db-fix-truth.job.test.ts` | a printed fix, executed: each row breaks a scaffold, asserts the code and runs the line |
85
+ | `fix-truth.test.ts` / `fix-truth-fixture.ts` / `db-fix-truth.job.test.ts` | a printed fix, executed: each row breaks a scaffold, asserts the code, runs the line; `typeErrors()` asserts the app still typechecks |
83
86
 
84
87
  ### Generators (`x g`, `x new`)
85
88
 
86
89
  | File | Job |
87
90
  |---|---|
88
- | `cmd-generate.ts` / `generate-files.ts` / `generate-kinds.ts` / `generate-write.ts` | argv → pure file list → writes (conflict-checked, `merge: 'json'` / `'if-absent'`) |
91
+ | `cmd-generate.ts` / `generate-files.ts` / `generate-kinds.ts` / `generate-write.ts` | argv → pure file list → writes (conflict-checked, `merge: 'json'` / `'if-absent'`, `policy.ts` appended) |
89
92
  | `templates/workspace.ts` | `x g app` / `x g package`: a workspace the root globs and the one tsconfig alias (`@<app>/*` → `packages/*/src`, then `apps/*`) already reach |
90
93
  | `write-generated.ts` | `x new`'s writer: a `link` file is a relative symlink, a copy only on a refusing win32 |
91
94
  | `generate-feature.ts` | a `--feature` naming no slice is `X_FEATURE_UNKNOWN`; nothing invents an entity |
@@ -93,7 +96,9 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
93
96
  | `generate-plural.ts` | a planned `entity.ts` in an already-plural slice (`posts` → `postses`) is `X_CLI_BAD_FLAG`; the fix names the singular |
94
97
  | `generate-catalog-locales.ts` | `--locales` never starts a catalog; missing locale is `X_CLI_BAD_FLAG` † |
95
98
  | `app-name.ts` | `x new`'s slug is asked of core's `defineConfig`, never a copied pattern; refused with a suggested name (`9lives` → `app-9lives`, `a` → `a-app`, cut at 64) |
96
- | `generate-grants.ts` | a written `policy.ts` or `entity.ts` declares and grants its permissions in `apps/web/shared/roles.ts` ‡ |
99
+ | `generate-grants.ts` | a written `policy.ts` grants the set the run wrote — its LAST `definePermissions([...])` (`:read` → member, else admin), never a permission already in the file; the slice path only when nothing reads; in `apps/web/shared/roles.ts` ‡ |
100
+ | `policy-append.ts` | a second `x g policy` appends its set; the same set again is the conflict, fix another set |
101
+ | `scaffold-growth.contract.test.ts` | an entity gaining a defaulted and a nullable column breaks no generated insert (`Insertable`) |
97
102
  | `api-registration.ts` | a written job or task is listed in `apps/web/api/index.ts` |
98
103
  | `generate-exercise.ts` | a contract test's entry in `apps/web/exercise.ts` (`exercise-entry-edit.ts`) |
99
104
  | `handle-registration.ts` / `workspace-dep-edit.ts` / `templates/scaffold-db-client.ts` | a written entity joins `entities` (`X_DB_HANDLE_UNREGISTERED`) † |
@@ -116,6 +121,8 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
116
121
  | `generate-refresh.ts` | `x g` refreshes the manifest only when a written file needs it |
117
122
  | `role-load.ts` / `document-graph.ts` / `serve-web.ts` | a role imports what it runs: `ROLE_LOADS` (`X_ROLE_LOAD_INCOMPLETE`) † |
118
123
  | `module-imports.ts` | a module's imports, resolved once for both graphs: `referenced` (reload), `evaluated` (document) |
124
+ | `dev-rebuild-remount.ts` / `dev-rebuild-schema.ts` | a save that changes what `x dev` mounted or its load findings is a restart, naming what moved; entities ahead of migrations are `X_DB_DRIFT` (`x db gen "…" && x db migrate`), skipped after a failed load |
125
+ | `dev-log.ts` | every logger line to `<stateDir>/dev.log` (`logs.tail`); `dev.log.1` at 16 MiB |
119
126
  | `cmd-dev.ts` / `dev-boot.ts` / `dev-rebuild.ts` / `dev-route-table.ts` | `x dev`: every role in one process, `/_x`, the watcher; one save = one generation, and the boot is the first: `buildGeneration` builds the manifest and the islands at once † |
120
127
  | `runtime-bindings.ts` | which service each binding points at (embedded or external); events follow `NATS_URL` |
121
128
  | `runtime-queue.ts` / `runtime-services.ts` / `runtime-bus.ts` | db + queue; every other accessor; the bus |
@@ -132,6 +139,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
132
139
  | `role-wake.ts` | the worker's LISTEN session (`@ultimat3/jobs`' `startQueueWake`) — worker role only, only over a client that `canListen` — and `queue_wake_live` |
133
140
  | `role-sync.ts` / `role-replicator.ts` / `runtime-live-feed.ts` | the sync node, the change feed |
134
141
  | `runtime-render*.ts` / `runtime-{isr-outcome,assets,storage,hooks}.ts` / `route-islands.ts` / `api-routes.ts` | the HTTP surface both boots mount † |
142
+ | `asset-route-meta.ts` | the ONE writer of an asset route's `tags: ['assets']` + `rateLimit: 'assets'`; the test walks `examples/dummy`'s built table and refuses an `assets.*` route on `default` |
135
143
  | `client-{errors,vitals}-*.ts` | `clientErrors` (and `.vitals`): the script on `app/` (vitals: listed) documents, its `POST` route, mounted by BOTH boots ‡ |
136
144
  | `retained-assets.ts` / `-layout.ts` / `-sweep.ts` / `-read.ts` / `-boot.ts` | `assets.retain`: the web boot publishes this build's hashed files before `/readyz` † |
137
145
  | `runtime-overrides.ts` / `runtime-ports.ts` / `runtime-port-bindings.ts` | `runtime.ts`: a field per `ADAPTER_PORTS` row, installed by ONE loop or read where used; unbound row = build error. Plus `routes`. `docs/history/cli-adapter-ports.md` |
@@ -166,7 +174,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
166
174
  |---|---|
167
175
  | `cmd-registries.ts` / `cmd-jobs.ts` / `cmd-tasks.ts` / `cmd-policy.ts` / `cmd-i18n.ts` | project a framework registry; each pairs CLI wiring with a facts module |
168
176
  | `cmd-auth.ts` / `cmd-auth-spec.ts` / `doctor-auth.ts` | `x auth seal-mfa`: seals plaintext `x_users.mfa_secret` through auth's `sealMfaSecrets` |
169
- | `cmd-mcp.ts` / `mcp-host.ts` / `mcp-errors.ts` / `mcp-db-target.ts` | `x mcp serve`: 19 tools, two transports † |
177
+ | `cmd-mcp.ts` / `mcp-host.ts` / `mcp-errors.ts` / `mcp-db-target.ts` / `mcp-host-shell.ts` / `mcp-test-{output,run}.ts` | `x mcp serve`: 19 tools, two transports; `tests.run`/`verify.run` ARE `x test`/`x verify`, `ULTIMATE_ENV` unset in children (`mcp-host.parity.test.ts`) † |
170
178
  | `cmd-shot*.ts` / `cdp-shot-*.ts` / `browser-launcher*.ts` / `island-*` | `x shot` over raw CDP; `verdict.json` names its own blind spots. Not a gate step |
171
179
  | `shot-route.ts` / `shot-run.ts` / `shot-gpu.ts` | `x shot`'s route argument (`readRoute`, `shotSlug`); one capture (`runShot`); the page's `navigator.gpu` adapter (`verdict.gpu`, never gating). `cmd-shot.ts` re-exports the first two |
172
180
  | `cmd-pr.ts` / `cmd-ci.ts` / `ci-runs.ts` / `ci-tested.ts` | GitHub through `gh`, schema-parsed; not gate steps † |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.4.2",
3
+ "version": "31.6.0",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.0.9",
56
- "@ultimat3/action": "31.4.2",
57
- "@ultimat3/admin": "31.4.2",
58
- "@ultimat3/ai": "31.4.2",
59
- "@ultimat3/auth": "31.4.2",
60
- "@ultimat3/cache": "31.4.2",
61
- "@ultimat3/core": "31.4.2",
62
- "@ultimat3/db": "31.4.2",
63
- "@ultimat3/entity": "31.4.2",
64
- "@ultimat3/flags": "31.4.2",
65
- "@ultimat3/http": "31.4.2",
66
- "@ultimat3/i18n": "31.4.2",
67
- "@ultimat3/jobs": "31.4.2",
68
- "@ultimat3/mail": "31.4.2",
69
- "@ultimat3/manifest": "31.4.2",
70
- "@ultimat3/mcp": "31.4.2",
71
- "@ultimat3/money": "31.4.2",
72
- "@ultimat3/notify": "31.4.2",
73
- "@ultimat3/policy": "31.4.2",
74
- "@ultimat3/pwa": "31.4.2",
75
- "@ultimat3/query": "31.4.2",
76
- "@ultimat3/realtime": "31.4.2",
77
- "@ultimat3/render": "31.4.2",
78
- "@ultimat3/schema": "31.4.2",
79
- "@ultimat3/scraping": "31.4.2",
80
- "@ultimat3/seo": "31.4.2",
81
- "@ultimat3/storage": "31.4.2",
82
- "@ultimat3/testing": "31.4.2",
83
- "@ultimat3/time": "31.4.2",
56
+ "@ultimat3/action": "31.6.0",
57
+ "@ultimat3/admin": "31.6.0",
58
+ "@ultimat3/ai": "31.6.0",
59
+ "@ultimat3/auth": "31.6.0",
60
+ "@ultimat3/cache": "31.6.0",
61
+ "@ultimat3/core": "31.6.0",
62
+ "@ultimat3/db": "31.6.0",
63
+ "@ultimat3/entity": "31.6.0",
64
+ "@ultimat3/flags": "31.6.0",
65
+ "@ultimat3/http": "31.6.0",
66
+ "@ultimat3/i18n": "31.6.0",
67
+ "@ultimat3/jobs": "31.6.0",
68
+ "@ultimat3/mail": "31.6.0",
69
+ "@ultimat3/manifest": "31.6.0",
70
+ "@ultimat3/mcp": "31.6.0",
71
+ "@ultimat3/money": "31.6.0",
72
+ "@ultimat3/notify": "31.6.0",
73
+ "@ultimat3/policy": "31.6.0",
74
+ "@ultimat3/pwa": "31.6.0",
75
+ "@ultimat3/query": "31.6.0",
76
+ "@ultimat3/realtime": "31.6.0",
77
+ "@ultimat3/render": "31.6.0",
78
+ "@ultimat3/schema": "31.6.0",
79
+ "@ultimat3/scraping": "31.6.0",
80
+ "@ultimat3/seo": "31.6.0",
81
+ "@ultimat3/storage": "31.6.0",
82
+ "@ultimat3/testing": "31.6.0",
83
+ "@ultimat3/time": "31.6.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -1,8 +1,10 @@
1
1
  // The catalog keys a MOUNTED admin renders: asked of each `AdminApp` (`catalogKeys()`), never
2
2
  // walked here — the admin owns the one derivation, so a key `defineAdmin` would draw and the
3
- // `i18n` step audits can never be two spellings of one rule.
3
+ // `i18n` step audits can never be two spellings of one rule. Also the label `x i18n sync` writes
4
+ // for one, by the rule `x g resource --admin` already labels its own keys with.
4
5
 
5
6
  import { describePages } from '@ultimat3/render';
7
+ import { columnLabel } from './templates/admin-catalog';
6
8
 
7
9
  /**
8
10
  * The keys of every admin this process declared. Asked of the route table first: an app with no
@@ -14,3 +16,17 @@ export async function mountedAdminKeys(): Promise<readonly string[]> {
14
16
  const { adminMounts } = await import('@ultimat3/admin');
15
17
  return [...new Set(adminMounts().flatMap((app) => app.catalogKeys()))].sort();
16
18
  }
19
+
20
+ /** Segments that name the slot a string fills, not the thing it labels: `admin.posts.title`. */
21
+ const SLOT_SEGMENTS = new Set(['title', 'label']);
22
+
23
+ /**
24
+ * `admin.posts.field.createdAt` → `Created at`, `admin.posts.title` → `Posts`: the label the
25
+ * generator writes for a key it derives (`adminCatalogEntries`), read back off the key itself so a
26
+ * key the generator never wrote — a section, a scope, an action — gets the same treatment.
27
+ */
28
+ export function adminKeyLabel(key: string): string {
29
+ const segments = key.split('.');
30
+ while (segments.length > 1 && SLOT_SEGMENTS.has(segments.at(-1) ?? '')) segments.pop();
31
+ return columnLabel(segments.at(-1) ?? key);
32
+ }
@@ -72,10 +72,11 @@ const isService = (path: string): boolean => /\/service\.[cm]?ts$/.test(path);
72
72
  * query that carries the read's policy, bound and cache tag — the scaffold's own dashboard showed
73
73
  * every post to a viewer holding `dashboard:read` alone. Matched as a whole module name, resolved
74
74
  * (`…/repo.ts`), NodeNext-spelled (`./repo.js`, `.mjs`, `.cjs`) or bare (`../post/repo`), so
75
- * `report` and `repository` are names, not repos.
75
+ * `report` and `repository` are names, not repos. A `repo-<part>` module is the same repo split at
76
+ * the file ceiling (`repo-window.ts`): without it the split was a door around this rule.
76
77
  */
77
78
  const isRepoSpecifier = (specifier: string): boolean =>
78
- /(^|\/)repo(\/index)?(\.[cm]?[jt]sx?)?$/.test(specifier);
79
+ /(^|\/)repo(-[a-z0-9]+)*(\/index)?(\.[cm]?[jt]sx?)?$/.test(specifier);
79
80
  const isDbSpecifier = (specifier: string): boolean =>
80
81
  /(^|\/)packages\/db($|\/)/.test(specifier) ||
81
82
  specifier.endsWith('/db') ||
@@ -17,6 +17,7 @@ import { readFileSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
18
  import { isJsonObject } from '@ultimat3/core';
19
19
  import type { SourceFile } from './app-boundaries';
20
+ import { mergeBarrelFindings, publishedEntries } from './browser-barrel-cut';
20
21
  import type { FindingContext } from './browser-transport';
21
22
  import {
22
23
  barrelFinding,
@@ -200,13 +201,16 @@ export async function appTransportFindings(
200
201
  workspaces(root),
201
202
  installedSpecifiers(root),
202
203
  ]);
203
- const published = [...installed, ...own.patterns.filter((p) => !p.wild).map((p) => p.head)];
204
+ const specifiers = [...installed, ...own.patterns.filter((p) => !p.wild).map((p) => p.head)];
205
+ const barrelMap = serverBarrels(specifiers);
204
206
  const { bypasses, barrels } = checkBrowserTransport({
205
207
  entries,
206
208
  // The tsconfig first: it is what the app's own typecheck resolves through.
207
209
  host: hostOf(root, sources, [...paths, ...own.patterns]),
208
210
  seams: new Map(),
209
- barrels: serverBarrels(published),
211
+ barrels: barrelMap,
212
+ // What each browser entry exports: a swap is printed only where it compiles.
213
+ published: await publishedEntries(root, barrelMap.values()),
210
214
  ownsBarrel: (file, barrel) => {
211
215
  const dir = own.dirs.get(barrel);
212
216
  return dir !== undefined && file.startsWith(`${dir}/`);
@@ -214,6 +218,6 @@ export async function appTransportFindings(
214
218
  });
215
219
  return [
216
220
  ...bypasses.map((bypass) => bypassFinding(bypass, CONTEXT)),
217
- ...barrels.map((barrel) => barrelFinding(barrel, CONTEXT)),
221
+ ...mergeBarrelFindings(barrels.map((barrel) => barrelFinding(barrel, CONTEXT))),
218
222
  ];
219
223
  }
@@ -0,0 +1,29 @@
1
+ // The one place an asset route's tag and rate-limit bucket are written. Every route serving built
2
+ // bytes (chunks, stylesheets, icons, site files, framework scripts) spends `assets`, not `default`:
3
+ // one page load is dozens of content-hashed GETs, and `default`'s 120 burst at 2/s answered 429 to
4
+ // an office behind one NAT from the fifth route on.
5
+
6
+ import type { RouteMeta } from '@ultimat3/http';
7
+
8
+ /** The tag `withRetainedAssets` and the manifest read to know a route serves built bytes. */
9
+ export const ASSET_ROUTE_TAG = 'assets';
10
+
11
+ /** The bucket in `@ultimat3/http`'s `DEFAULT_RATE_LIMIT` an asset route spends. */
12
+ export const ASSET_RATE_LIMIT_BUCKET = 'assets';
13
+
14
+ /** What an asset route declares itself; the tag and the bucket are this function's to write. */
15
+ export type AssetRouteDeclaration = Omit<
16
+ RouteMeta,
17
+ 'tags' | 'rateLimit' | 'rateLimitBucket' | 'rateLimitedBy'
18
+ >;
19
+
20
+ /**
21
+ * A route meta with `tags: ['assets']` and `rateLimit: 'assets'` written for it. Not optional per
22
+ * route: `asset-route-meta.test.ts` walks the reference app's built table and refuses any
23
+ * `assets.*` route whose meta did not come through here.
24
+ */
25
+ export const assetRouteMeta = (meta: AssetRouteDeclaration): RouteMeta => ({
26
+ ...meta,
27
+ tags: [ASSET_ROUTE_TAG],
28
+ rateLimit: ASSET_RATE_LIMIT_BUCKET,
29
+ });
@@ -0,0 +1,109 @@
1
+ // The browser graph's cuts over an app on disk: what each browser entry really exports (read from
2
+ // the installed manifest, so a promised swap compiles), one `X_BROWSER_SERVER_BARREL` per edge to
3
+ // delete, and the cut as `x fix boundary` prints it. The `boundaries` step (`app-transport.ts`) and
4
+ // `x fix boundary` both read from here, so the gate and the command cannot disagree.
5
+
6
+ // why: Bun ships no path joiner; the manifest and the entry are read at a joined path.
7
+ import { join } from 'node:path';
8
+ import { isJsonObject } from '@ultimat3/core';
9
+ import { exportedNames } from './browser-import-chain';
10
+ import type { Finding, JsonValue } from './output';
11
+
12
+ const CODE = 'X_BROWSER_SERVER_BARREL';
13
+
14
+ /** What `@scope/pkg/sub` exports, read through the app's `node_modules`; `undefined` = unknown. */
15
+ export async function publishedNames(
16
+ root: string,
17
+ spec: string,
18
+ ): Promise<ReadonlySet<string> | undefined> {
19
+ const match = /^(@[\w.-]+\/[\w.-]+)\/([\w.-]+)$/.exec(spec);
20
+ if (match === null) return undefined;
21
+ const dir = join(root, 'node_modules', match[1] ?? '');
22
+ try {
23
+ const manifest: unknown = await Bun.file(join(dir, 'package.json')).json();
24
+ const exports = isJsonObject(manifest) ? manifest['exports'] : undefined;
25
+ const row = isJsonObject(exports) ? exports[`./${match[2]}`] : undefined;
26
+ const target = isJsonObject(row) ? (row['import'] ?? row['default']) : row;
27
+ if (typeof target !== 'string') return undefined;
28
+ return exportedNames(await Bun.file(join(dir, target)).text());
29
+ } catch {
30
+ return undefined;
31
+ }
32
+ }
33
+
34
+ const strings = (value: JsonValue | undefined): readonly string[] | undefined =>
35
+ Array.isArray(value) && value.every((one) => typeof one === 'string')
36
+ ? (value as readonly string[])
37
+ : undefined;
38
+
39
+ /** One finding per edit: every site one cut clears is listed on it, never printed again. */
40
+ export function mergeBarrelFindings(findings: readonly Finding[]): readonly Finding[] {
41
+ const byEdit = new Map<string, Finding>();
42
+ const out: Finding[] = [];
43
+ for (const finding of findings) {
44
+ const key = `${finding.at ?? ''}\u0000${finding.fix}`;
45
+ const held = byEdit.get(key);
46
+ if (finding.code !== CODE || held === undefined) {
47
+ if (finding.code === CODE) byEdit.set(key, finding);
48
+ out.push(finding);
49
+ continue;
50
+ }
51
+ const sites = [...(strings(held.meta?.['sites']) ?? [])];
52
+ for (const one of strings(finding.meta?.['sites']) ?? [])
53
+ if (!sites.includes(one)) sites.push(one);
54
+ const grown: Finding = { ...held, meta: { ...held.meta, sites } };
55
+ byEdit.set(key, grown);
56
+ out[out.indexOf(held)] = grown;
57
+ }
58
+ return out.map((finding) => {
59
+ const sites = strings(finding.meta?.['sites']) ?? [];
60
+ return finding.code === CODE && sites.length > 1
61
+ ? {
62
+ ...finding,
63
+ cause: `${finding.cause}; the same edge also reaches ${sites.slice(1).join(', ')}`,
64
+ }
65
+ : finding;
66
+ });
67
+ }
68
+
69
+ /** Every browser entry's export names that could be read; an entry left out is unknown. */
70
+ export async function publishedEntries(
71
+ root: string,
72
+ entries: Iterable<string>,
73
+ ): Promise<ReadonlyMap<string, ReadonlySet<string>>> {
74
+ const read = await Promise.all(
75
+ [...new Set(entries)].map(async (entry) => [entry, await publishedNames(root, entry)] as const),
76
+ );
77
+ return new Map(read.flatMap(([entry, names]) => (names === undefined ? [] : [[entry, names]])));
78
+ }
79
+
80
+ /** The browser-graph findings `x fix boundary <target>` owns: its island, or any file on the chain. */
81
+ export const involvesTarget = (finding: Finding, target: string): boolean =>
82
+ finding.code === CODE &&
83
+ (finding.at?.split(':')[0] === target ||
84
+ (strings(finding.meta?.['chain']) ?? []).includes(target));
85
+
86
+ /**
87
+ * A browser-graph cut as `x fix boundary`'s `data.cuts` carries a surface one: the edge is the
88
+ * entry's first hop for a cut, the barrel import itself for a swap.
89
+ */
90
+ export function browserCutJson(finding: Finding): JsonValue {
91
+ const meta = finding.meta ?? {};
92
+ const chain = strings(meta['chain']) ?? [];
93
+ const [site = ''] = strings(meta['sites']) ?? [];
94
+ const entry = chain[0] ?? '';
95
+ const edge =
96
+ meta['cut'] === 'entry'
97
+ ? { from: entry, to: chain[1] ?? '' }
98
+ : { from: site.replace(/:\d+$/, ''), to: String(meta['barrel'] ?? '') };
99
+ return {
100
+ code: finding.code,
101
+ rule: 'browser-server-barrel',
102
+ entry,
103
+ at: finding.at ?? '',
104
+ edge,
105
+ chain: [...chain],
106
+ edit: finding.fix,
107
+ split: null,
108
+ };
109
+ }
@@ -0,0 +1,119 @@
1
+ // The browser-graph half of `x fix boundary`, pure: HOW an entry (an island) reaches a module, and
2
+ // WHAT a module takes from a barrel. A server barrel found three hops below an island is the
3
+ // island's mistake when the module importing it is server code — the edge to cut is the entry's
4
+ // first hop, and only the chain says which one that is.
5
+
6
+ import { stripComments } from '@ultimat3/core';
7
+ import type { ClosureHost } from './import-closure';
8
+ import { parseModule, resolveSpec } from './import-closure';
9
+ import { lineIndex } from './ts-scan';
10
+
11
+ /** The path an entry takes to a module, and the import in the entry that starts it. */
12
+ export interface ImportChain {
13
+ /** Entry first, the module last; `[module]` when the module is the entry. */
14
+ readonly chain: readonly string[];
15
+ /** The entry's specifier for `chain[1]` and the line it is written on; absent for `[module]`. */
16
+ readonly hop?: { readonly spec: string; readonly line: number };
17
+ }
18
+
19
+ /** Every specifier a module's text can load: value imports, side effects, re-exports, stars. */
20
+ const specifiersOf = (source: string): readonly string[] => {
21
+ const shape = parseModule(source);
22
+ return [
23
+ ...shape.imports.map((one) => one.spec),
24
+ ...shape.effects,
25
+ ...shape.reexports.map((one) => one.spec),
26
+ ...shape.stars,
27
+ ];
28
+ };
29
+
30
+ /** The 1-based line of the first import or re-export in `source` that names `spec`. */
31
+ export function specLine(source: string, spec: string): number {
32
+ const code = stripComments(source);
33
+ const quoted = [`'${spec}'`, `"${spec}"`].map((one) => code.indexOf(one)).filter((at) => at >= 0);
34
+ return quoted.length === 0 ? 1 : lineIndex(code)(Math.min(...quoted));
35
+ }
36
+
37
+ /** Breadth first, so the chain printed is the shortest — the one a reader can follow by eye. */
38
+ export function importChain(
39
+ host: ClosureHost,
40
+ entry: string,
41
+ target: string,
42
+ ): ImportChain | undefined {
43
+ if (entry === target) return { chain: [target] };
44
+ const parent = new Map<string, { readonly from: string; readonly spec: string }>();
45
+ const queue = [entry];
46
+ const seen = new Set(queue);
47
+ for (let at = queue.shift(); at !== undefined; at = queue.shift()) {
48
+ for (const spec of specifiersOf(host.read(at) ?? '')) {
49
+ const next = resolveSpec(host, at, spec);
50
+ if (next === undefined || seen.has(next)) continue;
51
+ seen.add(next);
52
+ parent.set(next, { from: at, spec });
53
+ if (next === target) return chainTo(host, parent, entry, target);
54
+ queue.push(next);
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ function chainTo(
61
+ host: ClosureHost,
62
+ parent: ReadonlyMap<string, { readonly from: string; readonly spec: string }>,
63
+ entry: string,
64
+ target: string,
65
+ ): ImportChain {
66
+ const chain = [target];
67
+ let spec = '';
68
+ for (let step = parent.get(target); step !== undefined; step = parent.get(step.from)) {
69
+ chain.unshift(step.from);
70
+ spec = step.spec;
71
+ }
72
+ return { chain, hop: { spec, line: specLine(host.read(entry) ?? '', spec) } };
73
+ }
74
+
75
+ /**
76
+ * The value names `source` takes from `spec`, or `'*'` when it takes the whole module (a namespace,
77
+ * a side-effect import, a dynamic `import()`, an `export *`) — which no browser entry can promise.
78
+ */
79
+ export function namesFrom(source: string, spec: string): readonly string[] | '*' {
80
+ const shape = parseModule(source);
81
+ if (shape.effects.includes(spec) || shape.stars.includes(spec)) return '*';
82
+ const names = new Set<string>();
83
+ for (const one of shape.imports) {
84
+ if (one.spec !== spec) continue;
85
+ if (one.names === '*') return '*';
86
+ for (const name of one.names) names.add(name);
87
+ }
88
+ for (const one of shape.reexports) {
89
+ if (one.spec === spec) for (const name of one.map.values()) names.add(name);
90
+ }
91
+ return [...names].sort();
92
+ }
93
+
94
+ const DECLARED =
95
+ /\bexport\s+(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class|abstract\s+class|enum|type|interface|namespace)\s+([\w$]+)/g;
96
+ const LISTED = /\bexport\s+(?:type\s+)?\{([^}]*)\}/g;
97
+
98
+ /**
99
+ * Every name a module exports, types included, or `undefined` when an `export *` makes the list
100
+ * unknowable from its own text — the caller then cannot promise a swap is safe.
101
+ */
102
+ export function exportedNames(source: string): ReadonlySet<string> | undefined {
103
+ const code = stripComments(source);
104
+ if (/\bexport\s+\*/.test(code)) return undefined;
105
+ const names = new Set<string>();
106
+ for (const found of code.matchAll(DECLARED)) names.add(found[1] ?? '');
107
+ for (const found of code.matchAll(LISTED)) {
108
+ for (const part of (found[1] ?? '').split(',')) {
109
+ const name = part
110
+ .trim()
111
+ .replace(/^type\s+/, '')
112
+ .split(/\s+as\s+/)
113
+ .at(-1)
114
+ ?.trim();
115
+ if (name !== undefined && name !== '') names.add(name);
116
+ }
117
+ }
118
+ return names;
119
+ }