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/// The prefix an `EdgeCache` instance's binding name would carry (first-party
450/// registry L7, #2414). Workers Cache is a Worker-wide `[cache]` setting with
451/// no `env` binding, so the name is never emitted: the instance is built from
452/// the entry's `ctx` instead.
453pub const EDGE_CACHE_BINDING_PREFIX: &str = "EDGE_CACHE";
454
455/// Whether a first-party item is under the 1.0 promise (track D2).
456#[derive(Debug, Clone, Copy, PartialEq, Eq)]
457pub enum Stability {
458    /// Under the promise: a stable L0/L1 item changes only at a major release; a
459    /// stable L2/L3 item may gain operations and, if extensible, variants.
460    Stable,
461    /// No promise: it may change or disappear in any release, and using it needs
462    /// an `[unstable] allow` entry in `bynk.toml`.
463    Experimental,
464}
465
466impl Unit {
467    /// The binding module to emit for this unit on `platform`, as
468    /// `(output path, source)`, or `None` for a commons.
469    pub fn binding_for(&self, platform: Platform) -> Option<(&'static str, &'static str)> {
470        match self.binding {
471            Binding::None => None,
472            Binding::PerPlatform => Some((
473                platform.bynk_binding_filename(),
474                platform.bynk_binding_source(),
475            )),
476            Binding::Fixed { filename, source } => Some((filename, source)),
477            Binding::PerPlatformFiles {
478                cloudflare,
479                node,
480                browser,
481            } => Some(match platform {
482                Platform::Cloudflare => cloudflare,
483                Platform::Node => node,
484                Platform::Browser => browser,
485            }),
486        }
487    }
488}
489
490/// The standard library's first-party units. Dependencies between them are not
491/// listed here: they are the `uses`/`consumes` lines of each unit's own source,
492/// which the checker follows when it injects. The table's order is
493/// [`FIRSTPARTY_SOURCES`]' order; injection follows [`Unit::id_block`].
494pub const UNITS: &[Unit] = &[
495    Unit {
496        name: BYNK_UNIT,
497        kind: UnitKind::Adapter,
498        identity_path: "bynk.bynk",
499        source: BYNK_ADAPTER_SRC,
500        binding: Binding::PerPlatform,
501        id_block: 0,
502        platform: None,
503        env_providers: &["SecretsProvider"],
504        stability: Stability::Stable,
505        experimental: &[],
506        extensible: &["FetchError", "Method"],
507        instantiable: &[],
508    },
509    Unit {
510        name: CLOUDFLARE_UNIT,
511        kind: UnitKind::Adapter,
512        identity_path: "bynk/cloudflare.bynk",
513        source: CLOUDFLARE_ADAPTER_SRC,
514        binding: Binding::Fixed {
515            filename: CLOUDFLARE_BINDING_FILENAME,
516            source: CLOUDFLARE_BINDING,
517        },
518        id_block: 1,
519        platform: Some(Platform::Cloudflare),
520        env_providers: &[
521            "WorkersKv",
522            "WorkersService",
523            "WorkersR2",
524            "WorkersRateLimit",
525        ],
526        stability: Stability::Stable,
527        // Interop I5 (#1972): a Service Binding to a non-Bynk Worker is new
528        // and its surface is untyped, so it lands outside the 1.0 promise.
529        // P5 (#2323): R2 ships experimental until the first-party registry has
530        // run on it (#2308 R6); its conditions are extensible meanwhile.
531        // P3 (#2342): RateLimit too, until the registry has run on it.
532        // L7 (#2414): EdgeCache likewise.
533        experimental: &["Service", "R2", "RateLimit", "EdgeCache"],
534        extensible: &["R2Condition"],
535        instantiable: &[
536            Instantiable {
537                capability: "Kv",
538                binding_prefix: KV_BINDING_NAME,
539                options: &[],
540                required: &[],
541                bare: true,
542            },
543            Instantiable {
544                capability: "Service",
545                binding_prefix: SERVICE_BINDING_PREFIX,
546                options: &[(SERVICE_WORKER_OPTION, OptionKind::Str)],
547                required: &[SERVICE_WORKER_OPTION],
548                bare: false,
549            },
550            Instantiable {
551                capability: "R2",
552                binding_prefix: R2_BINDING_PREFIX,
553                options: &[(R2_JURISDICTION_OPTION, OptionKind::Str)],
554                required: &[],
555                bare: false,
556            },
557            Instantiable {
558                capability: "RateLimit",
559                binding_prefix: RATELIMIT_BINDING_PREFIX,
560                options: &[
561                    (RATELIMIT_LIMIT_OPTION, OptionKind::PositiveInt),
562                    (RATELIMIT_PERIOD_OPTION, OptionKind::Duration),
563                ],
564                required: &[RATELIMIT_LIMIT_OPTION, RATELIMIT_PERIOD_OPTION],
565                bare: false,
566            },
567            Instantiable {
568                capability: "EdgeCache",
569                binding_prefix: EDGE_CACHE_BINDING_PREFIX,
570                options: &[],
571                required: &[],
572                bare: false,
573            },
574        ],
575    },
576    Unit {
577        name: LIST_UNIT,
578        kind: UnitKind::Commons,
579        identity_path: "bynk/list.bynk",
580        source: BYNK_LIST_SRC,
581        binding: Binding::None,
582        id_block: 3,
583        platform: None,
584        env_providers: &[],
585        stability: Stability::Stable,
586        experimental: &[],
587        extensible: &[],
588        instantiable: &[],
589    },
590    Unit {
591        name: MAP_UNIT,
592        kind: UnitKind::Commons,
593        identity_path: "bynk/map.bynk",
594        source: BYNK_MAP_SRC,
595        binding: Binding::None,
596        id_block: 2,
597        platform: None,
598        env_providers: &[],
599        stability: Stability::Stable,
600        experimental: &[],
601        extensible: &[],
602        instantiable: &[],
603    },
604    Unit {
605        name: STRING_UNIT,
606        kind: UnitKind::Commons,
607        identity_path: "bynk/string.bynk",
608        source: BYNK_STRING_SRC,
609        binding: Binding::None,
610        id_block: 4,
611        platform: None,
612        env_providers: &[],
613        stability: Stability::Stable,
614        experimental: &[],
615        extensible: &[],
616        instantiable: &[],
617    },
618    Unit {
619        name: LOCALE_UNIT,
620        kind: UnitKind::Commons,
621        identity_path: "bynk/locale.bynk",
622        source: BYNK_LOCALE_SRC,
623        binding: Binding::None,
624        id_block: 6,
625        platform: None,
626        env_providers: &[],
627        stability: Stability::Stable,
628        experimental: &[],
629        extensible: &[],
630        instantiable: &[],
631    },
632    Unit {
633        name: LOCALE_TYPES_UNIT,
634        kind: UnitKind::Commons,
635        identity_path: "bynk/locale/types.bynk",
636        source: BYNK_LOCALE_TYPES_SRC,
637        binding: Binding::None,
638        id_block: 5,
639        platform: None,
640        env_providers: &[],
641        stability: Stability::Stable,
642        experimental: &[],
643        extensible: &[],
644        instantiable: &[],
645    },
646    Unit {
647        name: CRYPTO_UNIT,
648        kind: UnitKind::Adapter,
649        identity_path: "bynk/crypto.bynk",
650        source: BYNK_CRYPTO_SRC,
651        binding: Binding::PerPlatformFiles {
652            cloudflare: (
653                "bynk/crypto-cloudflare.binding.ts",
654                CRYPTO_CLOUDFLARE_BINDING,
655            ),
656            node: ("bynk/crypto-node.binding.ts", CRYPTO_NODE_BINDING),
657            browser: ("bynk/crypto-browser.binding.ts", CRYPTO_BROWSER_BINDING),
658        },
659        id_block: 7,
660        platform: None,
661        env_providers: &[],
662        // Experimental until the first-party registry has signed with it in
663        // production (#2308 R6), as P5's R2 does.
664        stability: Stability::Experimental,
665        experimental: &[],
666        extensible: &["Digest", "Signature", "CryptoError"],
667        instantiable: &[],
668    },
669];
670
671/// The registry entry for `name`, if it is a first-party unit.
672pub fn unit(name: &str) -> Option<&'static Unit> {
673    UNITS.iter().find(|u| u.name == name)
674}
675
676/// The unit a dotted item path lies in, and the rest of the path relative to it
677/// (empty for the unit itself). Unit names contain dots, so the longest unit
678/// name that is a whole-segment prefix wins: `bynk.cloudflare.Kv` is in
679/// `bynk.cloudflare`, not in `bynk`.
680pub fn split_item_path(path: &str) -> Option<(&'static Unit, &str)> {
681    split_item_path_in(UNITS, path)
682}
683
684/// [`split_item_path`] over a given table (tests pass a synthetic one).
685pub fn split_item_path_in<'u, 'p>(units: &'u [Unit], path: &'p str) -> Option<(&'u Unit, &'p str)> {
686    units
687        .iter()
688        .filter_map(|u| {
689            if path == u.name {
690                Some((u, ""))
691            } else {
692                path.strip_prefix(u.name)?
693                    .strip_prefix('.')
694                    .map(|rest| (u, rest))
695            }
696        })
697        .max_by_key(|(u, _)| u.name.len())
698}
699
700/// Whether `path` is `prefix` or lies under it, by whole dotted segments.
701pub fn covers(prefix: &str, path: &str) -> bool {
702    path == prefix
703        || path
704            .strip_prefix(prefix)
705            .is_some_and(|rest| rest.starts_with('.'))
706}
707
708/// The stability of a first-party item: a unit (`bynk.cloudflare`), an
709/// exported item (`bynk.cloudflare.Kv`) or a capability operation
710/// (`bynk.cloudflare.Kv.list`). An item in an experimental unit, or under an
711/// experimental item, is experimental. `None` when no first-party unit holds
712/// the path.
713pub fn stability_of(path: &str) -> Option<Stability> {
714    stability_of_in(UNITS, path)
715}
716
717/// [`stability_of`] over a given table.
718pub fn stability_of_in(units: &[Unit], path: &str) -> Option<Stability> {
719    let (unit, rest) = split_item_path_in(units, path)?;
720    if unit.stability == Stability::Experimental
721        || unit.experimental.iter().any(|item| covers(item, rest))
722    {
723        Some(Stability::Experimental)
724    } else {
725        Some(Stability::Stable)
726    }
727}
728
729/// Every experimental item, as a full path: each experimental unit, and each
730/// listed item of a stable one.
731pub fn experimental_items() -> Vec<String> {
732    experimental_items_in(UNITS)
733}
734
735/// [`experimental_items`] over a given table.
736pub fn experimental_items_in(units: &[Unit]) -> Vec<String> {
737    let mut out = Vec::new();
738    for u in units {
739        if u.stability == Stability::Experimental {
740            out.push(u.name.to_string());
741        }
742        out.extend(
743            u.experimental
744                .iter()
745                .map(|item| format!("{}.{item}", u.name)),
746        );
747    }
748    out
749}
750
751/// Whether an `[unstable] allow` list covers `path`: an entry covers itself and
752/// everything under it.
753pub fn allows(allow: &[String], path: &str) -> bool {
754    allow.iter().any(|entry| covers(entry, path))
755}
756
757/// Whether `entry`, an `[unstable] allow` entry, reaches anything in
758/// `experimental` (a list of experimental item paths, such as
759/// [`experimental_items`]): it names an experimental item, lies under one, or
760/// contains one. An entry that reaches nothing is stale.
761pub fn allow_entry_is_live(experimental: &[String], entry: &str) -> bool {
762    experimental
763        .iter()
764        .any(|item| covers(item, entry) || covers(entry, item))
765}
766
767/// The instance kind `capability` of `unit` is, if a context may declare named
768/// instances of it (S4a, #1966).
769pub fn instantiable(unit: &str, capability: &str) -> Option<&'static Instantiable> {
770    self::unit(unit)?
771        .instantiable
772        .iter()
773        .find(|i| i.capability == capability)
774}
775
776/// Whether `name`, an enum exported by `unit`, is extensible.
777pub fn is_extensible(unit: &str, name: &str) -> bool {
778    is_extensible_in(UNITS, unit, name)
779}
780
781/// [`is_extensible`] over a given table.
782pub fn is_extensible_in(units: &[Unit], unit: &str, name: &str) -> bool {
783    units
784        .iter()
785        .any(|u| u.name == unit && u.extensible.contains(&name))
786}
787
788/// The names a first-party unit exports: those on its `exports … { … }` lines
789/// (an adapter) and its own `fn`s and `type`s (a commons). Read from the
790/// source, so the list cannot fall behind it.
791pub fn exported_names(unit: &Unit) -> Vec<&'static str> {
792    let mut out = Vec::new();
793    for line in unit.source.lines() {
794        let trimmed = line.trim_start();
795        if let Some(rest) = trimmed.strip_prefix("exports ")
796            && let Some((_, list)) = rest.split_once('{')
797            && let Some((names, _)) = list.split_once('}')
798        {
799            out.extend(names.split(',').map(str::trim).filter(|n| !n.is_empty()));
800        } else if unit.kind == UnitKind::Commons
801            // A commons' own declarations: at column 0 in the flat form, one tab
802            // in the braced `commons bynk.list { … }` form the first-party
803            // sources use. Nothing deeper is a declaration.
804            && (line == trimmed || line.strip_prefix('\t') == Some(trimmed))
805        {
806            for keyword in ["fn ", "type "] {
807                if let Some(rest) = trimmed.strip_prefix(keyword) {
808                    let end = rest
809                        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
810                        .unwrap_or(rest.len());
811                    if end > 0 {
812                        out.push(&rest[..end]);
813                    }
814                }
815            }
816        }
817    }
818    out
819}
820
821/// Whether `path` names a first-party unit or an item it exports. Operation
822/// paths (`bynk.cloudflare.Kv.list`) are accepted when their item exists.
823pub fn names_first_party_item(path: &str) -> bool {
824    names_first_party_item_in(UNITS, path)
825}
826
827/// [`names_first_party_item`] over a given table.
828pub fn names_first_party_item_in(units: &[Unit], path: &str) -> bool {
829    match split_item_path_in(units, path) {
830        None => false,
831        Some((_, "")) => true,
832        Some((unit, rest)) => {
833            let item = rest.split('.').next().unwrap_or(rest);
834            exported_names(unit).contains(&item)
835        }
836    }
837}
838
839#[cfg(test)]
840mod tests {
841    use super::*;
842
843    /// A synthetic registry with an experimental unit, an experimental item
844    /// and an experimental operation inside stable units.
845    const SYNTH: &[Unit] = &[
846        Unit {
847            name: "bynk",
848            kind: UnitKind::Adapter,
849            identity_path: "bynk.bynk",
850            source: "adapter bynk {\n\texports capability { Clock, Fetch }\n\texports transparent { FetchError }\n}\n",
851            binding: Binding::PerPlatform,
852            id_block: 0,
853            platform: None,
854            env_providers: &[],
855            stability: Stability::Stable,
856            experimental: &["Fetch.stream"],
857            extensible: &["FetchError"],
858            instantiable: &[],
859        },
860        Unit {
861            name: "bynk.cloudflare",
862            kind: UnitKind::Adapter,
863            identity_path: "bynk/cloudflare.bynk",
864            source: "adapter bynk.cloudflare {\n\texports capability { Kv, Ai }\n}\n",
865            binding: Binding::None,
866            id_block: 1,
867            platform: Some(Platform::Cloudflare),
868            env_providers: &[],
869            stability: Stability::Stable,
870            experimental: &["Ai"],
871            extensible: &[],
872            instantiable: &[],
873        },
874        Unit {
875            name: "bynk.cloudflare.d1",
876            kind: UnitKind::Adapter,
877            identity_path: "bynk/cloudflare/d1.bynk",
878            source: "adapter bynk.cloudflare.d1 {\n\texports capability { D1 }\n}\n",
879            binding: Binding::None,
880            id_block: 2,
881            platform: Some(Platform::Cloudflare),
882            env_providers: &[],
883            stability: Stability::Experimental,
884            experimental: &[],
885            extensible: &[],
886            instantiable: &[],
887        },
888        Unit {
889            name: "bynk.text",
890            kind: UnitKind::Commons,
891            identity_path: "bynk/text.bynk",
892            source: "commons bynk.text\n\ntype Slug = String\n\nfn shout(s: String) -> String {\n\ts\n}\n",
893            binding: Binding::None,
894            id_block: 3,
895            platform: None,
896            env_providers: &[],
897            stability: Stability::Stable,
898            experimental: &[],
899            extensible: &[],
900            instantiable: &[],
901        },
902    ];
903
904    #[test]
905    fn item_paths_resolve_to_the_longest_unit() {
906        let unit_of = |p| split_item_path_in(SYNTH, p).map(|(u, rest)| (u.name, rest));
907        assert_eq!(unit_of("bynk"), Some(("bynk", "")));
908        assert_eq!(unit_of("bynk.Fetch.send"), Some(("bynk", "Fetch.send")));
909        assert_eq!(
910            unit_of("bynk.cloudflare.Kv"),
911            Some(("bynk.cloudflare", "Kv"))
912        );
913        assert_eq!(
914            unit_of("bynk.cloudflare.d1.D1"),
915            Some(("bynk.cloudflare.d1", "D1"))
916        );
917        assert_eq!(unit_of("bynkx"), None, "a whole-segment prefix only");
918        assert_eq!(unit_of("user.unit"), None);
919    }
920
921    #[test]
922    fn stability_follows_unit_item_and_operation() {
923        let st = |p| stability_of_in(SYNTH, p);
924        use Stability::*;
925        assert_eq!(st("bynk.Clock"), Some(Stable));
926        assert_eq!(st("bynk.Fetch.send"), Some(Stable));
927        assert_eq!(
928            st("bynk.Fetch.stream"),
929            Some(Experimental),
930            "an experimental operation"
931        );
932        assert_eq!(
933            st("bynk.Fetch"),
934            Some(Stable),
935            "its capability stays stable"
936        );
937        assert_eq!(
938            st("bynk.cloudflare.Ai"),
939            Some(Experimental),
940            "an experimental item"
941        );
942        assert_eq!(
943            st("bynk.cloudflare.Ai.run"),
944            Some(Experimental),
945            "its operations too"
946        );
947        assert_eq!(st("bynk.cloudflare.Kv"), Some(Stable));
948        assert_eq!(
949            st("bynk.cloudflare.d1"),
950            Some(Experimental),
951            "an experimental unit"
952        );
953        assert_eq!(st("bynk.cloudflare.d1.D1.query"), Some(Experimental));
954        assert_eq!(st("user.unit"), None);
955    }
956
957    #[test]
958    fn allow_entries_cover_by_whole_segment_prefix() {
959        let allow = vec![
960            "bynk.cloudflare.Ai".to_string(),
961            "bynk.cloudflare.d1".to_string(),
962        ];
963        assert!(allows(&allow, "bynk.cloudflare.Ai"));
964        assert!(allows(&allow, "bynk.cloudflare.Ai.run"));
965        assert!(allows(&allow, "bynk.cloudflare.d1.D1.query"));
966        assert!(
967            !allows(&allow, "bynk.cloudflare.AiX"),
968            "not a segment prefix"
969        );
970        assert!(!allows(&allow, "bynk.Fetch.stream"));
971        assert!(!allows(&[], "bynk.cloudflare.Ai"));
972    }
973
974    #[test]
975    fn an_allow_entry_is_live_while_it_reaches_something_experimental() {
976        let synth = experimental_items_in(SYNTH);
977        let live = |e| allow_entry_is_live(&synth, e);
978        assert!(live("bynk.cloudflare.Ai"));
979        assert!(live("bynk.cloudflare.Ai.run"), "under an experimental item");
980        assert!(live("bynk.cloudflare"), "contains an experimental item");
981        assert!(live("bynk.Fetch.stream"));
982        assert!(live("bynk"), "contains an experimental operation");
983        assert!(!live("bynk.cloudflare.Kv"), "stable: a stale entry");
984        assert!(!live("bynk.text"));
985        assert_eq!(
986            experimental_items_in(SYNTH),
987            [
988                "bynk.Fetch.stream",
989                "bynk.cloudflare.Ai",
990                "bynk.cloudflare.d1"
991            ]
992        );
993    }
994
995    #[test]
996    fn exported_names_and_item_existence_come_from_the_sources() {
997        assert_eq!(exported_names(&SYNTH[0]), ["Clock", "Fetch", "FetchError"]);
998        assert_eq!(exported_names(&SYNTH[3]), ["Slug", "shout"]);
999        let names = |p| names_first_party_item_in(SYNTH, p);
1000        assert!(names("bynk.cloudflare"));
1001        assert!(names("bynk.cloudflare.Ai"));
1002        assert!(
1003            names("bynk.cloudflare.Ai.run"),
1004            "an operation of an existing item"
1005        );
1006        assert!(names("bynk.text.shout"));
1007        assert!(!names("bynk.cloudflare.Aii"), "a typo");
1008        assert!(!names("user.unit"));
1009    }
1010
1011    #[test]
1012    fn extensibility_is_by_unit_and_name() {
1013        assert!(is_extensible_in(SYNTH, "bynk", "FetchError"));
1014        assert!(
1015            !is_extensible_in(SYNTH, "user.app", "FetchError"),
1016            "a user's own FetchError"
1017        );
1018        assert!(!is_extensible_in(SYNTH, "bynk", "Method"));
1019    }
1020
1021    /// The shipped instantiable kinds: `bynk.cloudflare`'s `Kv` (S4a, #1966),
1022    /// binding as `KV_<NAME>` with no creation options, and its `Service`
1023    /// (interop I5, #1972), binding as `SERVICE_<NAME>` and naming its Worker
1024    /// with a required `@worker`, never usable bare. Each one is a capability
1025    /// its unit exports.
1026    #[test]
1027    fn the_shipped_instantiable_kinds_are_pinned() {
1028        let kinds: Vec<(&str, &str, &str)> = UNITS
1029            .iter()
1030            .flat_map(|u| {
1031                u.instantiable
1032                    .iter()
1033                    .map(move |i| (u.name, i.capability, i.binding_prefix))
1034            })
1035            .collect();
1036        assert_eq!(
1037            kinds,
1038            [
1039                ("bynk.cloudflare", "Kv", "KV"),
1040                ("bynk.cloudflare", "Service", "SERVICE"),
1041                ("bynk.cloudflare", "R2", "R2"),
1042                ("bynk.cloudflare", "RateLimit", "RATELIMIT"),
1043                ("bynk.cloudflare", "EdgeCache", "EDGE_CACHE")
1044            ]
1045        );
1046        let kv = instantiable("bynk.cloudflare", "Kv").expect("Kv is instantiable");
1047        assert!(kv.options.is_empty() && kv.required.is_empty() && kv.bare);
1048        let service = instantiable("bynk.cloudflare", "Service").expect("Service is instantiable");
1049        assert_eq!(service.option_names().collect::<Vec<_>>(), ["worker"]);
1050        assert_eq!(service.required, ["worker"]);
1051        assert!(!service.bare);
1052        let r2 = instantiable("bynk.cloudflare", "R2").expect("R2 is instantiable");
1053        assert_eq!(r2.option_names().collect::<Vec<_>>(), ["jurisdiction"]);
1054        assert!(r2.required.is_empty() && !r2.bare);
1055        let rl = instantiable("bynk.cloudflare", "RateLimit").expect("RateLimit is instantiable");
1056        assert_eq!(rl.option_kind("limit"), Some(OptionKind::PositiveInt));
1057        assert_eq!(rl.option_kind("period"), Some(OptionKind::Duration));
1058        assert_eq!(rl.required, ["limit", "period"]);
1059        assert!(!rl.bare);
1060        let edge = instantiable("bynk.cloudflare", "EdgeCache").expect("EdgeCache is instantiable");
1061        assert!(edge.options.is_empty() && !edge.bare);
1062        for u in UNITS {
1063            for i in u.instantiable {
1064                assert!(
1065                    i.required.iter().all(|r| i.option_kind(r).is_some()),
1066                    "{}.{}: a required option must be an option",
1067                    u.name,
1068                    i.capability
1069                );
1070            }
1071        }
1072        assert!(exported_names(unit("bynk.cloudflare").unwrap()).contains(&"Kv"));
1073        assert!(exported_names(unit("bynk.cloudflare").unwrap()).contains(&"Service"));
1074        assert_eq!(instantiable("bynk", "Clock"), None);
1075        assert_eq!(instantiable("bynk.cloudflare", "Nope"), None);
1076    }
1077
1078    /// The shipped registry: every unit is stable (S3 ships the mechanism,
1079    /// #1963 Decision C) but `bynk.crypto` (K4), which is experimental until the
1080    /// first-party registry has signed with it in production. The one
1081    /// experimental item inside a stable unit is `bynk.cloudflare`'s `Service`
1082    /// (interop I5, #1972), and the growing enums are extensible. A slice that
1083    /// marks an item experimental updates this test, so the change is visible
1084    /// in review.
1085    #[test]
1086    fn the_shipped_stability_is_pinned() {
1087        for u in UNITS {
1088            let expected = if u.name == CRYPTO_UNIT {
1089                Stability::Experimental
1090            } else {
1091                Stability::Stable
1092            };
1093            assert_eq!(u.stability, expected, "{}", u.name);
1094        }
1095        assert_eq!(
1096            experimental_items(),
1097            [
1098                "bynk.cloudflare.Service",
1099                "bynk.cloudflare.R2",
1100                "bynk.cloudflare.RateLimit",
1101                "bynk.cloudflare.EdgeCache",
1102                "bynk.crypto"
1103            ]
1104        );
1105        let extensible: Vec<(&str, &str)> = UNITS
1106            .iter()
1107            .flat_map(|u| u.extensible.iter().map(move |e| (u.name, *e)))
1108            .collect();
1109        assert_eq!(
1110            extensible,
1111            [
1112                ("bynk", "FetchError"),
1113                ("bynk", "Method"),
1114                ("bynk.cloudflare", "R2Condition"),
1115                ("bynk.crypto", "Digest"),
1116                ("bynk.crypto", "Signature"),
1117                ("bynk.crypto", "CryptoError"),
1118            ]
1119        );
1120        for (unit, name) in extensible {
1121            assert!(
1122                exported_names(self::unit(unit).unwrap()).contains(&name),
1123                "{unit} lists {name} as extensible but does not export it"
1124            );
1125        }
1126        assert!(names_first_party_item("bynk.cloudflare.Kv.list"));
1127        assert!(names_first_party_item("bynk.list.reverse"));
1128        assert!(!names_first_party_item("bynk.cloudflare.Kvv"));
1129    }
1130
1131    /// #1958: `WorkersKv` reads the namespace at the name every generated
1132    /// Worker declares it under (`[[kv_namespaces]] binding`, its `Env`), the
1133    /// one TypeScript literal no Rust constructor can supply. Since S4a (#1966)
1134    /// the name is a constructor parameter, so a derived capability's instance
1135    /// can pass its own; the bare `Kv`'s is the parameter's default.
1136    ///
1137    /// Matched as a whole identifier, then by its neighbours, so the test
1138    /// ignores formatting but not a rename: `KVX` is not `KV` (review of
1139    /// #1962).
1140    #[test]
1141    fn the_cloudflare_binding_reads_kv_binding_name() {
1142        let ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$';
1143        let src = CLOUDFLARE_BINDING;
1144        let uses: Vec<(&str, &str)> = src
1145            .match_indices(KV_BINDING_NAME)
1146            .map(|(at, name)| (&src[..at], &src[at + name.len()..]))
1147            .filter(|(before, after)| !before.ends_with(ident) && !after.starts_with(ident))
1148            .collect();
1149        assert!(
1150            uses.iter().any(|(b, a)| {
1151                b.trim_end().ends_with("binding: string = \"") && a.starts_with('"')
1152            }),
1153            "the constructor's `binding` no longer defaults to \"{KV_BINDING_NAME}\""
1154        );
1155        assert!(
1156            src.contains("?.[this.binding]"),
1157            "the namespace is no longer read at `env[binding]`"
1158        );
1159    }
1160
1161    /// Each unit's `ExprId` block is permanent: emitted output and the
1162    /// process-wide parse cache depend on it. These are the blocks the
1163    /// hand-written injection used before the registry (S1, #1945); a new
1164    /// unit takes a new block and never moves one of these.
1165    #[test]
1166    fn id_blocks_are_pinned_and_distinct() {
1167        let blocks: Vec<(&str, u32)> = UNITS.iter().map(|u| (u.name, u.id_block)).collect();
1168        assert_eq!(
1169            blocks,
1170            [
1171                ("bynk", 0),
1172                ("bynk.cloudflare", 1),
1173                ("bynk.list", 3),
1174                ("bynk.map", 2),
1175                ("bynk.string", 4),
1176                ("bynk.locale", 6),
1177                ("bynk.locale.types", 5),
1178                ("bynk.crypto", 7),
1179            ]
1180        );
1181        let mut sorted: Vec<u32> = UNITS.iter().map(|u| u.id_block).collect();
1182        sorted.sort_unstable();
1183        sorted.dedup();
1184        assert_eq!(sorted.len(), UNITS.len(), "two units share an id block");
1185    }
1186
1187    /// Hover and completion read [`FIRSTPARTY_SOURCES`] in order, so it is
1188    /// pinned to the order the hand-written list had.
1189    #[test]
1190    fn firstparty_sources_keep_their_order() {
1191        let names: Vec<&str> = FIRSTPARTY_SOURCES.iter().map(|(n, _)| *n).collect();
1192        assert_eq!(
1193            names,
1194            [
1195                "bynk",
1196                "bynk.cloudflare",
1197                "bynk.list",
1198                "bynk.map",
1199                "bynk.string",
1200                "bynk.locale",
1201                "bynk.locale.types",
1202                "bynk.crypto",
1203            ]
1204        );
1205        for (unit, (name, source)) in UNITS.iter().zip(FIRSTPARTY_SOURCES) {
1206            assert_eq!((unit.name, unit.source), (*name, *source));
1207        }
1208    }
1209
1210    /// The views over the table answer as the hand-written matches did.
1211    #[test]
1212    fn metadata_views_match_the_previous_answers() {
1213        assert_eq!(platform_of("bynk.cloudflare"), Some(Platform::Cloudflare));
1214        for name in [
1215            "bynk",
1216            "bynk.list",
1217            "bynk.map",
1218            "bynk.string",
1219            "bynk.locale",
1220            "user.unit",
1221        ] {
1222            assert_eq!(platform_of(name), None, "{name}");
1223        }
1224        assert!(provider_takes_env("bynk", "SecretsProvider"));
1225        assert!(provider_takes_env("bynk.cloudflare", "WorkersKv"));
1226        assert!(!provider_takes_env("bynk", "WorkersKv"));
1227        assert!(!provider_takes_env("bynk.cloudflare", "SecretsProvider"));
1228        assert!(!provider_takes_env("bynk", "ClockProvider"));
1229        assert!(!provider_takes_env("user.unit", "SecretsProvider"));
1230    }
1231
1232    /// An adapter carries a binding and a commons does not, and every name and
1233    /// identity path is unique, every name inside the reserved prefix.
1234    #[test]
1235    fn entries_are_well_formed() {
1236        for u in UNITS {
1237            assert!(
1238                u.name == "bynk" || u.name.starts_with("bynk."),
1239                "{}",
1240                u.name
1241            );
1242            assert_eq!(
1243                UNITS.iter().filter(|o| o.name == u.name).count(),
1244                1,
1245                "{}",
1246                u.name
1247            );
1248            // Two entries under one identity path would be two parsed units
1249            // that diagnostics and emission cannot tell apart.
1250            assert_eq!(
1251                UNITS
1252                    .iter()
1253                    .filter(|o| o.identity_path == u.identity_path)
1254                    .count(),
1255                1,
1256                "{}",
1257                u.identity_path
1258            );
1259            match u.kind {
1260                UnitKind::Adapter => assert_ne!(u.binding, Binding::None, "{}", u.name),
1261                UnitKind::Commons => {
1262                    assert_eq!(u.binding, Binding::None, "{}", u.name);
1263                    assert!(u.env_providers.is_empty(), "{}", u.name);
1264                }
1265            }
1266        }
1267        assert_eq!(
1268            unit("bynk.cloudflare").and_then(|u| u.binding_for(Platform::Node)),
1269            Some((CLOUDFLARE_BINDING_FILENAME, CLOUDFLARE_BINDING))
1270        );
1271        assert_eq!(
1272            unit("bynk").and_then(|u| u.binding_for(Platform::Browser)),
1273            Some(("bynk-browser.ts", BYNK_BROWSER_BINDING))
1274        );
1275        assert_eq!(
1276            unit("bynk.list").and_then(|u| u.binding_for(Platform::Node)),
1277            None
1278        );
1279    }
1280
1281    /// The three `bynk.crypto` bindings are one body with one marked region of
1282    /// platform difference (the constant-time comparison primitive). They are
1283    /// separate files because each ships alone, so this keeps them from drifting.
1284    #[test]
1285    fn the_crypto_bindings_differ_only_in_their_platform_region() {
1286        const START: &str = "// --- platform: constant-time comparison primitive";
1287        const END: &str = "// --- end platform";
1288        fn shared(src: &str) -> String {
1289            let (head, rest) = src.split_once(START).expect("platform region start");
1290            let (_, tail) = rest.split_once(END).expect("platform region end");
1291            // The second header line names the platform.
1292            let head = head.lines().skip(2).collect::<Vec<_>>().join("\n");
1293            format!("{head}\n{tail}")
1294        }
1295        let cloudflare = shared(CRYPTO_CLOUDFLARE_BINDING);
1296        assert_eq!(cloudflare, shared(CRYPTO_NODE_BINDING));
1297        assert_eq!(cloudflare, shared(CRYPTO_BROWSER_BINDING));
1298    }
1299
1300    /// The hardcoded [`BYNK_SURFACE_CAPABILITIES`] must match the adapter's
1301    /// `exports capability { … }` line — otherwise the unknown-name quick-fix
1302    /// (#852) would offer a stale `consumes bynk { … }` set.
1303    #[test]
1304    fn bynk_surface_capabilities_match_the_adapter() {
1305        let src = BYNK_ADAPTER_SRC;
1306        let line = src
1307            .lines()
1308            .find(|l| l.trim_start().starts_with("exports capability {"))
1309            .expect("adapter declares `exports capability`");
1310        let inner = line
1311            .split_once('{')
1312            .and_then(|(_, r)| r.split_once('}'))
1313            .map(|(names, _)| names)
1314            .expect("braced capability list");
1315        let declared: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
1316        assert_eq!(
1317            declared, BYNK_SURFACE_CAPABILITIES,
1318            "BYNK_SURFACE_CAPABILITIES is out of sync with bynk.bynk"
1319        );
1320    }
1321}