Skip to main content

bynk_std/
lib.rs

1//! The Bynk standard library's first-party sources, as data.
2//!
3//! The `bynk` conformance surface, the Bynk-written commons (`bynk.list`,
4//! `bynk.map`, `bynk.string`, `bynk.locale`, `bynk.locale.types`) and the
5//! `bynk.cloudflare` platform adapter ship with the compiler rather than being
6//! authored by the user. This crate holds their `.bynk` sources, their
7//! per-platform TypeScript bindings and the metadata the toolchain reads about
8//! them, embedded with `include_str!`. It holds no logic: `bynk-check` parses and
9//! injects these sources when a project `uses` or `consumes` them, and provides
10//! each binding for the selected [`Platform`]. The `bynk` root namespace is
11//! reserved (`bynk.namespace.reserved`) so user code can never collide with it.
12//!
13//! The sources live under `lib/`: the portable layers in `lib/core/` (with the
14//! `bynk` surface's bindings in `lib/core/bindings/`) and the platform adapter in
15//! `lib/cloudflare/`. Nothing in `lib/core/` depends on `lib/cloudflare/`, so the
16//! platform layer can be split out later without renaming a unit.
17
18/// The deploy platform — a selection axis distinct from the `--target
19/// {bundle,workers}` emit mode (§6.2). It chooses which `bynk-<platform>.ts`
20/// binding is linked for the `bynk` surface. v0.17 shipped `cloudflare`;
21/// v0.18 adds `node`, making the axis observable (and giving v0.19's
22/// platform-lock enforcement a second platform to fire against).
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
24pub enum Platform {
25    #[default]
26    Cloudflare,
27    Node,
28    /// The browser (in-browser track, slice 1 — the REPL/playground host). A
29    /// Tier-3 binding exposing the `bynk` surface over Web APIs, composed with
30    /// `BuildTarget::Bundle` only (a browser cannot do the Workers wire model).
31    Browser,
32}
33
34impl Platform {
35    /// The output filename of this platform's `bynk` binding module.
36    pub fn bynk_binding_filename(self) -> &'static str {
37        match self {
38            Platform::Cloudflare => "bynk-cloudflare.ts",
39            Platform::Node => "bynk-node.ts",
40            Platform::Browser => "bynk-browser.ts",
41        }
42    }
43
44    /// The TypeScript source of this platform's `bynk` binding.
45    pub fn bynk_binding_source(self) -> &'static str {
46        match self {
47            Platform::Cloudflare => BYNK_CLOUDFLARE_BINDING,
48            Platform::Node => BYNK_NODE_BINDING,
49            Platform::Browser => BYNK_BROWSER_BINDING,
50        }
51    }
52
53    /// The platform's stable name (for the `--platform` flag and diagnostics).
54    pub fn as_str(self) -> &'static str {
55        match self {
56            Platform::Cloudflare => "cloudflare",
57            Platform::Node => "node",
58            Platform::Browser => "browser",
59        }
60    }
61}
62
63/// The unit name of the reserved first-party surface adapter.
64pub const BYNK_UNIT: &str = "bynk";
65
66/// The capabilities the env-free `bynk` surface exports (its `exports
67/// capability { … }` line in `bynk.bynk`). First-party symbols live on
68/// synthetic files and are excluded from the binding index, so the
69/// unknown-name quick-fix (#852) offering `consumes bynk { … }` needs this
70/// explicit list. Kept in sync with the adapter source by
71/// `bynk_surface_capabilities_match_the_adapter`.
72pub const BYNK_SURFACE_CAPABILITIES: &[&str] = &[
73    "Clock",
74    "Random",
75    "Logger",
76    "Fetch",
77    "Secrets",
78    "Locale",
79    "Idempotency",
80    "Events",
81];
82
83/// The unit name of the first-party Cloudflare platform adapter (v0.19,
84/// decision 0026): inside the reserved `bynk.*` prefix, so no separate
85/// reservation rule is needed. The surface unit `bynk` stays the portability
86/// marker; `bynk.<platform>` units are the platform-locked ones.
87pub const CLOUDFLARE_UNIT: &str = "bynk.cloudflare";
88
89/// The fixed Worker binding name for the Kv namespace (decision C1, v0.19):
90/// one namespace, one `[[kv_namespaces]]` stanza, one `env.KV` field.
91pub const KV_BINDING_NAME: &str = "KV";
92
93/// v0.18 decision 0021 / v0.19 decision 0025: which first-party provider
94/// classes take the Worker `env` as a constructor argument, keyed by
95/// (unit, provider class). `SecretsProvider` accepts an optional env with a
96/// `globalThis` probe fallback; `WorkersKv` *requires* env on use — KV
97/// namespaces exist only on the Worker `env`, never on `globalThis`.
98///
99/// A view over [`UNITS`]: each entry's [`Unit::env_providers`].
100pub fn provider_takes_env(unit: &str, provider: &str) -> bool {
101    self::unit(unit).is_some_and(|u| u.env_providers.contains(&provider))
102}
103
104/// v0.19 decision 0024: which first-party units are **platform-native** —
105/// consuming one locks its deployment unit to the returned platform. This is
106/// the metadata that drives effective-platform computation, `env` resource
107/// typing, and `wrangler.toml` stanza derivation; no user-facing marker
108/// syntax exists (additive later, when third-party platform adapters become
109/// a goal).
110///
111/// A view over [`UNITS`]: each entry's [`Unit::platform`].
112pub fn platform_of(unit: &str) -> Option<Platform> {
113    self::unit(unit).and_then(|u| u.platform)
114}
115
116/// The unit names of the first-party collection commons (v0.20b): the
117/// Bynk-written combinator stdlib over the built-in `List`/`Map` kernel.
118/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported.
119pub const LIST_UNIT: &str = "bynk.list";
120pub const MAP_UNIT: &str = "bynk.map";
121
122/// `bynk.list` — combinators over the `List` kernel (`fold`, `prepend`,
123/// `length`, `get`, `foldEff`), written in ordinary Bynk (decision 0034):
124/// the first real consumer of v0.20a generics, lambdas, and effectful
125/// traversal. Order-preserving combinators build with `fold` + `prepend`
126/// and a final `reverse` — O(n) builds, never `append` (which would be
127/// O(n²) over the array lowering).
128pub const BYNK_LIST_SRC: &str = include_str!("../lib/core/bynk.list.bynk");
129
130/// `bynk.map` — combinators over the `Map` kernel (`empty`, `insert`, `get`,
131/// `keys`, `length`). `fromList` is deliberately absent: Bynk has no pair
132/// type to spell a `List[(K, V)]` with, so map construction is `Map.empty()`
133/// + `insert` (revisit with tuples or generic records).
134pub const BYNK_MAP_SRC: &str = include_str!("../lib/core/bynk.map.bynk");
135
136/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported.
137pub const STRING_UNIT: &str = "bynk.string";
138
139/// `bynk.string` — Bynk-written helpers over the v0.22a string kernel
140/// (`concat`, the `List` `fold`, and the `Option` kernel methods). The
141/// kernel itself is compiler built-in (ADR 0046); only derived helpers
142/// live here. `join` folds to `Option[String]` so empty-string *elements*
143/// are joined faithfully (a bare `""` accumulator could not tell "nothing
144/// yet" from "first element was empty").
145pub const BYNK_STRING_SRC: &str = include_str!("../lib/core/bynk.string.bynk");
146
147/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported by
148/// application code (a message-bundle commons, ADR 0272) — never directly by
149/// the `bynk` adapter itself any more (see [`LOCALE_TYPES_UNIT`]).
150pub const LOCALE_UNIT: &str = "bynk.locale";
151
152/// `bynk.locale` — the bundle-free `render`/`renderArg` helpers and the
153/// `message`/`withText`/`withWhole`/`withNum`/`withMoment` builder API
154/// (slice 1: `render` formats `code` plus a deterministic sorted-by-key
155/// rendering of `params`; no lookup, no locale-dependent behaviour). `uses
156/// bynk.locale.types` for the types its own signatures name.
157pub const BYNK_LOCALE_SRC: &str = include_str!("../lib/core/bynk.locale.bynk");
158
159/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported. Also
160/// `uses`-imported by the `bynk` adapter itself, to give `capability Locale`'s
161/// `current() -> Effect[LocaleTag]` a type to name (an adapter may `uses` a
162/// commons; a commons cannot in turn reference an adapter). Split out of
163/// `bynk.locale` (locale-negotiation-slice-2 follow-up, #886) specifically so
164/// a context can reach `LocaleTag` without also pulling in `bynk.locale`'s
165/// own `render` — which previously collided with a message-bundle commons's
166/// own synthesised `render` (ADR 0272) the moment a context needed both.
167pub const LOCALE_TYPES_UNIT: &str = "bynk.locale.types";
168
169/// `bynk.locale.types` — `LocaleTag`, `MessageArg`, `Message`: a
170/// dependency-free leaf (no `uses` of its own) so any consumer, including
171/// the `bynk` adapter itself, can reach these types without also reaching
172/// `bynk.locale`'s value-level API.
173pub const BYNK_LOCALE_TYPES_SRC: &str = include_str!("../lib/core/bynk.locale.types.bynk");
174
175/// The reserved `bynk` conformance-surface adapter (env-free core). It has no
176/// `binding` clause — the toolchain supplies one per platform (see
177/// [`Platform::bynk_binding_source`]).
178pub const BYNK_ADAPTER_SRC: &str = include_str!("../lib/core/bynk.bynk");
179
180/// The Cloudflare binding for the `bynk` surface. Implements the canonical
181/// provider symbols against the platform host API. The refined `Uuid` is built
182/// through its emitted validating `.of` constructor (§4.4), treating the
183/// unreachable `Err` as a bug rather than trusting the value away.
184const BYNK_CLOUDFLARE_BINDING: &str = include_str!("../lib/core/bindings/bynk-cloudflare.ts");
185
186/// The Node (≥ the toolchain's `NODE_MAJOR_FLOOR`, in `bynk-emit`) binding for
187/// the `bynk` surface (v0.18). Deliberately
188/// near-identical to the cloudflare binding: `Date.now`, the global
189/// `crypto`/`fetch`, and `console` are the same host API on both runtimes —
190/// which is exactly the ambient-surface portability claim (spec §4.2). The
191/// `SecretsProvider` reads `process.env` through the same `globalThis` probe
192/// (never bare `process`, which would demand @types/node at the tsc gate).
193const BYNK_NODE_BINDING: &str = include_str!("../lib/core/bindings/bynk-node.ts");
194
195/// The Browser binding for the `bynk` surface (in-browser track, slice 1). Tier-3:
196/// the same capability surface over Web APIs. `Clock`/`Random`/`Logger` are
197/// byte-identical to the Node binding (`Date.now`, Web Crypto `crypto.randomUUID`,
198/// `console` — all Web standards); the two substitutions are the playground safety
199/// boundary — `Fetch` is **withheld** (throws; no outbound egress from the
200/// playground origin) and `Secrets` is **unavailable** (throws; a browser has no
201/// secret store), both failing loudly rather than silently degrading.
202const BYNK_BROWSER_BINDING: &str = include_str!("../lib/core/bindings/bynk-browser.ts");
203
204/// The first-party Cloudflare platform adapter (v0.19): the platform's real
205/// infrastructure capabilities, as they are — no portable intersection
206/// (decision 0016). The v0.19 surface was the minimal, collection-free `Kv`
207/// (decision 0023); v0.23 adds the `list` drain and `putTtl` (0050/0051);
208/// structured values are v0.22-codec composition, and `Queue` remains its
209/// own future increment. Like the `bynk` surface it has no `binding`
210/// clause — the toolchain supplies the binding.
211pub const CLOUDFLARE_ADAPTER_SRC: &str = include_str!("../lib/cloudflare/bynk.cloudflare.bynk");
212
213/// Every first-party `.bynk` source, paired with its unit name — the single
214/// list every consumer iterates: hover (`describe_firstparty_symbol`),
215/// completion (`EMBEDDED_UNITS`), and the parse guard
216/// (`every_first_party_source_parses`). Before this list each consumer kept its
217/// own hand-maintained copy, and `bynk.locale`/`bynk.locale.types` were added to
218/// none of them — so the whole locale surface hovered as nothing and was absent
219/// from completion (#901).
220///
221/// A view over [`UNITS`], in its order, which is observable: hover takes the
222/// first source declaring a name, and completion lists units in this order. The
223/// `firstparty_sources_cover_every_src_const` drift guard
224/// (`bynkc/tests/firstparty_sources.rs`) fails if a `*_SRC` const is left out of
225/// [`UNITS`].
226pub const FIRSTPARTY_SOURCES: &[(&str, &str)] = &SOURCES;
227
228/// [`FIRSTPARTY_SOURCES`]' backing array, built from [`UNITS`] at compile time.
229const SOURCES: [(&str, &str); UNITS.len()] = {
230    let mut out = [("", ""); UNITS.len()];
231    let mut i = 0;
232    while i < UNITS.len() {
233        out[i] = (UNITS[i].name, UNITS[i].source);
234        i += 1;
235    }
236    out
237};
238
239/// The output path of the Cloudflare platform adapter's binding module,
240/// beside the adapter's emitted `bynk/cloudflare.ts` (distinct from the
241/// `bynk` *surface*'s per-platform `bynk-cloudflare.ts`).
242pub const CLOUDFLARE_BINDING_FILENAME: &str = "bynk/cloudflare.binding.ts";
243
244/// The Cloudflare platform adapter's binding. `WorkersKv` reads the Worker
245/// `env` explicitly (decision 0025): KV namespaces exist only on `env` —
246/// there is no `globalThis` path — so a missing binding is a clear runtime
247/// error rather than a silent fallback.
248const CLOUDFLARE_BINDING: &str = include_str!("../lib/cloudflare/cloudflare.binding.ts");
249
250/// The toolchain-supplied binding for the Cloudflare platform adapter.
251pub fn cloudflare_binding_source() -> &'static str {
252    CLOUDFLARE_BINDING
253}
254
255/// The unit name of the first-party cryptography adapter (standard-library K4,
256/// D5/D6): a flat sibling of `bynk`, platform-free, with a binding per platform.
257pub const CRYPTO_UNIT: &str = "bynk.crypto";
258
259/// `bynk.crypto` — digests, HMAC, constant-time comparison, and signing and
260/// verification with imported keys, as `Effect`s over Web Crypto.
261pub const BYNK_CRYPTO_SRC: &str = include_str!("../lib/crypto/bynk.crypto.bynk");
262
263/// The Cloudflare Workers binding for `bynk.crypto`. The three differ only where
264/// the platforms do: the constant-time comparison primitive.
265const CRYPTO_CLOUDFLARE_BINDING: &str = include_str!("../lib/crypto/crypto-cloudflare.binding.ts");
266
267/// The Node binding for `bynk.crypto`.
268const CRYPTO_NODE_BINDING: &str = include_str!("../lib/crypto/crypto-node.binding.ts");
269
270/// The browser binding for `bynk.crypto`. Web Crypto exists only in a secure
271/// context (R14.5): outside one it throws, loudly, rather than degrade.
272const CRYPTO_BROWSER_BINDING: &str = include_str!("../lib/crypto/crypto-browser.binding.ts");
273
274/// The opaque key types `bynk.crypto` exports. A value of one holds a
275/// non-extractable platform key, so it is never stored, persisted, logged or
276/// sent (`bynk.types.key_at_boundary`), as a `Stream` is not. The checker finds
277/// them by the unit's reserved span file, so a user type of the same name is not
278/// mistaken for one.
279pub const CRYPTO_KEY_TYPES: &[&str] = &["SigningKey", "VerifyKey"];
280
281/// What a first-party unit is, and so how a project brings it in: an adapter is
282/// injected when a unit `consumes` it, a commons when a unit `uses` it. Local to
283/// this crate, which has no dependencies; `bynk-check` maps it onto its own
284/// unit kind.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum UnitKind {
287    Adapter,
288    Commons,
289}
290
291/// The TypeScript binding the toolchain supplies for a first-party unit.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub enum Binding {
294    /// A commons: Bynk-written, so nothing to bind.
295    None,
296    /// One binding per [`Platform`] ([`Platform::bynk_binding_filename`] and
297    /// [`Platform::bynk_binding_source`]): the portable `bynk` surface.
298    PerPlatform,
299    /// A single binding, for a platform-native adapter that runs only on its own
300    /// platform (the platform lock rejects every other `--platform`).
301    Fixed {
302        filename: &'static str,
303        source: &'static str,
304    },
305    /// One binding file per [`Platform`], each with its own name and source, for a
306    /// platform-free unit whose binding differs where the platforms do
307    /// (`bynk.crypto`). [`Binding::PerPlatform`] stays the `bynk` surface's.
308    PerPlatformFiles {
309        cloudflare: (&'static str, &'static str),
310        node: (&'static str, &'static str),
311        browser: (&'static str, &'static str),
312    },
313}
314
315/// One first-party unit, as data (standard-library track, S1 #1945). Adding a
316/// unit to the standard library is an entry in [`UNITS`] plus its files; the
317/// checker's injection reads this table and needs no change.
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319pub struct Unit {
320    /// The unit's dotted name, inside the reserved `bynk.*` prefix.
321    pub name: &'static str,
322    /// Whether a project `consumes` it (an adapter) or `uses` it (a commons).
323    pub kind: UnitKind,
324    /// The synthetic path the injected unit is parsed under. Diagnostics and
325    /// emission name the unit by it, so it never changes.
326    pub identity_path: &'static str,
327    /// The unit's `.bynk` source.
328    pub source: &'static str,
329    /// The binding the toolchain supplies for it.
330    pub binding: Binding,
331    /// Its permanent `ExprId` block: the checker parses it at
332    /// `FIRSTPARTY_ID_BASE + id_block * FIRSTPARTY_ID_BLOCK`, and injects units
333    /// in ascending `id_block` order. A block is never reused or moved, so ids
334    /// and injection order stay stable as units are added; a new unit takes the
335    /// next free block.
336    pub id_block: u32,
337    /// The platform that consuming it locks a deployment unit to (decision
338    /// 0024), if it is platform-native.
339    pub platform: Option<Platform>,
340    /// The provider classes whose constructor takes the Worker `env` (decisions
341    /// 0021/0025).
342    pub env_providers: &'static [&'static str],
343    /// The unit's stability (track D2, S3 #1963): a stable item is under the
344    /// 1.0 promise, an experimental one carries none and needs an explicit
345    /// `[unstable] allow` to use. Required, so no entry is added without a
346    /// choice.
347    pub stability: Stability,
348    /// Items inside a stable unit that are experimental, as paths relative to
349    /// the unit: an exported item (`"Kv"`) or a capability operation
350    /// (`"Kv.list"`). An experimental item makes its operations experimental.
351    pub experimental: &'static [&'static str],
352    /// The exported enums that may gain variants in a minor release, so a
353    /// `match` covering one needs a wildcard (track §11 Q5).
354    pub extensible: &'static [&'static str],
355    /// The capabilities a context may declare named instances of with
356    /// `capability Sessions = Kv` (S4a, #1966): each its own platform resource.
357    /// A capability not listed (Workers AI's single `[ai]` binding, say) has no
358    /// instances.
359    pub instantiable: &'static [Instantiable],
360}
361
362/// A capability a context may declare instances of (S4a, #1966, track D3).
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub struct Instantiable {
365    /// The capability's name in its unit (`Kv`).
366    pub capability: &'static str,
367    /// The prefix of each instance's Worker binding name: `KV` makes
368    /// `capability Sessions = Kv` bind as `KV_SESSIONS`.
369    pub binding_prefix: &'static str,
370    /// The creation options (`@name(…)`) an instance may carry, each with the
371    /// one literal its value is (standard-library P3, #2342: `@worker("…")`
372    /// takes a string, `@limit(100)` an `Int`, `@period(60.seconds)` a
373    /// `Duration`); any other is refused. Empty when the kind takes none yet.
374    pub options: &'static [(&'static str, OptionKind)],
375    /// The options every instance must carry (interop I5, #1972): a
376    /// `Service` names the Worker it reaches, so it has no default. A subset
377    /// of [`Instantiable::options`].
378    pub required: &'static [&'static str],
379    /// Whether the base capability is usable bare, through `given Kv`, as
380    /// well as through instances. `false` for a kind whose every use needs an
381    /// option: a bare `Service` would name no Worker.
382    pub bare: bool,
383}
384
385impl Instantiable {
386    /// The kind of literal option `name` takes, or `None` when it is not one
387    /// of this kind's options.
388    pub fn option_kind(&self, name: &str) -> Option<OptionKind> {
389        self.options
390            .iter()
391            .find(|(o, _)| *o == name)
392            .map(|(_, k)| *k)
393    }
394
395    /// The names of this kind's options, in declaration order.
396    pub fn option_names(&self) -> impl Iterator<Item = &'static str> + '_ {
397        self.options.iter().map(|(o, _)| *o)
398    }
399}
400
401/// The literal an instance option takes (standard-library P3, #2342).
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub enum OptionKind {
404    /// A string literal: `@worker("legacy-billing")`.
405    Str,
406    /// A positive `Int` literal: `@limit(100)`.
407    PositiveInt,
408    /// A `Duration` literal: `@period(60.seconds)`.
409    Duration,
410}
411
412/// The Worker binding prefix of a `Service` instance (interop I5, #1972):
413/// `capability Billing = Service @worker("legacy-billing")` binds as
414/// `SERVICE_BILLING`, a `[[services]]` entry naming `legacy-billing`.
415pub const SERVICE_BINDING_PREFIX: &str = "SERVICE";
416
417/// The option of a `Service` instance that names the Worker it reaches.
418/// `worker`, not D4's `service`: `service` is a keyword, so `@service(…)`
419/// does not parse, and widening the annotation grammar is language work
420/// (ADR 0023).
421pub const SERVICE_WORKER_OPTION: &str = "worker";
422
423/// The Worker binding prefix of an `R2` instance (standard-library P5,
424/// #2323): `capability Archives = R2` binds as `R2_ARCHIVES`, an
425/// `[[r2_buckets]]` entry.
426pub const R2_BINDING_PREFIX: &str = "R2";
427
428/// The one creation option of an `R2` instance: the bucket's jurisdiction.
429pub const R2_JURISDICTION_OPTION: &str = "jurisdiction";
430
431/// The jurisdictions an `R2` bucket may be pinned to, as `@jurisdiction(…)`
432/// takes them and `wrangler r2 bucket create --jurisdiction` accepts them.
433pub const R2_JURISDICTIONS: &[&str] = &["eu", "fedramp"];
434
435/// The Worker binding prefix of a `RateLimit` instance (standard-library P3,
436/// #2342): `capability LoginLimit = RateLimit @limit(100) @period(60.seconds)`
437/// binds as `RATELIMIT_LOGIN_LIMIT`, a `[[ratelimits]]` entry.
438pub const RATELIMIT_BINDING_PREFIX: &str = "RATELIMIT";
439
440/// A `RateLimit` instance's count: the calls per key allowed in one period.
441pub const RATELIMIT_LIMIT_OPTION: &str = "limit";
442
443/// A `RateLimit` instance's window.
444pub const RATELIMIT_PERIOD_OPTION: &str = "period";
445
446/// The windows the Workers Rate Limiting binding offers, in seconds.
447pub const RATELIMIT_PERIODS: &[i64] = &[10, 60];
448
449/// Whether a first-party item is under the 1.0 promise (track D2).
450#[derive(Debug, Clone, Copy, PartialEq, Eq)]
451pub enum Stability {
452    /// Under the promise: a stable L0/L1 item changes only at a major release; a
453    /// stable L2/L3 item may gain operations and, if extensible, variants.
454    Stable,
455    /// No promise: it may change or disappear in any release, and using it needs
456    /// an `[unstable] allow` entry in `bynk.toml`.
457    Experimental,
458}
459
460impl Unit {
461    /// The binding module to emit for this unit on `platform`, as
462    /// `(output path, source)`, or `None` for a commons.
463    pub fn binding_for(&self, platform: Platform) -> Option<(&'static str, &'static str)> {
464        match self.binding {
465            Binding::None => None,
466            Binding::PerPlatform => Some((
467                platform.bynk_binding_filename(),
468                platform.bynk_binding_source(),
469            )),
470            Binding::Fixed { filename, source } => Some((filename, source)),
471            Binding::PerPlatformFiles {
472                cloudflare,
473                node,
474                browser,
475            } => Some(match platform {
476                Platform::Cloudflare => cloudflare,
477                Platform::Node => node,
478                Platform::Browser => browser,
479            }),
480        }
481    }
482}
483
484/// The standard library's first-party units. Dependencies between them are not
485/// listed here: they are the `uses`/`consumes` lines of each unit's own source,
486/// which the checker follows when it injects. The table's order is
487/// [`FIRSTPARTY_SOURCES`]' order; injection follows [`Unit::id_block`].
488pub const UNITS: &[Unit] = &[
489    Unit {
490        name: BYNK_UNIT,
491        kind: UnitKind::Adapter,
492        identity_path: "bynk.bynk",
493        source: BYNK_ADAPTER_SRC,
494        binding: Binding::PerPlatform,
495        id_block: 0,
496        platform: None,
497        env_providers: &["SecretsProvider"],
498        stability: Stability::Stable,
499        experimental: &[],
500        extensible: &["FetchError", "Method"],
501        instantiable: &[],
502    },
503    Unit {
504        name: CLOUDFLARE_UNIT,
505        kind: UnitKind::Adapter,
506        identity_path: "bynk/cloudflare.bynk",
507        source: CLOUDFLARE_ADAPTER_SRC,
508        binding: Binding::Fixed {
509            filename: CLOUDFLARE_BINDING_FILENAME,
510            source: CLOUDFLARE_BINDING,
511        },
512        id_block: 1,
513        platform: Some(Platform::Cloudflare),
514        env_providers: &[
515            "WorkersKv",
516            "WorkersService",
517            "WorkersR2",
518            "WorkersRateLimit",
519        ],
520        stability: Stability::Stable,
521        // Interop I5 (#1972): a Service Binding to a non-Bynk Worker is new
522        // and its surface is untyped, so it lands outside the 1.0 promise.
523        // P5 (#2323): R2 ships experimental until the first-party registry has
524        // run on it (#2308 R6); its conditions are extensible meanwhile.
525        // P3 (#2342): RateLimit too, until the registry has run on it.
526        experimental: &["Service", "R2", "RateLimit"],
527        extensible: &["R2Condition"],
528        instantiable: &[
529            Instantiable {
530                capability: "Kv",
531                binding_prefix: KV_BINDING_NAME,
532                options: &[],
533                required: &[],
534                bare: true,
535            },
536            Instantiable {
537                capability: "Service",
538                binding_prefix: SERVICE_BINDING_PREFIX,
539                options: &[(SERVICE_WORKER_OPTION, OptionKind::Str)],
540                required: &[SERVICE_WORKER_OPTION],
541                bare: false,
542            },
543            Instantiable {
544                capability: "R2",
545                binding_prefix: R2_BINDING_PREFIX,
546                options: &[(R2_JURISDICTION_OPTION, OptionKind::Str)],
547                required: &[],
548                bare: false,
549            },
550            Instantiable {
551                capability: "RateLimit",
552                binding_prefix: RATELIMIT_BINDING_PREFIX,
553                options: &[
554                    (RATELIMIT_LIMIT_OPTION, OptionKind::PositiveInt),
555                    (RATELIMIT_PERIOD_OPTION, OptionKind::Duration),
556                ],
557                required: &[RATELIMIT_LIMIT_OPTION, RATELIMIT_PERIOD_OPTION],
558                bare: false,
559            },
560        ],
561    },
562    Unit {
563        name: LIST_UNIT,
564        kind: UnitKind::Commons,
565        identity_path: "bynk/list.bynk",
566        source: BYNK_LIST_SRC,
567        binding: Binding::None,
568        id_block: 3,
569        platform: None,
570        env_providers: &[],
571        stability: Stability::Stable,
572        experimental: &[],
573        extensible: &[],
574        instantiable: &[],
575    },
576    Unit {
577        name: MAP_UNIT,
578        kind: UnitKind::Commons,
579        identity_path: "bynk/map.bynk",
580        source: BYNK_MAP_SRC,
581        binding: Binding::None,
582        id_block: 2,
583        platform: None,
584        env_providers: &[],
585        stability: Stability::Stable,
586        experimental: &[],
587        extensible: &[],
588        instantiable: &[],
589    },
590    Unit {
591        name: STRING_UNIT,
592        kind: UnitKind::Commons,
593        identity_path: "bynk/string.bynk",
594        source: BYNK_STRING_SRC,
595        binding: Binding::None,
596        id_block: 4,
597        platform: None,
598        env_providers: &[],
599        stability: Stability::Stable,
600        experimental: &[],
601        extensible: &[],
602        instantiable: &[],
603    },
604    Unit {
605        name: LOCALE_UNIT,
606        kind: UnitKind::Commons,
607        identity_path: "bynk/locale.bynk",
608        source: BYNK_LOCALE_SRC,
609        binding: Binding::None,
610        id_block: 6,
611        platform: None,
612        env_providers: &[],
613        stability: Stability::Stable,
614        experimental: &[],
615        extensible: &[],
616        instantiable: &[],
617    },
618    Unit {
619        name: LOCALE_TYPES_UNIT,
620        kind: UnitKind::Commons,
621        identity_path: "bynk/locale/types.bynk",
622        source: BYNK_LOCALE_TYPES_SRC,
623        binding: Binding::None,
624        id_block: 5,
625        platform: None,
626        env_providers: &[],
627        stability: Stability::Stable,
628        experimental: &[],
629        extensible: &[],
630        instantiable: &[],
631    },
632    Unit {
633        name: CRYPTO_UNIT,
634        kind: UnitKind::Adapter,
635        identity_path: "bynk/crypto.bynk",
636        source: BYNK_CRYPTO_SRC,
637        binding: Binding::PerPlatformFiles {
638            cloudflare: (
639                "bynk/crypto-cloudflare.binding.ts",
640                CRYPTO_CLOUDFLARE_BINDING,
641            ),
642            node: ("bynk/crypto-node.binding.ts", CRYPTO_NODE_BINDING),
643            browser: ("bynk/crypto-browser.binding.ts", CRYPTO_BROWSER_BINDING),
644        },
645        id_block: 7,
646        platform: None,
647        env_providers: &[],
648        // Experimental until the first-party registry has signed with it in
649        // production (#2308 R6), as P5's R2 does.
650        stability: Stability::Experimental,
651        experimental: &[],
652        extensible: &["Digest", "Signature", "CryptoError"],
653        instantiable: &[],
654    },
655];
656
657/// The registry entry for `name`, if it is a first-party unit.
658pub fn unit(name: &str) -> Option<&'static Unit> {
659    UNITS.iter().find(|u| u.name == name)
660}
661
662/// The unit a dotted item path lies in, and the rest of the path relative to it
663/// (empty for the unit itself). Unit names contain dots, so the longest unit
664/// name that is a whole-segment prefix wins: `bynk.cloudflare.Kv` is in
665/// `bynk.cloudflare`, not in `bynk`.
666pub fn split_item_path(path: &str) -> Option<(&'static Unit, &str)> {
667    split_item_path_in(UNITS, path)
668}
669
670/// [`split_item_path`] over a given table (tests pass a synthetic one).
671pub fn split_item_path_in<'u, 'p>(units: &'u [Unit], path: &'p str) -> Option<(&'u Unit, &'p str)> {
672    units
673        .iter()
674        .filter_map(|u| {
675            if path == u.name {
676                Some((u, ""))
677            } else {
678                path.strip_prefix(u.name)?
679                    .strip_prefix('.')
680                    .map(|rest| (u, rest))
681            }
682        })
683        .max_by_key(|(u, _)| u.name.len())
684}
685
686/// Whether `path` is `prefix` or lies under it, by whole dotted segments.
687pub fn covers(prefix: &str, path: &str) -> bool {
688    path == prefix
689        || path
690            .strip_prefix(prefix)
691            .is_some_and(|rest| rest.starts_with('.'))
692}
693
694/// The stability of a first-party item: a unit (`bynk.cloudflare`), an
695/// exported item (`bynk.cloudflare.Kv`) or a capability operation
696/// (`bynk.cloudflare.Kv.list`). An item in an experimental unit, or under an
697/// experimental item, is experimental. `None` when no first-party unit holds
698/// the path.
699pub fn stability_of(path: &str) -> Option<Stability> {
700    stability_of_in(UNITS, path)
701}
702
703/// [`stability_of`] over a given table.
704pub fn stability_of_in(units: &[Unit], path: &str) -> Option<Stability> {
705    let (unit, rest) = split_item_path_in(units, path)?;
706    if unit.stability == Stability::Experimental
707        || unit.experimental.iter().any(|item| covers(item, rest))
708    {
709        Some(Stability::Experimental)
710    } else {
711        Some(Stability::Stable)
712    }
713}
714
715/// Every experimental item, as a full path: each experimental unit, and each
716/// listed item of a stable one.
717pub fn experimental_items() -> Vec<String> {
718    experimental_items_in(UNITS)
719}
720
721/// [`experimental_items`] over a given table.
722pub fn experimental_items_in(units: &[Unit]) -> Vec<String> {
723    let mut out = Vec::new();
724    for u in units {
725        if u.stability == Stability::Experimental {
726            out.push(u.name.to_string());
727        }
728        out.extend(
729            u.experimental
730                .iter()
731                .map(|item| format!("{}.{item}", u.name)),
732        );
733    }
734    out
735}
736
737/// Whether an `[unstable] allow` list covers `path`: an entry covers itself and
738/// everything under it.
739pub fn allows(allow: &[String], path: &str) -> bool {
740    allow.iter().any(|entry| covers(entry, path))
741}
742
743/// Whether `entry`, an `[unstable] allow` entry, reaches anything in
744/// `experimental` (a list of experimental item paths, such as
745/// [`experimental_items`]): it names an experimental item, lies under one, or
746/// contains one. An entry that reaches nothing is stale.
747pub fn allow_entry_is_live(experimental: &[String], entry: &str) -> bool {
748    experimental
749        .iter()
750        .any(|item| covers(item, entry) || covers(entry, item))
751}
752
753/// The instance kind `capability` of `unit` is, if a context may declare named
754/// instances of it (S4a, #1966).
755pub fn instantiable(unit: &str, capability: &str) -> Option<&'static Instantiable> {
756    self::unit(unit)?
757        .instantiable
758        .iter()
759        .find(|i| i.capability == capability)
760}
761
762/// Whether `name`, an enum exported by `unit`, is extensible.
763pub fn is_extensible(unit: &str, name: &str) -> bool {
764    is_extensible_in(UNITS, unit, name)
765}
766
767/// [`is_extensible`] over a given table.
768pub fn is_extensible_in(units: &[Unit], unit: &str, name: &str) -> bool {
769    units
770        .iter()
771        .any(|u| u.name == unit && u.extensible.contains(&name))
772}
773
774/// The names a first-party unit exports: those on its `exports … { … }` lines
775/// (an adapter) and its own `fn`s and `type`s (a commons). Read from the
776/// source, so the list cannot fall behind it.
777pub fn exported_names(unit: &Unit) -> Vec<&'static str> {
778    let mut out = Vec::new();
779    for line in unit.source.lines() {
780        let trimmed = line.trim_start();
781        if let Some(rest) = trimmed.strip_prefix("exports ")
782            && let Some((_, list)) = rest.split_once('{')
783            && let Some((names, _)) = list.split_once('}')
784        {
785            out.extend(names.split(',').map(str::trim).filter(|n| !n.is_empty()));
786        } else if unit.kind == UnitKind::Commons
787            // A commons' own declarations: at column 0 in the flat form, one tab
788            // in the braced `commons bynk.list { … }` form the first-party
789            // sources use. Nothing deeper is a declaration.
790            && (line == trimmed || line.strip_prefix('\t') == Some(trimmed))
791        {
792            for keyword in ["fn ", "type "] {
793                if let Some(rest) = trimmed.strip_prefix(keyword) {
794                    let end = rest
795                        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
796                        .unwrap_or(rest.len());
797                    if end > 0 {
798                        out.push(&rest[..end]);
799                    }
800                }
801            }
802        }
803    }
804    out
805}
806
807/// Whether `path` names a first-party unit or an item it exports. Operation
808/// paths (`bynk.cloudflare.Kv.list`) are accepted when their item exists.
809pub fn names_first_party_item(path: &str) -> bool {
810    names_first_party_item_in(UNITS, path)
811}
812
813/// [`names_first_party_item`] over a given table.
814pub fn names_first_party_item_in(units: &[Unit], path: &str) -> bool {
815    match split_item_path_in(units, path) {
816        None => false,
817        Some((_, "")) => true,
818        Some((unit, rest)) => {
819            let item = rest.split('.').next().unwrap_or(rest);
820            exported_names(unit).contains(&item)
821        }
822    }
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828
829    /// A synthetic registry with an experimental unit, an experimental item
830    /// and an experimental operation inside stable units.
831    const SYNTH: &[Unit] = &[
832        Unit {
833            name: "bynk",
834            kind: UnitKind::Adapter,
835            identity_path: "bynk.bynk",
836            source: "adapter bynk {\n\texports capability { Clock, Fetch }\n\texports transparent { FetchError }\n}\n",
837            binding: Binding::PerPlatform,
838            id_block: 0,
839            platform: None,
840            env_providers: &[],
841            stability: Stability::Stable,
842            experimental: &["Fetch.stream"],
843            extensible: &["FetchError"],
844            instantiable: &[],
845        },
846        Unit {
847            name: "bynk.cloudflare",
848            kind: UnitKind::Adapter,
849            identity_path: "bynk/cloudflare.bynk",
850            source: "adapter bynk.cloudflare {\n\texports capability { Kv, Ai }\n}\n",
851            binding: Binding::None,
852            id_block: 1,
853            platform: Some(Platform::Cloudflare),
854            env_providers: &[],
855            stability: Stability::Stable,
856            experimental: &["Ai"],
857            extensible: &[],
858            instantiable: &[],
859        },
860        Unit {
861            name: "bynk.cloudflare.d1",
862            kind: UnitKind::Adapter,
863            identity_path: "bynk/cloudflare/d1.bynk",
864            source: "adapter bynk.cloudflare.d1 {\n\texports capability { D1 }\n}\n",
865            binding: Binding::None,
866            id_block: 2,
867            platform: Some(Platform::Cloudflare),
868            env_providers: &[],
869            stability: Stability::Experimental,
870            experimental: &[],
871            extensible: &[],
872            instantiable: &[],
873        },
874        Unit {
875            name: "bynk.text",
876            kind: UnitKind::Commons,
877            identity_path: "bynk/text.bynk",
878            source: "commons bynk.text\n\ntype Slug = String\n\nfn shout(s: String) -> String {\n\ts\n}\n",
879            binding: Binding::None,
880            id_block: 3,
881            platform: None,
882            env_providers: &[],
883            stability: Stability::Stable,
884            experimental: &[],
885            extensible: &[],
886            instantiable: &[],
887        },
888    ];
889
890    #[test]
891    fn item_paths_resolve_to_the_longest_unit() {
892        let unit_of = |p| split_item_path_in(SYNTH, p).map(|(u, rest)| (u.name, rest));
893        assert_eq!(unit_of("bynk"), Some(("bynk", "")));
894        assert_eq!(unit_of("bynk.Fetch.send"), Some(("bynk", "Fetch.send")));
895        assert_eq!(
896            unit_of("bynk.cloudflare.Kv"),
897            Some(("bynk.cloudflare", "Kv"))
898        );
899        assert_eq!(
900            unit_of("bynk.cloudflare.d1.D1"),
901            Some(("bynk.cloudflare.d1", "D1"))
902        );
903        assert_eq!(unit_of("bynkx"), None, "a whole-segment prefix only");
904        assert_eq!(unit_of("user.unit"), None);
905    }
906
907    #[test]
908    fn stability_follows_unit_item_and_operation() {
909        let st = |p| stability_of_in(SYNTH, p);
910        use Stability::*;
911        assert_eq!(st("bynk.Clock"), Some(Stable));
912        assert_eq!(st("bynk.Fetch.send"), Some(Stable));
913        assert_eq!(
914            st("bynk.Fetch.stream"),
915            Some(Experimental),
916            "an experimental operation"
917        );
918        assert_eq!(
919            st("bynk.Fetch"),
920            Some(Stable),
921            "its capability stays stable"
922        );
923        assert_eq!(
924            st("bynk.cloudflare.Ai"),
925            Some(Experimental),
926            "an experimental item"
927        );
928        assert_eq!(
929            st("bynk.cloudflare.Ai.run"),
930            Some(Experimental),
931            "its operations too"
932        );
933        assert_eq!(st("bynk.cloudflare.Kv"), Some(Stable));
934        assert_eq!(
935            st("bynk.cloudflare.d1"),
936            Some(Experimental),
937            "an experimental unit"
938        );
939        assert_eq!(st("bynk.cloudflare.d1.D1.query"), Some(Experimental));
940        assert_eq!(st("user.unit"), None);
941    }
942
943    #[test]
944    fn allow_entries_cover_by_whole_segment_prefix() {
945        let allow = vec![
946            "bynk.cloudflare.Ai".to_string(),
947            "bynk.cloudflare.d1".to_string(),
948        ];
949        assert!(allows(&allow, "bynk.cloudflare.Ai"));
950        assert!(allows(&allow, "bynk.cloudflare.Ai.run"));
951        assert!(allows(&allow, "bynk.cloudflare.d1.D1.query"));
952        assert!(
953            !allows(&allow, "bynk.cloudflare.AiX"),
954            "not a segment prefix"
955        );
956        assert!(!allows(&allow, "bynk.Fetch.stream"));
957        assert!(!allows(&[], "bynk.cloudflare.Ai"));
958    }
959
960    #[test]
961    fn an_allow_entry_is_live_while_it_reaches_something_experimental() {
962        let synth = experimental_items_in(SYNTH);
963        let live = |e| allow_entry_is_live(&synth, e);
964        assert!(live("bynk.cloudflare.Ai"));
965        assert!(live("bynk.cloudflare.Ai.run"), "under an experimental item");
966        assert!(live("bynk.cloudflare"), "contains an experimental item");
967        assert!(live("bynk.Fetch.stream"));
968        assert!(live("bynk"), "contains an experimental operation");
969        assert!(!live("bynk.cloudflare.Kv"), "stable: a stale entry");
970        assert!(!live("bynk.text"));
971        assert_eq!(
972            experimental_items_in(SYNTH),
973            [
974                "bynk.Fetch.stream",
975                "bynk.cloudflare.Ai",
976                "bynk.cloudflare.d1"
977            ]
978        );
979    }
980
981    #[test]
982    fn exported_names_and_item_existence_come_from_the_sources() {
983        assert_eq!(exported_names(&SYNTH[0]), ["Clock", "Fetch", "FetchError"]);
984        assert_eq!(exported_names(&SYNTH[3]), ["Slug", "shout"]);
985        let names = |p| names_first_party_item_in(SYNTH, p);
986        assert!(names("bynk.cloudflare"));
987        assert!(names("bynk.cloudflare.Ai"));
988        assert!(
989            names("bynk.cloudflare.Ai.run"),
990            "an operation of an existing item"
991        );
992        assert!(names("bynk.text.shout"));
993        assert!(!names("bynk.cloudflare.Aii"), "a typo");
994        assert!(!names("user.unit"));
995    }
996
997    #[test]
998    fn extensibility_is_by_unit_and_name() {
999        assert!(is_extensible_in(SYNTH, "bynk", "FetchError"));
1000        assert!(
1001            !is_extensible_in(SYNTH, "user.app", "FetchError"),
1002            "a user's own FetchError"
1003        );
1004        assert!(!is_extensible_in(SYNTH, "bynk", "Method"));
1005    }
1006
1007    /// The shipped instantiable kinds: `bynk.cloudflare`'s `Kv` (S4a, #1966),
1008    /// binding as `KV_<NAME>` with no creation options, and its `Service`
1009    /// (interop I5, #1972), binding as `SERVICE_<NAME>` and naming its Worker
1010    /// with a required `@worker`, never usable bare. Each one is a capability
1011    /// its unit exports.
1012    #[test]
1013    fn the_shipped_instantiable_kinds_are_pinned() {
1014        let kinds: Vec<(&str, &str, &str)> = UNITS
1015            .iter()
1016            .flat_map(|u| {
1017                u.instantiable
1018                    .iter()
1019                    .map(move |i| (u.name, i.capability, i.binding_prefix))
1020            })
1021            .collect();
1022        assert_eq!(
1023            kinds,
1024            [
1025                ("bynk.cloudflare", "Kv", "KV"),
1026                ("bynk.cloudflare", "Service", "SERVICE"),
1027                ("bynk.cloudflare", "R2", "R2"),
1028                ("bynk.cloudflare", "RateLimit", "RATELIMIT")
1029            ]
1030        );
1031        let kv = instantiable("bynk.cloudflare", "Kv").expect("Kv is instantiable");
1032        assert!(kv.options.is_empty() && kv.required.is_empty() && kv.bare);
1033        let service = instantiable("bynk.cloudflare", "Service").expect("Service is instantiable");
1034        assert_eq!(service.option_names().collect::<Vec<_>>(), ["worker"]);
1035        assert_eq!(service.required, ["worker"]);
1036        assert!(!service.bare);
1037        let r2 = instantiable("bynk.cloudflare", "R2").expect("R2 is instantiable");
1038        assert_eq!(r2.option_names().collect::<Vec<_>>(), ["jurisdiction"]);
1039        assert!(r2.required.is_empty() && !r2.bare);
1040        let rl = instantiable("bynk.cloudflare", "RateLimit").expect("RateLimit is instantiable");
1041        assert_eq!(rl.option_kind("limit"), Some(OptionKind::PositiveInt));
1042        assert_eq!(rl.option_kind("period"), Some(OptionKind::Duration));
1043        assert_eq!(rl.required, ["limit", "period"]);
1044        assert!(!rl.bare);
1045        for u in UNITS {
1046            for i in u.instantiable {
1047                assert!(
1048                    i.required.iter().all(|r| i.option_kind(r).is_some()),
1049                    "{}.{}: a required option must be an option",
1050                    u.name,
1051                    i.capability
1052                );
1053            }
1054        }
1055        assert!(exported_names(unit("bynk.cloudflare").unwrap()).contains(&"Kv"));
1056        assert!(exported_names(unit("bynk.cloudflare").unwrap()).contains(&"Service"));
1057        assert_eq!(instantiable("bynk", "Clock"), None);
1058        assert_eq!(instantiable("bynk.cloudflare", "Nope"), None);
1059    }
1060
1061    /// The shipped registry: every unit is stable (S3 ships the mechanism,
1062    /// #1963 Decision C) but `bynk.crypto` (K4), which is experimental until the
1063    /// first-party registry has signed with it in production. The one
1064    /// experimental item inside a stable unit is `bynk.cloudflare`'s `Service`
1065    /// (interop I5, #1972), and the growing enums are extensible. A slice that
1066    /// marks an item experimental updates this test, so the change is visible
1067    /// in review.
1068    #[test]
1069    fn the_shipped_stability_is_pinned() {
1070        for u in UNITS {
1071            let expected = if u.name == CRYPTO_UNIT {
1072                Stability::Experimental
1073            } else {
1074                Stability::Stable
1075            };
1076            assert_eq!(u.stability, expected, "{}", u.name);
1077        }
1078        assert_eq!(
1079            experimental_items(),
1080            [
1081                "bynk.cloudflare.Service",
1082                "bynk.cloudflare.R2",
1083                "bynk.cloudflare.RateLimit",
1084                "bynk.crypto"
1085            ]
1086        );
1087        let extensible: Vec<(&str, &str)> = UNITS
1088            .iter()
1089            .flat_map(|u| u.extensible.iter().map(move |e| (u.name, *e)))
1090            .collect();
1091        assert_eq!(
1092            extensible,
1093            [
1094                ("bynk", "FetchError"),
1095                ("bynk", "Method"),
1096                ("bynk.cloudflare", "R2Condition"),
1097                ("bynk.crypto", "Digest"),
1098                ("bynk.crypto", "Signature"),
1099                ("bynk.crypto", "CryptoError"),
1100            ]
1101        );
1102        for (unit, name) in extensible {
1103            assert!(
1104                exported_names(self::unit(unit).unwrap()).contains(&name),
1105                "{unit} lists {name} as extensible but does not export it"
1106            );
1107        }
1108        assert!(names_first_party_item("bynk.cloudflare.Kv.list"));
1109        assert!(names_first_party_item("bynk.list.reverse"));
1110        assert!(!names_first_party_item("bynk.cloudflare.Kvv"));
1111    }
1112
1113    /// #1958: `WorkersKv` reads the namespace at the name every generated
1114    /// Worker declares it under (`[[kv_namespaces]] binding`, its `Env`), the
1115    /// one TypeScript literal no Rust constructor can supply. Since S4a (#1966)
1116    /// the name is a constructor parameter, so a derived capability's instance
1117    /// can pass its own; the bare `Kv`'s is the parameter's default.
1118    ///
1119    /// Matched as a whole identifier, then by its neighbours, so the test
1120    /// ignores formatting but not a rename: `KVX` is not `KV` (review of
1121    /// #1962).
1122    #[test]
1123    fn the_cloudflare_binding_reads_kv_binding_name() {
1124        let ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$';
1125        let src = CLOUDFLARE_BINDING;
1126        let uses: Vec<(&str, &str)> = src
1127            .match_indices(KV_BINDING_NAME)
1128            .map(|(at, name)| (&src[..at], &src[at + name.len()..]))
1129            .filter(|(before, after)| !before.ends_with(ident) && !after.starts_with(ident))
1130            .collect();
1131        assert!(
1132            uses.iter().any(|(b, a)| {
1133                b.trim_end().ends_with("binding: string = \"") && a.starts_with('"')
1134            }),
1135            "the constructor's `binding` no longer defaults to \"{KV_BINDING_NAME}\""
1136        );
1137        assert!(
1138            src.contains("?.[this.binding]"),
1139            "the namespace is no longer read at `env[binding]`"
1140        );
1141    }
1142
1143    /// Each unit's `ExprId` block is permanent: emitted output and the
1144    /// process-wide parse cache depend on it. These are the blocks the
1145    /// hand-written injection used before the registry (S1, #1945); a new
1146    /// unit takes a new block and never moves one of these.
1147    #[test]
1148    fn id_blocks_are_pinned_and_distinct() {
1149        let blocks: Vec<(&str, u32)> = UNITS.iter().map(|u| (u.name, u.id_block)).collect();
1150        assert_eq!(
1151            blocks,
1152            [
1153                ("bynk", 0),
1154                ("bynk.cloudflare", 1),
1155                ("bynk.list", 3),
1156                ("bynk.map", 2),
1157                ("bynk.string", 4),
1158                ("bynk.locale", 6),
1159                ("bynk.locale.types", 5),
1160                ("bynk.crypto", 7),
1161            ]
1162        );
1163        let mut sorted: Vec<u32> = UNITS.iter().map(|u| u.id_block).collect();
1164        sorted.sort_unstable();
1165        sorted.dedup();
1166        assert_eq!(sorted.len(), UNITS.len(), "two units share an id block");
1167    }
1168
1169    /// Hover and completion read [`FIRSTPARTY_SOURCES`] in order, so it is
1170    /// pinned to the order the hand-written list had.
1171    #[test]
1172    fn firstparty_sources_keep_their_order() {
1173        let names: Vec<&str> = FIRSTPARTY_SOURCES.iter().map(|(n, _)| *n).collect();
1174        assert_eq!(
1175            names,
1176            [
1177                "bynk",
1178                "bynk.cloudflare",
1179                "bynk.list",
1180                "bynk.map",
1181                "bynk.string",
1182                "bynk.locale",
1183                "bynk.locale.types",
1184                "bynk.crypto",
1185            ]
1186        );
1187        for (unit, (name, source)) in UNITS.iter().zip(FIRSTPARTY_SOURCES) {
1188            assert_eq!((unit.name, unit.source), (*name, *source));
1189        }
1190    }
1191
1192    /// The views over the table answer as the hand-written matches did.
1193    #[test]
1194    fn metadata_views_match_the_previous_answers() {
1195        assert_eq!(platform_of("bynk.cloudflare"), Some(Platform::Cloudflare));
1196        for name in [
1197            "bynk",
1198            "bynk.list",
1199            "bynk.map",
1200            "bynk.string",
1201            "bynk.locale",
1202            "user.unit",
1203        ] {
1204            assert_eq!(platform_of(name), None, "{name}");
1205        }
1206        assert!(provider_takes_env("bynk", "SecretsProvider"));
1207        assert!(provider_takes_env("bynk.cloudflare", "WorkersKv"));
1208        assert!(!provider_takes_env("bynk", "WorkersKv"));
1209        assert!(!provider_takes_env("bynk.cloudflare", "SecretsProvider"));
1210        assert!(!provider_takes_env("bynk", "ClockProvider"));
1211        assert!(!provider_takes_env("user.unit", "SecretsProvider"));
1212    }
1213
1214    /// An adapter carries a binding and a commons does not, and every name and
1215    /// identity path is unique, every name inside the reserved prefix.
1216    #[test]
1217    fn entries_are_well_formed() {
1218        for u in UNITS {
1219            assert!(
1220                u.name == "bynk" || u.name.starts_with("bynk."),
1221                "{}",
1222                u.name
1223            );
1224            assert_eq!(
1225                UNITS.iter().filter(|o| o.name == u.name).count(),
1226                1,
1227                "{}",
1228                u.name
1229            );
1230            // Two entries under one identity path would be two parsed units
1231            // that diagnostics and emission cannot tell apart.
1232            assert_eq!(
1233                UNITS
1234                    .iter()
1235                    .filter(|o| o.identity_path == u.identity_path)
1236                    .count(),
1237                1,
1238                "{}",
1239                u.identity_path
1240            );
1241            match u.kind {
1242                UnitKind::Adapter => assert_ne!(u.binding, Binding::None, "{}", u.name),
1243                UnitKind::Commons => {
1244                    assert_eq!(u.binding, Binding::None, "{}", u.name);
1245                    assert!(u.env_providers.is_empty(), "{}", u.name);
1246                }
1247            }
1248        }
1249        assert_eq!(
1250            unit("bynk.cloudflare").and_then(|u| u.binding_for(Platform::Node)),
1251            Some((CLOUDFLARE_BINDING_FILENAME, CLOUDFLARE_BINDING))
1252        );
1253        assert_eq!(
1254            unit("bynk").and_then(|u| u.binding_for(Platform::Browser)),
1255            Some(("bynk-browser.ts", BYNK_BROWSER_BINDING))
1256        );
1257        assert_eq!(
1258            unit("bynk.list").and_then(|u| u.binding_for(Platform::Node)),
1259            None
1260        );
1261    }
1262
1263    /// The three `bynk.crypto` bindings are one body with one marked region of
1264    /// platform difference (the constant-time comparison primitive). They are
1265    /// separate files because each ships alone, so this keeps them from drifting.
1266    #[test]
1267    fn the_crypto_bindings_differ_only_in_their_platform_region() {
1268        const START: &str = "// --- platform: constant-time comparison primitive";
1269        const END: &str = "// --- end platform";
1270        fn shared(src: &str) -> String {
1271            let (head, rest) = src.split_once(START).expect("platform region start");
1272            let (_, tail) = rest.split_once(END).expect("platform region end");
1273            // The second header line names the platform.
1274            let head = head.lines().skip(2).collect::<Vec<_>>().join("\n");
1275            format!("{head}\n{tail}")
1276        }
1277        let cloudflare = shared(CRYPTO_CLOUDFLARE_BINDING);
1278        assert_eq!(cloudflare, shared(CRYPTO_NODE_BINDING));
1279        assert_eq!(cloudflare, shared(CRYPTO_BROWSER_BINDING));
1280    }
1281
1282    /// The hardcoded [`BYNK_SURFACE_CAPABILITIES`] must match the adapter's
1283    /// `exports capability { … }` line — otherwise the unknown-name quick-fix
1284    /// (#852) would offer a stale `consumes bynk { … }` set.
1285    #[test]
1286    fn bynk_surface_capabilities_match_the_adapter() {
1287        let src = BYNK_ADAPTER_SRC;
1288        let line = src
1289            .lines()
1290            .find(|l| l.trim_start().starts_with("exports capability {"))
1291            .expect("adapter declares `exports capability`");
1292        let inner = line
1293            .split_once('{')
1294            .and_then(|(_, r)| r.split_once('}'))
1295            .map(|(names, _)| names)
1296            .expect("braced capability list");
1297        let declared: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
1298        assert_eq!(
1299            declared, BYNK_SURFACE_CAPABILITIES,
1300            "BYNK_SURFACE_CAPABILITIES is out of sync with bynk.bynk"
1301        );
1302    }
1303}