Skip to main content

portaki_sdk_macros/
lib.rs

1//! Proc-macros that declare Portaki Wasm module metadata at compile time.
2//!
3//! Each macro prepends an invisible `const` block (via `emit::write_emission`) that writes a
4//! JSON fragment when `OUT_DIR` is set during `cargo build` — Cargo sets it only for a crate
5//! with a build script, so a module keeps a `build.rs` (`fn main() {}` is enough). A wasm32 build
6//! without one fails at `portaki_module!` with that advice. Fragments land under:
7//!
8//! ```text
9//! {OUT_DIR}/portaki-emissions/{kind}-{sanitized_key}.json
10//! ```
11//!
12//! where `OUT_DIR` is Cargo's per-crate build output directory (e.g.
13//! `target/debug/build/<crate-hash>/out/` for host builds, or the analogous path under
14//! `target/wasm32-unknown-unknown/` for Wasm targets).
15//!
16//! # Build pipeline
17//!
18//! 1. Module source uses these macros (typically via `portaki_sdk::prelude::*` re-exports).
19//! 2. `cargo build --target wasm32-unknown-unknown` expands macros and writes emission files.
20//! 3. [`portaki build`](https://docs.rs/portaki-cli) calls `find_emissions_dir`, which picks the
21//!    **most recently modified** `portaki-emissions` directory under `target/`, then
22//!    `collect_emissions` + `generate_manifest` merge fragments into `target/portaki/manifest.json`.
23//! 4. `portaki lint` validates capability ids against the host catalog
24//!    (`portaki_sdk::capability::ALL` / `is_known`), i18n keys, and manifest shape.
25//!
26//! A `portaki.module.json` catalog at the module root can override or supplement emissions; if
27//! neither emissions nor a catalog exist, `portaki build` fails.
28//!
29//! # Emission kinds
30//!
31//! | Macro | `kind` field | Filename pattern |
32//! |-------|--------------|------------------|
33//! | `portaki_module` | `module` | `module-{id}.json` |
34//! | `entity` | `entity` | `entity-{StructName}.json` |
35//! | `entity_indexes` | `entity_indexes` | `entity_indexes-{EntityName}.json` |
36//! | `surface` | `surface` | `surface-{context}_{id}.json` |
37//! | `query` | `query` | `query-{name}.json` |
38//! | `command` | `command` | `command-{name}.json` |
39//! | `params` | `params` | `params-{TypeName}.json` |
40//! | `config` | `config` (+ `query` `legacyConfig`, `command` `legacyConfigAdopted`) | `config-{StructName}.json` |
41//! | `email_vars` | `email_vars` (+ `query` `emailContext`) | `email_vars-emailContext.json` |
42//! | `email_blocks` | `email_blocks` (+ `query` `emailContext`) | `email_blocks-emailContext.json` |
43//! | `event_handler` | `event_handler` | `event_handler-{event_type}.json` |
44//! | `capability` | `capability` | `capability-{id}.json` |
45//! | `connector` | `connector_builtin` | `connector_builtin-{builtin}.json` |
46//! | `custom_connector` | `connector_custom` | `connector_custom-{id}.json` |
47//! | `connector_op` | `connector_op` | `connector_op-{fn_name}.json` |
48//!
49//! `entity_indexes` emissions are written for Atlas/migration tooling; they are **not** merged into
50//! `manifest.json` today (only `entity` field metadata is).
51//!
52//! # Wasm runtime code generation
53//!
54//! `portaki_module` additionally emits Extism export shims (`portaki_query`, `portaki_command`) and
55//! a `__getrandom_v03_custom` hook when `target_arch = "wasm32"`.
56//!
57//! `query`, `command`, and `surface` emit `inventory::submit!` handler registrations that wire
58//! manifest operation names to the annotated Rust function via JSON dispatch — a
59//! `HandlerRegistration` on `wasm32`, a `HandlerDeclaration` (with the handler's kind and surface
60//! context) on native targets, where the test-utils conformance battery reads it.
61
62#![deny(missing_docs)]
63
64mod bundle;
65mod capability;
66mod command;
67mod config;
68mod connector;
69mod email;
70mod email_blocks;
71mod email_vars;
72mod emit;
73mod entity;
74mod event_handler;
75mod layout;
76mod link;
77mod module;
78mod nav;
79mod params;
80mod query;
81mod resource;
82mod surface;
83mod typed;
84mod wasm_handler;
85mod wire;
86mod wire_lit;
87
88use proc_macro::TokenStream;
89
90/// A text of the module's own bundles, in every language they have — an `I18nText`.
91///
92/// Re-exported as `portaki_sdk::bundle_text!`. The bundles are found at compile time: every
93/// `i18n/*.json`, then every `email_i18n/*.json`, under the crate root (the language is the file
94/// name's first part: `fr-FR.json`, `fr.json` → `fr`). No hand-kept `include_str!` list. A key in
95/// both folders takes the `i18n/` text.
96///
97/// ```ignore
98/// let title = bundle_text!("stats.tile.title");                       // I18nText
99/// let body = bundle_text!("email.syncFailed.body", &[("source", name)]); // {source} filled in
100/// let subject: LocalizedEmailText = bundle_text!("email.subject").into();
101/// let shown = title.for_ctx(&ctx);                                     // the reader's language
102/// ```
103///
104/// A key written as a literal must exist in at least one bundle — a typo is a compile error,
105/// not a key shown to the guest. A key computed at run time is looked up then.
106#[proc_macro]
107pub fn bundle_text(input: TokenStream) -> TokenStream {
108    bundle::expand(input)
109}
110
111/// Declares module identity and bootstraps Wasm exports.
112///
113/// # Forms
114///
115/// **Function-like (recommended)** — invoke once at the root of `lib.rs` (re-exported as
116/// `portaki_sdk::portaki_module!`):
117///
118/// ```ignore
119/// portaki_sdk::portaki_module!(
120///     id = "weather",
121///     display_name_key = "module.displayName",
122///     description_key = "module.description",
123///     author = "Portaki",
124///     version = "1.0.0", // optional; defaults to compiling crate's CARGO_PKG_VERSION
125/// );
126/// ```
127///
128/// **Attribute** — attach to a `mod` item (same attribute keys). Rarely used; prefer the
129/// function-like form at crate root.
130///
131/// ```ignore
132/// #[portaki_sdk_macros::portaki_module(id = "weather")]
133/// mod internal { /* ... */ }
134/// ```
135///
136/// # Attributes
137///
138/// | Key | Required | Default |
139/// |-----|----------|---------|
140/// | `id` | no | `"unknown"` |
141/// | `display_name_key` | no | `"module.displayName"` |
142/// | `description_key` | no | `"module.description"` |
143/// | `author` | no | `"Portaki"` |
144/// | `version` | no | `CARGO_PKG_VERSION` of the **module crate** (not this proc-macro crate) |
145/// | `icon` | no | — catalog icon name |
146/// | `maturity` | no | — `stable`, `beta`… |
147/// | `module_type` | no | — catalog `type` and `author.type` (`official`…) |
148/// | `author_url` | no | — `author.url` |
149/// | `sort_order` | no | — integer, catalog position |
150/// | `core` | no | — bare flag: a core module of the booklet, installed on every property, always active, no on/off switch, absent from the modules list and the marketplace |
151///
152/// `error = "photo_required"` (repeatable, at most 32, `^[a-z][a-z0-9_]{0,47}$`) declares a code
153/// `portaki_sdk::refuse!` may raise; it lands in the manifest's `errors` and needs the key
154/// `errors.<code>` in every bundle. A module's own error text never reaches the host — it could
155/// carry guest data out — so the host only ever sees a code declared here.
156///
157/// The catalog keys, with the name and description read from the i18n bundles, fill whatever
158/// `portaki.module.json` leaves out — `portaki build` writes them, the author never does.
159///
160/// Unknown keys are a **compile error** (`unknown portaki_module attribute: …`).
161///
162/// # Emission
163///
164/// Writes `module-{id}.json` with `"kind": "module"`, `displayName`, `description`, `author.name`,
165/// `version`, `manifestVersion: "1"`, and `uiSchema: { host: "1", guest: "1" }`.
166///
167/// `portaki build` requires exactly one `module` emission (or a `portaki.module.json` catalog).
168///
169/// # Generated Rust
170///
171/// - `const __PORTAKI_DECLARED_ERRORS` — the `error` codes, which `portaki_sdk::refuse!` checks
172///   at compile time (hence: at the crate root).
173///
174/// # Generated Rust (Wasm only)
175///
176/// - `mod __portaki_wasm_getrandom` — fills random bytes via `portaki_sdk::host::wasm_getrandom`.
177/// - `mod __portaki_wasm_exports` — `#[plugin_fn] portaki_query` / `portaki_command` delegating
178///   to `portaki_sdk::wasm::dispatch`.
179#[proc_macro_attribute]
180pub fn portaki_module(attr: TokenStream, item: TokenStream) -> TokenStream {
181    module::expand(attr, item)
182}
183
184/// Function-like module declaration (`portaki_module!(…)`).
185///
186/// Re-exported from `portaki_sdk` as [`portaki_module`](https://docs.rs/portaki-sdk/latest/portaki_sdk/fn.portaki_module.html).
187/// See [`portaki_module`] (attribute) for attribute keys, defaults, emission shape, and Wasm shims.
188///
189/// Unlike the attribute form, this macro does not wrap a `mod` item — it only emits metadata and
190/// Wasm bootstrap modules.
191#[proc_macro]
192pub fn portaki_module_decl(input: TokenStream) -> TokenStream {
193    module::expand_invocation(input)
194}
195
196/// Declares a persistent entity schema for Atlas and `host::repo`.
197///
198/// # Syntax
199///
200/// ```ignore
201/// #[portaki_sdk::entity(schema_version = 1)]
202/// pub struct WeatherCache {
203///     pub id: uuid::Uuid,
204///     pub lat: f64,
205///     pub lng: f64,
206///     // ...
207/// }
208/// ```
209///
210/// # Attributes
211///
212/// | Key | Required |
213/// |-----|----------|
214/// | `schema_version` | **yes** — positive integer, bumped when the on-disk schema changes |
215///
216/// Missing `schema_version` → **compile error**. Unknown keys → **compile error**.
217///
218/// # Target item
219///
220/// Must be a struct with **named fields**. Tuple/unit structs emit `"fields": []`.
221/// Field types are captured as token strings (e.g. `uuid :: Uuid`), not semantic type names.
222///
223/// # Emission
224///
225/// `entity-{StructName}.json`:
226///
227/// ```json
228/// { "kind": "entity", "name": "WeatherCache", "schemaVersion": 1, "fields": [ … ] }
229/// ```
230///
231/// Merged into `manifest.json` → `entities[]`. `portaki build` uses the max `schemaVersion` across
232/// entities when writing Atlas migration bundles.
233#[proc_macro_attribute]
234pub fn entity(attr: TokenStream, item: TokenStream) -> TokenStream {
235    entity::expand_entity(attr, item)
236}
237
238/// Declares repository indexes for an entity (Atlas spatial/field indexes).
239///
240/// # Syntax
241///
242/// ```ignore
243/// #[portaki_sdk::entity_indexes(WeatherCache)]
244/// pub const WEATHER_CACHE_INDEXES: &[&str] = &["lat", "lng"];
245/// ```
246///
247/// The attribute argument is the entity **type name** (not a string). The decorated item must be a
248/// `const` whose value is a string array literal `&["field", …]` or `&[ "field", … ]`.
249///
250/// Non-literal elements → **compile error** (`entity index entries must be string literals`).
251/// Non-array value → **compile error** (message suggests `&["lat", "lng"]`).
252///
253/// # Index inference
254///
255/// - `lat` + `lng` together → one `"kind": "spatial"` index with both fields.
256/// - Otherwise → one `"kind": "field"` index per entry.
257/// - Empty array → `"indexes": []`.
258///
259/// # Emission
260///
261/// `entity_indexes-{EntityName}.json`. Not merged into `manifest.json` today; consumed by Atlas /
262/// migration tooling. Host and Wasm builds may emit different contents if the const is not visible
263/// to the Wasm compile — `portaki build` picks the latest `portaki-emissions` tree under `target/`.
264#[proc_macro_attribute]
265pub fn entity_indexes(attr: TokenStream, item: TokenStream) -> TokenStream {
266    entity::expand_entity_indexes(attr, item)
267}
268
269/// Declares a host or guest SDUI surface renderer.
270///
271/// # Syntax
272///
273/// ```text
274/// #[portaki_sdk::surface(guest, id = "home.card", display_name_key = "surface.home.card")]
275/// pub fn render_home_card(ctx: GuestContext) -> Surface { /* ... */ }
276///
277/// #[portaki_sdk::surface(host, id = "main")]
278/// pub fn render_host_main(ctx: HostContext) -> Surface { /* ... */ }
279/// ```
280///
281/// # Attributes
282///
283/// | Position | Key | Required |
284/// |----------|-----|----------|
285/// | 1st | `host` or `guest` (identifier) or `"host"` / `"guest"` (string) | yes — surface context |
286/// | 2nd | `id = "…"` or `id = SurfaceId::new("…")` | yes — stable surface id in the manifest |
287/// | 3rd | `display_name_key = "…"` | no — i18n key; omitted from JSON when absent |
288/// | any | `gate = false` | no — guest only: skip the SDK's guest states (see below) |
289///
290/// Where the surface is linked from — its catalogue entry — follows, in any order. Closed lists
291/// take their enum (in the prelude), and a string there does not compile:
292///
293/// | Context | Key | Value |
294/// |---------|-----|-------|
295/// | host | `placement` (repeatable) | `HostPlacement::…` — one entry per placement |
296/// | host | `design_id` | `DesignId::…` |
297/// | host | `icon` | `IconName::…` |
298/// | host | `label_key` | i18n key, checked against every bundle by `portaki build` |
299/// | host | `path` | `pathSegment`; defaults to the module id for `main`, the surface id otherwise |
300/// | guest | `path` | the route — a guest surface without one is rendered, never linked |
301/// | guest | `label_key` | i18n key |
302/// | guest | `role` | `GuestRole::…` |
303/// | guest | `embeds` (repeatable) | `HostFragmentId::…` |
304///
305/// Wrong first token (not `id =`) → **compile error**. Bare const paths are not
306/// resolved at macro time — use a string lit or `Type::new("…")`.
307///
308/// # Target item
309///
310/// A function. Its Rust symbol is recorded as `renderFn`. Return type may be `Surface` or
311/// `Result<Surface, _>`; the Wasm shim serializes the return value with `serde_json::to_value`.
312/// The function itself is left as written: a unit test calls it directly.
313///
314/// # Guest states
315///
316/// A guest surface is rendered through `portaki_sdk::guest_shell`: the shim asks the platform
317/// whether the module is ready and renders the SDK's « inactive » or « incomplete » state without
318/// calling the function when it is not; an `Err` from the function is logged
319/// (`<module>_<surface>_render_failed`) and rendered as the SDK's error state. So a guest
320/// surface is written for the happy path:
321///
322/// ```text
323/// #[portaki_sdk::surface(guest, id = "home.card")]
324/// pub fn render_home_card(ctx: GuestContext) -> Result<Surface> {
325///     let config = Config::load(&ctx)?;
326///     Ok(Surface::new(/* … */))
327/// }
328/// ```
329///
330/// `gate = false` opts a guest surface out: the function is called whatever the status, and an
331/// `Err` reaches the platform as before. Only for a surface that has something to say while the
332/// module is not ready — a card that must stay visible with an incomplete config, or one that
333/// already renders its own states (a module that keeps its `guest/empty.rs`, whose texts keep
334/// the same keys, needs nothing: its function is simply not called when the SDK's state shows).
335/// A host surface is never gated: the dashboard shows the host what to fix.
336///
337/// # Emission
338///
339/// `surface-{context}_{id}.json` → merged into `manifest.surfaces.host` or `.guest`.
340///
341/// # Wasm registration
342///
343/// Emits `inventory::submit!` with `operation_names: &[render_fn_symbol]` for JSON dispatch.
344#[proc_macro_attribute]
345pub fn surface(attr: TokenStream, item: TokenStream) -> TokenStream {
346    surface::expand(attr, item)
347}
348
349/// Declares a read-only gateway query operation.
350///
351/// # Syntax
352///
353/// ```text
354/// #[portaki_sdk::query(name = "getCurrent")]
355/// pub fn get_current(ctx: Context, args: GetCurrentArgs) -> Result<WeatherCurrent> { /* ... */ }
356/// ```
357///
358/// # Attributes
359///
360/// | Key | Required |
361/// |-----|----------|
362/// | `name = "…"` | yes — gateway-visible operation name (camelCase convention) |
363/// | `guest` | no — bare flag: a guest may call it through the guest gateway. Absent, the platform refuses a guest with `operation_not_guest_callable` |
364/// | `example(label = "…", input = r#"{…}"#)` | no, repeatable — a ready-made call the sandbox's Exécuter tab offers (`dispatchExamples` of the manifest). `input` is a JSON object, checked at compile time; omitted, `{}` |
365///
366/// Wrong key → **compile error** (`expected name = "…"`).
367///
368/// # Target item
369///
370/// A function with signature `(Context, …) -> Result<T>` where the second parameter is optional:
371///
372/// - `(ctx: Context)` — no JSON params deserialized.
373/// - `(ctx: Context, args: Args)` — `args` deserialized from the Wasm `params` JSON object.
374///
375/// Handlers must not take `self`. Missing context parameter **panics at macro expansion** (proc-macro
376/// panic, not `compile_error`).
377///
378/// # Emission
379///
380/// `query-{name}.json` → `manifest.queries[]` with `{ name, fn, guest }`, and each `example` →
381/// `manifest.dispatchExamples[]` with `{ kind, name, title, input }` — `title` carries `label`.
382///
383/// # Wasm registration
384///
385/// `inventory::submit!` registers both the manifest `name` and the Rust `fn` symbol for dispatch.
386#[proc_macro_attribute]
387pub fn query(attr: TokenStream, item: TokenStream) -> TokenStream {
388    query::expand(attr, item)
389}
390
391/// Declares a mutating gateway command operation.
392///
393/// # Syntax
394///
395/// ```text
396/// #[portaki_sdk::command(name = "refreshForecast")]
397/// pub fn refresh_forecast(ctx: Context) -> Result<()> { /* ... */ }
398///
399/// #[portaki_sdk::command(name = "submit", guest)]
400/// pub fn submit(ctx: Context, args: SubmitArgs) -> Result<()> { /* ... */ }
401/// ```
402///
403/// Same attribute and signature rules as [`query`]. Emits `command-{name}.json` →
404/// `manifest.commands[]`. Wasm `inventory` registration mirrors [`query`].
405///
406/// # Result
407///
408/// A command's `Ok(T)` is serialized and returned to its caller, like a query's — `()` answers
409/// `null`. A guest command's result reaches the booklet, which reads one key by convention:
410///
411/// - `guest_notice` — one sentence, **already translated** by the module (`t!`), that the booklet
412///   shows the traveller as a notice. Nothing else of the result is rendered; the rest is for the
413///   caller that reads it (`access-guide` reading a smart lock's credential).
414///
415/// Everything in the result crosses to the traveller's browser: return what they may see, nothing
416/// of the module's bookkeeping.
417#[proc_macro_attribute]
418pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
419    command::expand(attr, item)
420}
421
422/// Declares an email the command sends, so the manifest lists it without anyone writing JSON.
423///
424/// # Syntax
425///
426/// ```text
427/// #[portaki_sdk::email(id = "submitted", audience = EmailAudience::Host)]
428/// #[portaki_sdk::command(name = "submit", guest)]
429/// pub fn submit(ctx: Context, args: SubmitArgs) -> Result<()> { /* … host::email::send … */ }
430///
431/// #[portaki_sdk::email(
432///     id = "checkout-j2", audience = EmailAudience::Guest,
433///     trigger = EmailTrigger::RelativeToCheckOut, offset_days = 2, requires_guest_email,
434///     skip_when = SkipWhen::StayCancelled, description_key = "email.checkout-j2.description",
435/// )]
436/// #[portaki_sdk::command(name = "sendCheckoutFollowUp")]
437/// pub fn send_checkout_follow_up(ctx: Context) -> Result<()> { /* ... */ }
438/// ```
439///
440/// Goes **above** `#[command]` (or a `#[query]`, with a `trigger`), whose name it reads. `id` is
441/// the `email_id` given to `host::email::send`. Typed values — a string does not compile:
442/// `audience` an [`EmailAudience`], `trigger` an [`EmailTrigger`] (default `ModuleCommand`, sent
443/// when the command runs), `skip_when` a [`SkipWhen`] (repeatable). `offset_days` /
444/// `offset_hours` / `offset_minutes` (integers, one sign) and `at_local_time = "HH:MM"` time it
445/// against the stay. Bare flags: `dispatch_on_stay_created`, `catch_up_on_property_publish`,
446/// `catch_up_on_config_update`, `requires_guest_email`.
447///
448/// [`EmailAudience`]: https://docs.rs/portaki-sdk/latest/portaki_sdk/host/email/enum.EmailAudience.html
449/// [`EmailTrigger`]: https://docs.rs/portaki-sdk/latest/portaki_sdk/vocab/enum.EmailTrigger.html
450/// [`SkipWhen`]: https://docs.rs/portaki-sdk/latest/portaki_sdk/vocab/enum.SkipWhen.html
451///
452/// Emits `email-{id}.json` → `manifest.emails[]`, merged by `id` over `portaki.module.json`.
453#[proc_macro_attribute]
454pub fn email(attr: TokenStream, item: TokenStream) -> TokenStream {
455    email::expand(attr, item)
456}
457
458/// Declares a host dashboard entry that no surface renders.
459///
460/// # Syntax
461///
462/// ```text
463/// #[portaki_sdk::nav(
464///     placement = HostPlacement::WorkspaceTimelineTask, path = "tasks",
465///     label_key = "nav.tasks", icon = IconName::Sparkles,
466/// )]
467/// #[portaki_sdk::surface(host, id = "cleaning", …)]
468/// pub fn render_host_cleaning(ctx: HostContext) -> Surface { /* ... */ }
469/// ```
470///
471/// `placement` and `path` are required; `label_key`, `icon`, `design_id` as on `#[surface]`. Goes
472/// on any item, which it leaves untouched. Emits `nav-{path}_{placement}.json` →
473/// `hostSurfaces[]` of the catalogue.
474#[proc_macro_attribute]
475pub fn nav(attr: TokenStream, item: TokenStream) -> TokenStream {
476    nav::expand(attr, item)
477}
478
479/// Describes the arguments of a query or command, so tooling can offer a form for them.
480///
481/// # Syntax
482///
483/// ```text
484/// #[portaki_sdk::params]
485/// #[derive(Deserialize)]
486/// pub struct UpdateConfigArgs {
487///     /// Feeds to import.
488///     #[serde(default)]
489///     pub calendars: Vec<CalendarInput>,
490/// }
491///
492/// #[portaki_sdk::command(name = "updateConfig")]
493/// pub fn update_config(ctx: Context, args: UpdateConfigArgs) -> Result<()> { /* ... */ }
494/// ```
495///
496/// On a struct: each field with its wire name, type, whether it is required and its first doc
497/// paragraph — read the way serde reads it (`rename_all`, `rename`, `default`, `skip`,
498/// `flatten`, `Option<T>`). On an enum of unit variants: the values. A field whose type is
499/// another struct or enum refers to it by name; put `#[params]` on it too to describe it.
500///
501/// Emits `params-{TypeName}.json`. `portaki build` joins it with the operations whose handler
502/// takes that type (`args` in `query-*.json` / `command-*.json`) → `manifest.commands[].params`.
503/// On a config row type (`Vec<Step>` in `#[portaki_sdk::config]`), the same shape tells
504/// `portaki build` which sub-keys are translated and which identifies a row.
505/// Only a native-only registration for the conformance battery is generated — nothing in the Wasm
506/// binary; unknown serde attributes are ignored rather than rejected.
507#[proc_macro_attribute]
508pub fn params(attr: TokenStream, item: TokenStream) -> TokenStream {
509    params::expand(attr, item)
510}
511
512/// Declares the module's host configuration: the struct is the schema, the platform the store.
513///
514/// # Syntax
515///
516/// ```text
517/// #[portaki_sdk::config]
518/// #[derive(Debug, Clone, Default, Serialize, Deserialize)]
519/// pub struct Config {
520///     #[field(required, label = "config.ssid")]
521///     pub ssid: String,
522///     #[field(secret, recommended, label = "config.password")]
523///     pub password: String,
524///     #[field(structured, label = "config.contacts")]
525///     pub contacts: Vec<Contact>,
526///     pub hidden: bool,
527/// }
528///
529/// let config = Config::load(&ctx)?;
530/// ```
531///
532/// Goes **above** the derives. The struct needs `Default` and serde's `Serialize` /
533/// `Deserialize`; `#[serde(default)]` is added when missing — the platform stores only the keys
534/// the host filled in.
535///
536/// # `#[field(…)]`
537///
538/// | Key | |
539/// |-----|--|
540/// | `label = "…"` | **required** — i18n key, translated by `portaki build` into every bundle |
541/// | `description = "…"` | i18n key |
542/// | `required` | publication is blocked while it is empty |
543/// | `recommended` | a warning while it is empty, never a block |
544/// | `secret` | encrypted at rest, masked when read back |
545/// | `structured` | a list or object edited by the module's own host surface, never by a generic form |
546/// | `kind = "…"` | `text`, `textarea`, `url`, `number`, `secret`, `toggle`, `select`, `readonly`, `structured`, `localized` |
547/// | `options = ["…", …]` | the values of a `select`; each label is the i18n key `<label>.<value>` |
548/// | `item_id = "…"` | on a `structured` list: the row sub-key that identifies a row (default: a row field named `id`) |
549/// | `reveal(…)` | on a `secret` field: where the module shows its value — `guest_pre_arrival` (guest surfaces before the stay), `guest_stay` (guest surfaces during the stay), `arrival_email` (the `emailContext` answer); see below |
550///
551/// Without `kind`, the Rust type decides: `I18nText` → `localized`, `String` → `text`, `bool` →
552/// `toggle`, numbers → `number`, anything else → `structured` (`Option<T>` reads as `T`). The key
553/// is the serde name (`rename`, `rename_all`). A field without `#[field]` is not declared: the
554/// host never edits it.
555///
556/// # Revealed secrets
557///
558/// A secret never leaves the module, except where `reveal(…)` says so: a door code the booklet
559/// shows during the stay is `#[field(secret, reveal(guest_stay), label = "…")]`. The conformance
560/// battery seeds each secret with a sentinel and fails on any other output — host surfaces, the
561/// guest booklet after departure, logs, events, e-mails the module sends, ordinary query and
562/// command answers. Hosts and reviewers read the declaration; a reveal added since the previous
563/// stable is justified in the release notes like an added permission. When the value shows is
564/// still the module's call — see [`reveal`](../portaki_sdk/reveal/index.html) for the timing.
565///
566/// # Translated text
567///
568/// A `localized` field (`I18nText`) holds one text per language; the platform writes a host
569/// save into the host's language and keeps the others. Show it in the host form with
570/// `I18nText::host_value(&ctx)`.
571///
572/// A `structured` list whose rows hold `I18nText` fields gets
573/// `"item": { "id": "id", "localized": ["title", …] }`, so a save keeps the languages and the
574/// sub-keys the form did not send, row by row. The macro cannot see the row type's fields: put
575/// `#[portaki_sdk::params]` on it (`Vec<Step>` → `#[params] struct Step`), and `portaki build`
576/// fills `item` from it. Without it, the list has no `item` and a save replaces the rows whole.
577///
578/// ```text
579/// #[portaki_sdk::params]
580/// #[derive(Debug, Clone, Default, Serialize, Deserialize)]
581/// #[serde(default)]
582/// pub struct Step { pub id: String, pub title: I18nText, pub note: String }
583///
584/// #[portaki_sdk::config]
585/// #[derive(Debug, Clone, Default, Serialize, Deserialize)]
586/// pub struct Config {
587///     #[field(label = "config.welcome")]
588///     pub welcome: I18nText,        // "type": "localized"
589///     #[field(label = "config.steps")]
590///     pub steps: Vec<Step>,         // "item": { "id": "id", "localized": ["title"] }
591/// }
592/// ```
593///
594/// # Generated
595///
596/// - `Config::load(&Context) -> Result<Config>` — reads `context.moduleConfig`; when the runtime
597///   sends none at all, the KV key `config` (a config saved before the platform held it). An
598///   empty `moduleConfig` is an empty config, never the KV. A config that does not
599///   deserialize is an error, never a silent `Default`.
600/// - the host query `legacyConfig` — the raw JSON of the KV key `config`, or `null`, which the
601///   platform imports once.
602/// - the host command `legacyConfigAdopted` — called by the platform once that import is stored:
603///   deletes the KV key `config` and the keys of `legacy_keys`. Refused while no `moduleConfig`
604///   is sent (the import has not happened).
605///
606/// # `legacy_keys = ["texts/fr", "texts/en"]`
607///
608/// Other KV keys the old code kept its settings under, read by `legacy` or not: they go with
609/// `config` once the platform holds the config.
610///
611/// # `legacy = path::to::fn`
612///
613/// When the old KV blob does not have the declared keys — a key missing, a number where a
614/// string is declared, a nested object — `#[portaki_sdk::config(legacy = legacy::read)]` names a
615/// `fn(serde_json::Value) -> serde_json::Value` mapping the raw blob onto an object of the
616/// declared keys — or `fn(Value) -> Result<Value, E>` (`E: Display`) when a blob may not map:
617/// the error fails `legacyConfig`, which the platform retries, instead of a panic.
618/// `legacyConfig` answers its result (never called on `null`: nothing in KV), and `load` reads
619/// the KV through it while the platform does not hold the config yet.
620///
621/// ```text
622/// fn read(old: Value) -> Value {
623///     json!({ "radius_km": old["radius_km"].as_f64().map(|km| km.to_string()), "welcome": old["texts"]["welcome"] })
624/// }
625/// ```
626///
627/// # Emission
628///
629/// `config-{StructName}.json` → `config.fields[]` of the catalogue, labels translated;
630/// `query-legacyConfig.json` and `command-legacyConfigAdopted.json`.
631#[proc_macro_attribute]
632pub fn config(attr: TokenStream, item: TokenStream) -> TokenStream {
633    config::expand(attr, item)
634}
635
636/// Declares a subscription to a platform event type.
637///
638/// # Syntax
639///
640/// ```text
641/// #[portaki_sdk::event_handler(event_type = "core.booking.confirmed")]
642/// pub fn on_booking_confirmed(ctx: Context, event: BookingConfirmedEvent) -> Result<()> { /* ... */ }
643/// ```
644///
645/// `type = "…"` is accepted as an alias for `event_type`.
646///
647/// # Attributes
648///
649/// | Key | Required |
650/// |-----|----------|
651/// | `event_type = "…"` or `type = "…"` | yes |
652///
653/// Wrong key → **compile error** (`expected type = "…" or event_type = "…"`).
654///
655/// # Target item
656///
657/// Handler function; only the symbol name is emitted (`handler` field). No Wasm `inventory`
658/// registration — event delivery is orchestrator-driven using manifest metadata.
659///
660/// # Emission
661///
662/// `event_handler-{event_type}.json` → `manifest.events.subscribes[]`.
663#[proc_macro_attribute]
664pub fn event_handler(attr: TokenStream, item: TokenStream) -> TokenStream {
665    event_handler::expand(attr, item)
666}
667
668/// Declares a required or optional host capability dependency.
669///
670/// # Syntax
671///
672/// ```ignore
673/// use portaki_sdk::capability;
674///
675/// #[portaki_sdk::capability(required)]
676/// pub const STORAGE: &str = capability::core::STORAGE;
677///
678/// #[portaki_sdk::capability(
679///     optional,
680///     id = "external.open-weather.pool",
681///     purpose_key = "capability.openWeather.purpose",
682///     fallback_key = "capability.openWeather.fallback"
683/// )]
684/// pub const OPEN_WEATHER_POOL: &str = "external.open-weather.pool";
685///
686/// #[portaki_sdk::capability(provided, id = "amenities.provide", shares = ["reveal_policy"])]
687/// pub const AMENITIES: &str = "amenities.provide";
688///
689/// // A capability the module names itself: the provider says where to open it…
690/// #[portaki_sdk::capability(provided, id = "report.issue", path = "my-module/form")]
691/// pub const REPORT_ISSUE: &str = "report.issue";
692/// // …and a consumer depends on it, here without requiring it.
693/// #[portaki_sdk::capability(optional, id = "report.issue")]
694/// pub const ISSUE_REPORTING: &str = "report.issue";
695/// ```
696///
697/// # Attributes
698///
699/// | Key | Required | Notes |
700/// |-----|----------|-------|
701/// | `required`, `optional` or `provided` | one of | bare flags (no `=`), default is required |
702/// | `id = "…"` | if const value is not a string literal | capability id |
703/// | `purpose_key = "…"` | no | i18n key for optional capabilities |
704/// | `fallback_key = "…"` | no | i18n key when capability unavailable |
705/// | `shares = ["key", …]` | no, `provided` only | own config keys peers read through `host::module::list_by_capability` (`ModulePeer::shared`), published values only — `portaki check` refuses an unknown key, a secret field or a list with secret sub-keys |
706/// | `path = "…"` | no, `provided` only | one of the module's own guest surface paths, served to peers as `ModulePeer::path` — a consumer opens it with `Action::navigate` |
707/// | `commands = ["…", …]` | no, `provided` only | own commands a module that depends on the capability may call; none = reached by navigation only, the platform refuses every peer command |
708///
709/// An id no platform capability has, outside the platform namespaces, is **module-declared**
710/// (`portaki_sdk::capability::is_module_declared`): `provided` offers it to other modules,
711/// `required` / `optional` declares a dependency on it (`manifest.capabilities.depends[]`).
712///
713/// Capability id is taken from `id = "…"` or from a **string literal** const initializer. A const
714/// referencing another const (e.g. `capability::core::STORAGE`) without explicit `id` → **compile
715/// error** (`requires a string literal value or an explicit id = "…" attribute`).
716///
717/// Unknown keys → **compile error**.
718///
719/// # Host catalog
720///
721/// Ids should match `portaki_sdk::capability::{core,external,ai}::*` constants, which mirror the
722/// Java `Capability` enum. `portaki lint` rejects unknown ids via `capability::is_known`.
723///
724/// # Emission
725///
726/// `capability-{id}.json` → `manifest.capabilities.required[]`, `.optional[]` (with
727/// `purposeKey` / `fallbackKey` for optional entries) or `.provided[]` (with `.shares[id]`,
728/// `.paths[id]`, `.commands[id]`); a module-declared id goes to `.declared[]` or `.depends[]`.
729#[proc_macro_attribute]
730pub fn capability(attr: TokenStream, item: TokenStream) -> TokenStream {
731    capability::expand(attr, item)
732}
733
734/// Declares use of a **built-in** platform connector (manifest reference only).
735///
736/// # Syntax
737///
738/// ```ignore
739/// #[portaki_sdk::connector(builtin = "open-weather")]
740/// pub struct UsesOpenWeather;
741/// ```
742///
743/// # Attributes
744///
745/// | Key | Required |
746/// |-----|----------|
747/// | `builtin = "…"` | yes — connector id from the host connector catalog |
748///
749/// Wrong key → **compile error** (`expected builtin = "…"`).
750///
751/// Accepts any `syn::Item` (struct, const, etc.); the item is passed through unchanged.
752///
753/// # Emission
754///
755/// `connector_builtin-{builtin}.json` → `manifest.connectors.builtin[]`.
756#[proc_macro_attribute]
757pub fn connector(attr: TokenStream, item: TokenStream) -> TokenStream {
758    connector::expand_builtin(attr, item)
759}
760
761/// Declares a **custom** HTTP connector implemented by the module.
762///
763/// # Syntax
764///
765/// ```ignore
766/// #[portaki_sdk::custom_connector(
767///     id = "open-weather",
768///     display_name_key = "connector.openWeather.name",
769///     base_url = "https://api.openweathermap.org",
770///     credential_provider_id = "open-weather"
771/// )]
772/// pub struct ModuleOpenWeather;
773/// ```
774///
775/// # Attributes
776///
777/// | Key | Required |
778/// |-----|----------|
779/// | `id = "…"` | **yes** |
780/// | `display_name_key = "…"` | no |
781/// | `base_url = "…"` | no |
782/// | `credential_provider_id = "…"` | no |
783/// | `auth = "bearer" \| "query_appid" \| "query_key" \| "none"` | no |
784///
785/// Missing `id` → **compile error**. Unknown keys → **compile error**.
786///
787/// Must decorate a **struct** (metadata-only marker; runtime uses generic egress from manifest).
788///
789/// # Emission
790///
791/// `connector_custom-{id}.json` → `manifest.connectors.custom[]` (operations filled by
792/// [`connector_op`] emissions that follow in source order).
793#[proc_macro_attribute]
794pub fn custom_connector(attr: TokenStream, item: TokenStream) -> TokenStream {
795    connector::expand_custom(attr, item)
796}
797
798/// Declares the variables a module gives Portaki guest emails, per template, on the function
799/// that computes them.
800///
801/// # Syntax
802///
803/// ```ignore
804/// use portaki_sdk::prelude::*;
805///
806/// #[portaki_sdk::email_vars(StayLink | Arrival | ArrivalDay => [WifiName])]
807/// pub fn email_vars(ctx: Context, _args: EmailContextArgs) -> Result<EmailVars> {
808///     let config = Config::load(&ctx)?;
809///     Ok(EmailVars::new().with(EmailVar::WifiName, config.ssid))
810/// }
811/// ```
812///
813/// Templates are `EmailTemplateKey` variants, variables `EmailVar` variants (bare or by path);
814/// `A | B => [..]` shares one list. A variable its template does not render (`EmailVar::templates`)
815/// is a **compile error**, as are a template declared twice and a string instead of a variant.
816///
817/// To add a tile to a stay email rather than fill a variable of its body, see
818/// [`email_blocks`](macro@email_blocks) — a module declares one or the other, never both.
819///
820/// # Generated
821///
822/// - the host query `emailContext` the platform calls: the function runs only for a declared
823///   template; a variable it returns but did not declare for that template is an error; blank
824///   values are left out. Do not write an `emailContext` query next to it.
825/// - `emailVars` in the manifest: `{ "arrival": ["wifiName"], … }` — the platform merges the
826///   module's values into those templates, nothing else.
827///
828/// # Emission
829///
830/// `email_vars-emailContext.json` → `emailVars`; and `query-emailContext.json`.
831#[proc_macro_attribute]
832pub fn email_vars(attr: TokenStream, item: TokenStream) -> TokenStream {
833    email_vars::expand(attr, item)
834}
835
836/// Declares the **blocks** a module adds to Portaki stay emails, per email.
837///
838/// A short addition to an email Portaki owns — not an email the module writes
839/// ([`email`](macro@email) does that). A module declares either `#[email_vars]` or
840/// `#[email_blocks]`, never both: it has one `emailContext`, and data already rendered in the body
841/// of an email has no business being repeated in a block.
842///
843/// # Syntax
844///
845/// ```ignore
846/// use portaki_sdk::prelude::*;
847///
848/// #[portaki_sdk::email_blocks(Arrival | ArrivalDay => [Pairs])]
849/// pub fn email_blocks(ctx: Context, _args: EmailContextArgs) -> Result<EmailBlocks> {
850///     let config = Config::load(&ctx)?;
851///     Ok(EmailBlocks::new().with(
852///         EmailBlock::pairs("Parking")
853///             .title("Votre place")
854///             .row("Place", config.spot)
855///             .link("Voir le plan", "parking"),
856///     ))
857/// }
858/// ```
859///
860/// Emails are `EmailTemplateKey` variants, blocks `BlockType` variants (bare or by path);
861/// `A | B => [..]` shares one list. A kind its email does not render (`BlockType::templates`) is a
862/// **compile error**, as are an email declared twice and a string instead of a variant.
863///
864/// To fill a variable of an email's body rather than add a tile, see
865/// [`email_vars`](macro@email_vars).
866///
867/// # Generated
868///
869/// - the host query `emailContext` the platform calls: the function runs only for a declared
870///   email; a kind it returns but did not declare for that email is dropped, and one declared
871///   nowhere is an error. Do not write an `emailContext` query next to it.
872/// - `emailBlocks` in the manifest: `{ "arrival": ["pairs"], … }` — the platform calls the module
873///   for those emails, and for no other.
874///
875/// # Emission
876///
877/// `email_blocks-emailContext.json` → `emailBlocks`; and `query-emailContext.json`.
878#[proc_macro_attribute]
879pub fn email_blocks(attr: TokenStream, item: TokenStream) -> TokenStream {
880    email_blocks::expand(attr, item)
881}
882
883/// Marks a struct or enum as a Portaki **wire** JSON DTO (gateway / SDUI / events / email).
884///
885/// Serde defaults to Rust field names (`snake_case`). Portaki's platform wire format is
886/// camelCase. This attribute applies `#[serde(rename_all = "camelCase")]` and injects the
887/// usual derives when missing:
888///
889/// | Attribute | Derives added |
890/// |---|---|
891/// | `#[wire]` | `Debug`, `Clone`, `Serialize`, `Deserialize` |
892/// | `#[wire(serialize)]` | `Debug`, `Serialize` |
893/// | `#[wire(deserialize)]` | `Debug`, `Deserialize` |
894///
895/// Escape hatches: `no_debug`, `no_clone` (combinable, e.g. `#[wire(serialize, no_debug)]`).
896///
897/// Prefer this over repeating `#[serde(rename_all = "camelCase")]` and common derives on
898/// command/query args, responses, event payloads, and email-context types. Do **not** use it
899/// for KV/config blobs or entity rows that intentionally stay snake_case on disk.
900///
901/// # Syntax
902///
903/// ```ignore
904/// #[portaki_sdk::wire]
905/// pub struct SubmitArgs {
906///     pub item_description: String,
907/// }
908///
909/// // Serialize-only event payload:
910/// #[portaki_sdk::wire(serialize)]
911/// struct SubmittedPayload {
912///     property_id: uuid::Uuid,
913/// }
914///
915/// // Keep PartialEq / Default yourself; wire covers Debug+Clone+serde:
916/// #[portaki_sdk::wire]
917/// #[derive(PartialEq, Eq, Default)]
918/// pub struct EmailContextArgs { /* … */ }
919/// ```
920///
921/// Existing `Serialize` / `Deserialize` on the item are left as-is (wire still adds `Debug` /
922/// `Clone` when appropriate). Existing `#[serde(…)]` container attrs are kept — a separate
923/// `rename_all = "camelCase"` is added when missing (serde merges multiple container attributes).
924#[proc_macro_attribute]
925pub fn wire(attr: TokenStream, item: TokenStream) -> TokenStream {
926    wire::expand(attr, item)
927}
928
929/// Declares one HTTP operation on the most recently emitted custom connector, or a validator stub.
930///
931/// # Syntax
932///
933/// ```ignore
934/// impl ModuleOpenWeather {
935///     #[portaki_sdk::connector_op(method = "GET", path = "/data/2.5/weather")]
936///     pub fn current() {}
937///
938///     #[portaki_sdk::connector_op(method = "GET", path = "/data/2.5/forecast", cache = "5m")]
939///     pub fn forecast() {}
940/// }
941///
942/// // Validator-only stub (no method/path):
943/// #[portaki_sdk::connector_op(validator)]
944/// pub fn validate_credentials() {}
945/// ```
946///
947/// # Attributes
948///
949/// | Key | Required | Notes |
950/// |-----|----------|-------|
951/// | `method = "…"` | for HTTP ops | e.g. `"GET"` |
952/// | `path = "…"` | for HTTP ops | URL path on `base_url` |
953/// | `cache = "…"` | no | cache hint (opaque string) |
954/// | `validator` | bare flag | sets `"validator": true`, ignores method/path |
955///
956/// Unknown keys → **compile error**. Empty attribute list → HTTP op with null method/path.
957///
958/// `portaki build` appends each op to the **last** `connector_custom` entry's `operations` array,
959/// using the Rust `fn` symbol as operation `id`.
960///
961/// # Emission
962///
963/// `connector_op-{fn_name}.json` with `{ fn, method, path, cache, validator }`.
964#[proc_macro_attribute]
965pub fn connector_op(attr: TokenStream, item: TokenStream) -> TokenStream {
966    connector::expand_op(attr, item)
967}
968
969/// `extern crate <this package's lib> as _;` — hidden, for `portaki_test_utils::conformance!`.
970///
971/// Expanded inside an integration test of a module package, it names the package's library so the
972/// test binary links it, and with it the handler declarations the conformance battery reads. The
973/// library name comes from `[lib] name` in `Cargo.toml`, else the package name with `-` → `_`.
974/// An explicit identifier (`link_module_crate!(my_lib)`) wins over both.
975#[doc(hidden)]
976#[proc_macro]
977pub fn link_module_crate(input: TokenStream) -> TokenStream {
978    link::expand(input)
979}
980
981/// A unit enum a declared field picks from (`unstable`). `label = "rule.status"`: a value's label
982/// is the bundle key `rule.status.<value>`; `#[icon(IconName::X)]` on a variant gives its icon.
983/// Writes the derives, `portaki_sdk::resource::Choice`, and the values for the manifest.
984#[proc_macro_attribute]
985pub fn choice(attr: TokenStream, item: TokenStream) -> TokenStream {
986    resource::expand_choice(attr, item)
987}
988
989/// A row type of a declared collection (`unstable`), or with `meta` its settings. Each
990/// `#[field(label = "…", required, max_chars = N, between(a, b), description = "…")]` is declared:
991/// kind from the Rust type (`I18nText`, `String`, `bool`, numbers, a `#[choice]` enum;
992/// `kind = "time_range"` on a `String`). Adds `id`, the derives, `#[serde(default)]`, and
993/// `portaki_sdk::resource::Item` (or `Meta`). `key = "title"`: the natural key an import dedupes on.
994#[proc_macro_attribute]
995pub fn item(attr: TokenStream, item: TokenStream) -> TokenStream {
996    resource::expand_item(attr, item)
997}
998
999/// A collection the SDK stores (`unstable`): `#[collection(name = "rules", item = Rule,
1000/// meta = Display, max = 30, import)]` on a unit struct. Generates `load` / `save`, the
1001/// `updateConfig` command (host form), `importRows` (with `import`), the host query `readRows`
1002/// (with `read`: the rows as declared, for the platform's guest assistant — only on rows the guest
1003/// sees, never on a record), `publishReadiness` (unless `readiness = false`), the
1004/// `PortakiResource` entity and the manifest's `resources[]` entry.
1005#[proc_macro_attribute]
1006pub fn collection(attr: TokenStream, item: TokenStream) -> TokenStream {
1007    resource::expand_collection(attr, item)
1008}
1009
1010/// A record the SDK stores (`unstable`): what a guest deposits during a stay and the host follows.
1011/// `#[record(name = "reports", item = Report, status = ReportStatus, due_hours = 24,
1012/// task_title = "…", task_done = "…", hooks)]` on a unit struct. Generates `list` / `for_stay` /
1013/// `get`, the commands `submit` (guest), `add`, `setStatus`, `note`, the query `listForStay`, the
1014/// timeline contract when `due_hours` is set, and the entity. With `hooks`, the module implements
1015/// `portaki_sdk::resource::RecordHooks` (guard, on_created, on_note).
1016#[proc_macro_attribute]
1017pub fn record(attr: TokenStream, item: TokenStream) -> TokenStream {
1018    resource::expand_record(attr, item)
1019}